JQuery Ajax only calls predefined function - javascript

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.

Related

How to to return a value from Ajax call to server [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 8 years ago.
I make an ajax call to my server to retrieve some records and return them as a JSON object.
Here is the code for the call
$(".reply").click(function (){
$.ajax({
url: "/ajax_up/",
type: 'GET',
dataType: "json",
success: function (data) {
sync_data=JSON.stringify(data)
}
});
Am trying to use the returned data to construct grid, so when I pass the variable syncd_data which I have declared global in the Ajax call, It seems to be undefined.
$(document).ready(function(){
var data = source_data;
//other code
..........................
..........................
But when I do alert(sync_data) from within the ajax call as below:
$(".reply").click(function (){
$.ajax({
url: "/ajax_up/",
type: 'GET',
dataType: "json",
success: function (data) {
sync_data=JSON.stringify(data)
}
});
It shows the data correctly.
I can I use this data outside the Ajax call?
Any Help Insights or examples will be highly appreciated.
Thanks
You need to make sure you are calling that function inside of the success callback of your ajax call:
success: function (data) {
sync_data=JSON.stringify(data);
doSomething(sync_data);
}
This is because AJAX is Asynchronous, you need to make sure your call is done and successful before proceeding to the next event. Even if the variable is declared to be global.
UPDATE:
var sync_data;
$(document).ready(function(){
$.ajax({
url: "/ajax_up/",
type: 'GET',
dataType: "json",
success: function (data) {
sync_data=JSON.stringify(data);
}
});
});
This way, you'll make sure sync_data is, technically, populated in document.ready upon returning from the AJAX request. You can now consume it anywhere.
add var sync_data = "" out of your ajax call and before it. And after your ajax call, you can see it's data by alert(sync_data);
by adding a variable before ajax call make it can use out of ajax call

What is the main functional difference between these two jQuery ajax calls?

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

Loading XML into JS variable with jQuery without JS alert

I know questions about loading XML into a JS variable have been posted here many times, but I didn't find a solution that would work. In my script I declare a variable before an ajax request, and then add the result to the variable. This works only if I add alert to the script:
var myDB;
$.ajax({
type: 'GET',
url: 'db.xml',
dataType: 'xml',
success: function (xml){
myDB = xml;
}
});
alert(myDB); //returns: undefined
$(myDB).find('item').each(function (){
var question = $(this).find('question').text();
alert(question);
});
The above code works only with the alert. When I delete the alert, the code doesn't work. How can I make this work without the alert?
You need to add your code to success handler for doing that:
var myDB;
$.ajax({
type: 'GET',
url: 'db.xml',
dataType: 'xml',
success: function (xml){
$(myDB).find('item').each(function (){
var question = $(this).find('question').text();
});
}
});
An ajax request is asynchronous. That means, the function you gave in the success option is excuted somwhen later.
After you've started the request, you're variable is still empty. Only if you wait long enough to confirm the blocking alert, the variable will have been loaded.
You will need to add the iteration to the success function, where the xml data is certainly available.

Using same callback for two ajax() request yields "parsererror"

So, I've been battling with Javascript for a little while now and I have a weird error which is probably something simple. I have an ajax request like so:
$.ajax({
url: 'http://www.hahaha.com/api/v3/acts',
crossDomain: true,
jsonpCallback: 'handlejson',
async: false,
jsonp: 'callback',
dataType: 'jsonp',
type: 'GET',
success: handleActs,
error: handleError
});
Which works fine and calls the callback with no problems. Now, if I add this request directly underneath:
$.ajax({
url: 'http://www.hahaha.com/api/v3/performances',
crossDomain: true,
async: false,
jsonpCallback: 'handlejson',
jsonp: 'callback',
dataType: 'jsonp',
type: 'GET',
success: handlePerformances,
error: handleError
});
I get a "parsererror" on the first request and the second one succeeds. Anyone have any ideas as to why it's doing this? Can a jsonpCallback only have one request called on it?
I don't think it works to have two AJAX calls referring to the same jsonpCallback - I think jQuery puts a callback function in the global namespace, then removes it when it's called - so it won't be around for the second set of loaded data. I wouldn't have thought this would matter with async set to false, but it looks like it does.
At first I couldn't figure out why you were setting jsonpCallback at all, but testing seems to indicate that the API you're using strips anything other than [a-z] from the callback name :(. So you might try this with jsonpCallback set to 'handlejsona' in the first call and 'handlejsonb' in the second call.
This approach seems to work here: http://jsfiddle.net/nrabinowitz/H7zYt/

jQuery $.ajax success must be a callback function?

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.

Categories