A comparison between Angular JSON and JSONP $promise

When making a JSON call from my controller.js:

$scope.userInvestors = userInvestors.query({UserID:$scope.user.uid}, 
  function(userInvestors) {
    console.log("yep yer here");
}

Using this $resource:

factory('userInvestors', function($resource){
  return $resource('http://wherevertheserveris/Rest/userInvestors.php', {}, {
    query: {method:'GET', params:{}, isArray:true}
  });
})

The console gets updated as expected with: yep yer here.

If I switch the request to a JSONP request:

$scope.userInvestors = userInvestors.query({UserID:$scope.user.uid, 
  callback: 'JSON_CALLBACK'}, function(userInvestors) {
    console.log("but are you here?");
}

Along with the following resource:

factory('userInvestors', function($resource){
  return $resource('http://wherevertheserveris/Rest/userInvestors.php', {}, {
    query: {method:'JSONP', params:{}, isArray:true}

  });
})

No output is shown in the console even though the call was successful and data was retrieved. How can I make my JSONP log statement print?

ANSWER:

Thanks for all the answers provided below. It turns out that I needed to format the return response from the API correctly.

Instead of returning NULL via PHP like this: print $callback."null";

I should have returned an empty array inside a function wrapper or any other properly formatted JSONP response. In my case, it should be: print $callback."([])";

Answer №1

To start off, it is important to ensure the data format being returned from the backend. A JSONP response consists of JSON data wrapped around a function call.

Here is an example of my PHP API implementation:

<?php
    $callback = isset($_GET['callback'])?$_GET['callback']:'JSON_CALLBACK';

    $array = array("name"=>"test","email"=>"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="552130262115313c323c2134397b363a38">[email protected]</a>");

    echo $callback."(".json_encode($array).")";
?>

Make sure to assign the proper name to the callback parameter and customize the method property 'callback' when utilizing the ngResource module.

For Angular implementation:

angular.module("app",['ngResource'])
.controller("myCtrl",function($scope,userInvertors){
    $scope.jsonpTest = function(){
        $scope.result = userInvertors.query(function(response){
            console.log(response);
        });
    }
})
.factory("userInvertors",function($resource){
    return $resource('http://your.domain.com/API/getUser/123',{},{
        query:{
            method:'JSONP',
            params:{callback:"JSON_CALLBACK"},
            callback:"JSON_CALLBACK"
        }
    });
});

HTML Structure:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ngResource</title>
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular-resource.js"></script>
        <script src="js/ngResource.js"></script>
</head>
<body ng-app="app">
    <div ng-controller="myCtrl">
        <input type="button" ng-click="jsonpTest()" value="JSONP"/>
    </div>
</body>
</html>

Screenshot:

API response:

Obtain the response:

We hope this information proves useful for you.

Answer №2

Ensure to complete these 2 tasks:
1. When using the JSONP userInvestors service, include the callback parameter with a value of 'JSON_CALLBACK';
2. In your userInvestors.php file, access the callback request variable and utilize its value for formulating the response:

PHP CODE:

$callback = $_GET['callback'];
$jsonStr = "...";
header("Content-type: text/javascript");

echo $callback."(".jsonStr.")";

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for hiding the bottom bar within a stackNavigator in react-navigation

I am facing a challenge with my navigation setup. I have a simple createBottomTabNavigator where one of the tabs is a createStackNavigator. Within this stack, I have a screen that I want to overlap the tab bar. I attempted to use tabBarVisible: false on th ...

Drawing mysteriously disappeared from the canvas

Having trouble with my JavaScript code. I created a function called drawLine to trace lines on a canvas from one point (x,y) to another point (xdest, ydest). The first few lines display correctly but after the fourth line, it stops working and I can't ...

Pending status persists for Axios post request

Here is a straightforward example of a POST request using Axios within Vue: import axios from 'axios' export default { name: 'HelloWorld', props: { msg: String }, mounted () { const code = 'test&apo ...

How to iterate through a "for" loop in JavaScript using Python-Selenium?

In my current project, I am utilizing Javascript to gather data from an HTML page using Selenium. However, I am facing a challenge where I am unable to execute the multi-line for loop in the Javascript portion on my computer through Selenium with Python (S ...

What is the method to utilize global mixin methods within a TypeScript Vue component?

I am currently developing a Vue application using TypeScript. I have created a mixin (which can be found in global.mixin.js) and registered it using Vue.mixin() (as shown in main.ts). Content of global.mixin.js: import { mathHttp, engHttp } from '@/ ...

Receiving an alert in VSCode regarding the usage of CharAt function in conjunction with Vuejs

While attempting to extract the first character of a computed property, I utilized the charAt() function. Despite the fact that it is functioning correctly, I am receiving a warning from VSCode indicating that it is not the correct usage. computed: { ...m ...

Steps to modify the servletRequest's content length within a filter

My main objective is to secure the POST body requests sent from my web application to my service by encrypting them. This encryption process takes place within a filter in my system. However, I've encountered an issue related to content length. When ...

Issues with AngularJS version 1.8.0 and the ng-selected option functionality not functioning as

I recently updated the AngularJs version from 1.4.8 to 1.8.0 and encountered an issue with ng-selected on a select element that requires a default value. Can anyone provide guidance on how to set ng-selected in version 1.8.0? (the code utilizes ng-model) ...

Trouble arises when the properties of this.props are supposed to exist, yet they are not

Wow, what a name. I am struggling to come up with a better title given my current state. The problem at hand is as follows: When using React, I set the state to null during componentWillMount. This state is then updated after data is fetched from a serve ...

Stopping animation in jQuery function before it starts

After each update, a function is executed: window.ticker.client.updateData = function (data) { try { if (viewModelOrder.selectedInstrument == data.symbol) { viewModelOrder.updatePrice(data.ask.to ...

Application experienced a failure while retrieving a string from a Dictionary in Swift

After converting a JSON to a Dictionary, I retrieved some Strings using the code snippet below: title = json?.objectForKey("Titel_Live") as! String However, there are instances where my app crashes. Despite not being able to replicate this issue, I have ...

I would like to know the best approach to utilizing a PHP array or JSON response within JavaScript

Let me present my workflow briefly. While I initiate an Ajax call from the index.phtml file, the Ajax response is as follows: Array ( [Data] => Array ( [0] => Array ( [PlayerId] => 20150 ...

Why is "undefined" being used to alert an ajax call response?

I am encountering an issue with a returned value from an AJAX request. The web method being referenced returns a boolean value of true or false. However, when attempting to access this value outside the AJAX method, I am receiving an "undefined" message :? ...

Chai-http does not execute async functions on the server during testing

In my app.js file, there is a function that I am using: let memoryCache = require('./lib/memoryCache'); memoryCache.init().then(() => { console.log("Configuration loaded on app start", JSON.stringify(memoryCache.getCache())); }); app.use( ...

What is the solution for integrating formwizard with steps inside directives using Angular UI and jQuery passthrough?

After successfully implementing the jquery passthrough in angular using the form wizard, I've encountered a new issue. It seems that the jquery passthrough doesn't function properly when the steps within the formwizard are encapsulated inside dir ...

Changes to a key value are not reflected in the array of objects

When making changes to input fields within an array of records that include Date and Text fields in a table, the data is not updating as expected. I am encountering issues where changing the Date input results in undefined Text values, and vice versa. My g ...

Tips for modifying plain text data based on JSON responses in AngularJS

When receiving JSON data in the response, I would like to change the values to human-readable terms. For example, 0: registered, 1: connected, 2: disconnected, 3: busy. Although I can display the data as it comes in the response, I need to modify it based ...

Quick tip on closing an Angular-ui modal from a separate controller

I am currently using Angular-ui to display a modal with a form inside. Here is the code snippet: app.controller('NewCaseModalCtrl', ['$http', '$scope','$modal', function ($http, $scope, $modal, $log) { $scope.ite ...

Unseen columns within an HTML table are also being included in the export

In my HTML table, I have included a drop-down feature for users to select the row they want to view, along with an export button that allows them to save the data in Excel format. During the exporting process, I encountered an issue where hidden rows were ...

ng-repeat hide all elements except the first one

Hello there! I'm currently working on rendering a form based on an API call. Using a couple of filters, I am able to hide all elements that have 'id' in the title and which equal 0. However, I do need to display the initial element Id. I tho ...