I've seen these two kinds of ajax calls, what is the main functional difference between them?
$.ajax({
url: '',
type: 'post',
data: {},
success: function (data) {
alert(data);
}
});
and
$.ajax({
url: '',
type: 'post',
data: {}
}).success( function (data) {
alert(data);
});
The first adds a success callback to the ajax method.
The second adds a success callback to the promise interface that $.ajax returns.
I actually don’t think there is a success method on the deferred object that $.ajax returns (maybe there is a legacy in an older version), it should be done according to the docs:
$.ajax({
url: '',
type: 'post',
data: {}
}).done( function (data) {
alert(data);
});
There is no difference between those 2 snippets. Even though you are using the option property success internally it is getting added to the promise callback list of the ajax request.
If you look at the attached image you can see that the value passed to success, error and complete are passed back to the jqXHR object's callback methods
Related
I have the following JQuery Ajax method:
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData,
dataType: 'json',
success: function() {
$('#test').html("testing123");
},
});
As it is written, the success function does not fire.
However, if I predefine the function somewhere else and then call it like this:
success: testFunction()
OR
success: $('#test').html("testing123")
then it works.
What am I missing?
The solutions that you think you have working are actually only illusions of so. They are actually not being called on success, but right when you declare it. This leads me to think that your ajax call is not returning success.
The right way to predefine a function and pass it would be
success: testFunction
If you do success: testFunction(), you are running that function right away when parsing the code and not when the callback from your ajax fires. This is the same case with
success: $('#test').html("testing123")
and is actually equivalent if you called testFunction() right after your ajax call.
I know this question hast probably been asked a thousand times, but i cannot seem to find the answer. I want result to be the data returned from the ajax-request, which should be a json-data array (the result of console.log(data)).
var result = $.ajax({
type: 'GET',
url: dataPath,
dataType: 'json',
success: function(data) {
console.log(data)
},
error: function(){
//alert("damn");
},
data: {},
aync: false
});
console.log(result);
However, console.log(result); will return some strange object, which I don't know how to handle. Why isn't result = data ?
Typo.
Change this:
aync: false
to:
async: false
And the ajax method still returns the jqXHR object doing the request, not the result. Use the data parameter in the success call and store it somewhere.
First of all remove the aync: false from your code. It should be spelled async: false but you don't need it to achieve your goal and what it actually does is block the entire browser's user interface resulting in a terrible user experience. Remember that "A" in AJAX means Asynchronous.
The result of an $.ajax() call is a promise which is not the same as your data, but it can still be useful to get to your data. You just need to use it in a certain way.
Try changing:
console.log(result);
to:
result.done(function (data) {
console.log(data);
});
or:
result.done(function (data) {
console.dir(data);
});
or even this might work - untested:
result.done(console.dir);
See this answer for a better explanation.
Initialize result inside success function.
var result;
$.ajax({
type: 'GET',
url: dataPath,
dataType: 'json',
success: function(data) {
result = data;
console.log(data)
},
error: function(){
//alert("damn");
},
data: {},
async: false
});
console.log(result);
There is a small spelling mistake aync: false should read async: false assuming of course that you require the request to run synchronously i.e. for the remainder of your code to wait for this result.
I think that the main issue here is that the result you are trying to output to the console is not being referenced by the ajax request.
It is entirely your choice how you reference the data returned by the ajax request, you chose the word data this could just as easily have been result or json_Data or return_Data or ....
Hence to send the result of the ajax request to the console I would suggest:
var result = $.ajax({
type: 'GET',
url: dataPath,
dataType: 'json',
success: function(result) {
console.log(result)
},
error: function(){
//alert("damn");
},
data: {},
async: false
});
You mentioned console.log(result) returns a strange object, actually this strange object is known as xhr (XMLHttpRequest) object.
Since the call is syncronous because of async: false so it's easy to get the returned data like
var result = $.ajax({...}); // get the xhr object in to result
console.log(result.responseText); // xhr object has a "responseText" property
As because result.responseText will be available only after the request completes and there is no chance to execute this console.log(result.responseText); because of async:false, before the request completes because a syncronous ajax request hangs on everything before it finish the request.
In your success callback data will be an object because of dataType: 'json' but outside of success callback, i.e. console.log(result.responseText); will be only text so to use it as an object you have to convert it to an object using $.parseJSON(result.responseText).
UPDATE Following #Ryan Olds suggestion to include the setTimeout in the callback, I must clarify that in my production code I'm calling multiple urls to get json data from several sites. (Have updated JavaScript code below).
Is it only possible to have multiple timeouts scattered throughout this function?
I have a self-invoking updateFunction as follows:
(function update() {
$.ajax({
type: 'GET',
url: "http://myexample.com/jsondata",
dataType: 'json',
success: function (data) {
// do some callback stuff
},
async: false
});
$.ajax({
type: 'GET',
url: "http://myexample2.com/jsondata2",
dataType: 'json',
success: function (data) {
// do some further callback stuff
},
async: false
});
setTimeout(update, 2000);
})();
What I expected this code to do
I hoped that this function would go off to the target URL and wait for the result, then deal with the success callback. Then (and only then) would it fall through to set a 2 second timeout to call the function again.
What appears to be happening instead
Instead, the GET request codes out, and before the response has been dealt with, the timeout has already been set.
What am I missing? How can I make this entirely synchronous?
If I were you, I'd make use of jQuery's support for deferred action.
(function update() {
$.when($.ajax({
type: 'GET',
url: "http://myexample.com/jsondata",
dataType: 'json',
success: function (data) {
// do some callback stuff
}
}), $.ajax({
type: 'GET',
url: "http://myexample2.com/jsondata2",
dataType: 'json',
success: function (data) {
// do some further callback stuff
}
}), $.ajax({
// more requests as you like
})).then(function() {
// when all the requests are complete
setTimeout(update, 2000);
});
}());
Much nicer, IMHO, than mucking around with synchronous requests. Indeed, if the requests are cross-domain, this is pretty much your only option.
See
$.when
deferred.then
Move the timeout in to the success callback. The request is synchronous, it would appear the the callback is not.
I would modify the setup like so:
function update() {
$.ajax({
type: 'GET',
url: "http://myexample.com/jsondata",
dataType: 'json',
success: function (data) {
// do some callback stuff
},
async: false
});
$.ajax({
type: 'GET',
url: "http://myexample2.com/jsondata2",
dataType: 'json',
success: function (data) {
// do some further callback stuff
},
async: false
});
}
setInterval(update, 2000);
update(); // only necessary if you can't wait 2 seconds before 1st load.
You cannot make it entirely synchronous because you're setting up calls to alternate domains. That's done (internal to jQuery) by creating <script> tags and adding them to the document. Browsers perform those calls asynchronously, and that's that. You can't make ordinary xhr requests to domains different from your own.
I can't imagine why you'd want something like that to be synchronous, especially since you're doing many of these operations.
I don't think async: false works on cross domain requests.
From the docs:
async Boolean
Default: true
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
In any case, maybe you can set some conditionals to fire the requests in the order that you want.
I dont know how write this script. I need load results with some URL (eg: localhost/index.php?action=get&type=29) and this result to give a variable for further processing. I need create this on Jquery. Thanks.
There are features in jQuery that can be used, you have either a quick load using the simple .load() function that will parse the HTML into an element. Usage:
$('#element').load('http://www.urlgoeshere.com/');
With processing events with AJAX with further writing options, you have many options to choose from:
http://api.jquery.com/jQuery.ajax/
These options below are using the .ajax() function but makes the writing easier:
http://api.jquery.com/jQuery.get/
http://api.jquery.com/jQuery.post/
EDIT: With your "refresh", you can use the setTimeout function to repeat the ajax call:
setTimeout(function()
{
$.ajax({
type: "POST",
url: "some.php",
data: "action=get&type=29",
success: function(arg){
// do something
}
});
}, 1000); // This will "refresh" every 1 second
$.ajax({
type: "POST",
url: "some.php",
data: "action=get&type=29",
success: function(arg){
// do something
}
});
you can use
$.ajax({
url: "localhost/index.php",
data: "action=get&type=29",
success: function(data, status, xhr){
// data is the response from the server, status is the http status code,
// xhr is the actual xhr
},
error: function(){
},
...
});
to get the results.
Be sure to define the success and error callbacks to process the data when it is returned.
Look here http://api.jquery.com/jQuery.ajax/ to get started.
I've created a wrapper function for jQuery's $.ajax() method so I can pass different dataTypes and post variables - like so:
function doPost(dType, postData, uri){
$.ajax({
url: SITE_URL + uri,
dataType: dType,
data: postData,
success: function(data){
return data;
});
}
The problem I'm having is getting the data (which is always JSON) back out. I've tried setting a var ret before the $.ajax() function call and setting it as ret = data in the success function. Am I being stupid about this? If I don't set a success function, will the $.ajax simply return the data? Or is it just success: return data? Or does success require a callback function to handle the data, which could just be return data?
Well, you are inside a function - take advantage of variable scope ;-)
function doPost(dType, postData, uri) {
var result;
$.ajax({
url: SITE_URL + uri,
dataType: dType,
data: postData,
async: false,
success: function(data){
result = data;
});
return result;
}
This actually works, but I guess the async part is obligatory then... Otherwise the call of $.ajax would return immediately, and result would still be undefined - you would always get undefined as result of your function call.
However, when you make the $.ajax call synchronous, it blocks until the data is received, and you can return the data as result of your own function.
But you have to be clear that when using this method, no other code will be executed until the ajax load finishes!
When you call $.ajax() it creates the request and then moves on to the next thing. It doesn't sit around and wait for the return and block the next lines of code. That means that unless the success callback function can't return the value of data for the doPost function.
If you really want to have a wrapper function then you could do something like this:
function doPost(dType, postData, uri, success){
$.ajax({
url: SITE_URL + uri,
dataType: dType,
data: postData,
success: success
});
}
And define your success handler when you call doPost, but the wrapper function really isn't doing much for you at the point.