JQuery JSONP: One request multiple callbacks - javascript

The contents of my jsonp url http://host/dummyJsonp?callback=myFunction is:
myFunction("a");
myFunction("b");
myFunction("c");
but JQuery success function is called just once when I run this code:
$.ajax({
url: "http://host/dummyJsonp",
jsonp: "myFunction",
dataType: "jsonp",
success: function( response ) {
console.log( response ); // server response
}
});
Does JQuery supports multiple callbacks in one request?

It is not possible to call a callback multiple times with different arguments. Since the ajax call happens just once, there only is one response. That means you can not call multiple callbacks with different arguments.
If you want the response to be different, you have to make an ajax call three times and each time your server has to give you a different response.
The easiest workaround to achieve your desired result is to put all your responses on the serverside in a json object like this:
{
a:'a',
b:'b',
c:'c'
}
And in your success function you simply use the results you need:
success: function( response ) {
console.log( response.a ); // server response
console.log( response.b ); // server response
console.log( response.c ); // server response
}

Related

Error when storing JSON after an ajax request (jQuery)

I'm quite new to JavaScript/jQuery so please bear with. I have been trying to store the resulting JSON after an ajax request so I can use the login info from it later in my program. I get an error stating that "Data" is undefined. Here is the problematic code:
function LOGIN(){
$.ajax({
url: 'https://.......&JSONP=Data&.........',
success: function Success(){
var SessionData = Data();
(FunctionThatParsesJSON);
}
})
}
I have checked the URL manually and it works fine (including) being wrapped in the "Data" function. From what I have found online, this may be something to do with ajax been asynchronous. Can anyone suggest a way of storing the JSON so that I can use it later?
Try something like the following;
function LOGIN(){
$.ajax({
url: 'https://.......&JSONP=Data&.........',
success: function Success(data){
functionToProcessData(data)
})
}
When making your ajax call, you can handle the response given by assigning a parameter to the function. In the case above, I have passed the 'data' parameter to the success function allowing me to then use it in further functions (as demonstrated by 'functionToProcessData(data)'.
The response from ajax call is captured in success handler, in this case 'data'.
Check below code:
success: function(data){
var SessionData = data.VariableName;
// Here goes the remaining code.
}
})
Since people ask about explanation, thus putting few words:
When we do $.ajax, javascript does the async ajax call to the URL to fetch the data from server. We can provide callback function to the "success" property of the $.ajax. When your ajax request completed successfully, it will invoke registered success callback function. The first parameter to this function will be data came from server as response to your request.
success: function ( data ) {
console.log( data );
},
Hope this helps.
Internally everything uses promises. You can explore more on promises:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
Apparently you are using JSONP, so your code should look like this:
$.ajax({
url: 'https://.......&JSONP=Data&.........',
dataType:"jsonp",
success: function (data){
(no need to parse data);
}
});
Another option:
$.ajax({
url: 'https://.......&JSONP=Data&.........',
dataType:"jsonp"
})
.done(function (data){
(no need to parse data);
});
See the documentation and examples for more details.
success: function (data, textStatus, jqXHR){
these are the arguments which get passed to the success function. data would be the json returned.

Restrictions of Multiple AJAX Calls?

Context:
I have a javascript file, within i have an AJAX function calling a php file returning the data and performing a function with it(an sql query returning records for a set date, then plotting it on a map using the google maps API). Lets call this Data A
Question:
What i need is to be able to get the next days data and storing it in an array (Lets call it Data B) and comparing it with the first set of data(Data A).
From my understanding i need another ajax call within this one, iv tried it but it seems i cannot get the data, i may have a misunderstanding of the core workings of ajax. For example:
var data_a;
var data_b;
$.ajax({
type: "POST",
url: scriptday,
data: $("#dayForm").serialize(),
error: function( data ) {
console.log("Error: "+ data );
},
success: function( json ) {
data_a = json
//start of inner ajax call
$.ajax({
type: "POST",
url: scriptday2,
data: $("#dayForm").serialize(),
error: function( data ) {
console.log("Error: "+ data );
},
success: function( json ) {
data_b = json
// access data_a here
}
}
});
//end of inner ajax call
}
});
EDIT:
Correct way of doing this was to store inner ajax call in a function that takes data_a inside.
function innerAjax(data_a){
$.ajax({
.....
//data_a can now be used here
})
}
and to call it inside the first ajax as
innerAjax(data_a);
this way using AJAX in a synchronous way :)
thanks to those who contributed!
No, restrictions of multiple AJAX calls do not exist, if you use async ajax (and looks like you do).
For you problem - perhaps you need to wait correctly for result of both ajax calls, to store the results and then process them.

jquery jsonp request is not getting a callback parameter added properly

