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.
Related
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.
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.
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
}
For reference, this is the JSON I'm working with: http://goo.gl/xxHci0
In regular JavaScript, using the code below works fine and I can manipulate it easily:
var info = JSON.parse(document.getElementsByTagName("pre")[0].innerHTML);
alert(info[0]["AssetId"]);
But I'm working on a jQuery version of the same code to avoid using methods like iFrames to get this data. My jQuery function is:
$.get (
page,
function parse(data) {
var r = $.parseJSON(data);
alert(r[0]["AssetId"]);
}
);
I found ways to convert the JSON using jQuery, but I'm having trouble finding where the JSON code is that needs to be converted.
Provided that the response from the server is a valid string representation of a JSON object, you'll be able to specify the dataType for the get() request. You could do something like this:
$.get( page, function( data ) {
alert( data[0]["AssetId"] );
}, "json" ); // <-- here is the dataType
With the correct dataType set, you will not need to manually parse the data, it will arrive in your callback function as a JSON object.
References:
$.get()
jQuery.get( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )
You can use getJson. This converts your JSON string to a JavaScript object.
I threw JSFiddle together for you using the facebook graph api:
http://jsfiddle.net/J4LCX/
$.getJSON( "http://graph.facebook.com/spikeh/",
function( data ) {
alert(data.id);
});
Alternatively, to fix your code, just reference the object's id directly:
$.get (
"http://graph.facebook.com/spikeh/",
function parse(data) {
alert(data.id);
}
);
JsFiddle: http://jsfiddle.net/LBy9y/
I have a backbone object that I'm calling save on. How do I know what comes back in the ajax call. Looking at the code for the project I got put on, I see some people just have a generic
success: function (data) {
console.log(data);
Then other times, I see:
success: function (library, response) {
console.log(library);
console.log(response)
I'm confused on how you would know you would have I presume a library or response object, vs a general data. When I look at the second example, I am looking at the output of
console.log(response);
and I see response has three attributes:
Notifications
Response
ResponseStatus
Response itself looks like Object {Id="12345", href="the/href", Name="asdf"}
So it looks like a Javascript object to me, but then when I try to do
console.log(response.Name);
I always get undefined even though I can see the value.
So I'm trying to understand how the callback in an ajax calls. Like when you can use an actual library object, response object, vs a data object, and how I can go about parsing the results properly. Thanks in advance!
You should either
$.ajax({
dataType : 'json',
..
})
or
$.ajax({
..
success : function(data) {
var result = JSON.parse(data);
});
Then I think you will be good