I have an object containing UPC codes and I'm iterating through them, hitting a server for product info on each via jsonp requests:
$.each( obj, function( key, val ){
var requestUrl = 'https://domain.com/products/' + val.upcCode + '/prices';
$.ajax({
url : requestUrl,
dataType : 'jsonp',
success : function(responseData){
console.log( responseData );
}
});
});
This works except for that the first request is not getting a callback parameter added properly. All the other requests get
&callback=jQuery111108732157719514818_1411587984724&_=1411587984725
(or similar) appended but the first is only getting
&true=jsonp&_=1411587984723
So the server doesn't get a callback and just returns json. Has anybody seen jQuery doing this?
The answer appears to be that I had made a separate, earlier jsonp request wherein I manually set the jsonpCallback value to 'jsonp':
$.ajax({
url : '/logic/under29.js',
dataType : 'jsonp',
jsonpCallback : 'jsonp',
success : function(response){
console.log( response);
logic = response;
}
});
Name that callback anything else and the second jsonp request works. Name it "jsonp" and you get the problem described above.
(jquery 1.11.1)

How to retrieve response from xmlhttprequest? (screenshots)

I've got this code of autocomplete jqueryUI:
.autocomplete({
source: function( request, response ) {
var results = $.getJSON( url, {
term: extractLast( request.term )
}, response );
console.log(results);
},...
The console.log of the var 'results' looks like this:
I need to extract the response or responseText field to test if is empty and popup an error with no matches found. But nothing works to retrieve that field:
results.response
results.getResponse()
results.getResponseHeader()
Neither of these methods works. Thanks
Both of the answers work: It returns my response properly. I can test it.. but it break my autocomplete. I am still looking into it.
The third variation, the callback, provides the most flexibility, and can be used to connect any data source to Autocomplete. The callback gets two arguments:
A request object, with a single property called "term", which refers
to the value currently in the text input. For example, when the user
entered "new yo" in a city field, the Autocomplete term will equal
"new yo".
A response callback, which expects a single argument to
contain the data to suggest to the user. This data should be filtered
based on the provided term, and can be in any of the formats described
above for simple local data (String-Array or Object-Array with
label/value/both properties). It's important when providing a custom
source callback to handle errors during the request. You must always
call the response callback even if you encounter an error. This
ensures that the widget always has the correct state.
This is the jquery UI autocomplete documentation about source by callback function. I can't understand why the new version is not working
if you want the response you probably want to do
var results = $.getJSON( url, {
term: extractLast( request.term )
}, function(response) {
console.log(response);
});
.getJSON is asynchronous and will return the result in a callback function.
Hence, change your code to something like this:
.autocomplete({
source: function( request, response ) {
var results = $.getJSON( url, {
term: extractLast( request.term )
}, function( results ) {
console.log( results );
});
}, ...
);
If you by some reason need to do a synchronous call you can use jQuery's .ajax function instead with the async option set to false.
You need a success callback when performing jQuery's ajax functions. You should read the documentation.

What/when does a call to the jQuery AJAX method return?

A little background:
I am trying to implement and AJAX powered SlickGrid. There isn't much documentation so I used this example as a base.
In this example there is the following code that hits the desired web service to get the data:
req = $.jsonp({
url: url,
callbackParameter: "callback",
cache: true, // Digg doesn't accept the autogenerated cachebuster param
success: onSuccess,
error: function(){
onError(fromPage, toPage)
}
});
req.fromPage = fromPage;
req.toPage = toPage;
I'm not exactly sure what jsonp does but from what i've read it appears to be very similar to the ajax method in jQuery except it returns json and allows cross domain requests. The webservice that I happen to be calling only returns XML so I changed this chunk of code to:
req = $.ajax({
url: "/_vti_bin/lists.asmx",
type: "POST",
dataType: "xml",
data: xmlData,
complete: onSuccess,
error: function (xhr, ajaxOptions, thrownError) {
alert("error: " + xhr.statusText);
alert(thrownError);
},
contentType: "text/xml; charset=\"utf-8\""
});
req.fromPage = fromPage;
req.toPage = toPage;
My issue is that my page errors out at req.fromPage = fromPage; because req is null.
Am I wrong to think that I can just replace my jsonp call with a call to the ajax method? Is req just not set because my ajax call hasn't finished by the time that code is executed? How can I get around either of these issues?
If I comment out the last two lines and hard-code those values elsewhere everything runs fine.
Am I wrong to think that I can just replace my jsonp call with a call to the ajax method?
No, that should work just fine.
Is req just not set because my ajax call hasn't finished by the time that code is executed?
Yes, that is correct.
The ajax methods starts the request and returns immediately. If you want to do something after the response has arrived you should do that in the success event handler.
You might actually want to use the success event instead of the complete event, as the complete event happens even if there is an error.
You could specify async: false, in your settings to make the ajax call wait for the response, but that means that the browser freezes while it's waiting.
As Guffa stated, $.ajax() works asynchronically. Thus, you have to specify a callback that will be called when the request has returned a response, rather than to just use whatever $.ajax() returns.
There are a couple of different callback methods you can specify:
complete - runs when you recieve a response, regardless of its status.
success - runs when you recieve a response with a successful status code (usually 200).
error - runs when you recieve a response with an error code (for example 404 or 500).
To do something with the response body after a successful request, you should do something like
$.ajax({
...
success: function(body) {
alert('This is the method body:' + body);
}
});
Read up in the documentation on the different methods to see what more parameters you can use.

Categories