Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery return ajax result into outside variable

I have some problem using ajax.

How can I assign all result from ajax into outside variable ?

I google it up and found this code..

var return_first = (function () {     var tmp = null;     $.ajax({         'async': false,         'type': "POST",         'global': false,         'dataType': 'html',         'url': "ajax.php?first",         'data': { 'request': "", 'target': arrange_url, 'method': method_target },         'success': function (data) {             tmp = data;         }     });     return tmp; }); 

but not work for me..

Can anybody tell what is wrong about that code ?

like image 609
Mohd Shahril Avatar asked May 29 '13 04:05

Mohd Shahril


People also ask

How can a function return a value in Ajax?

Use async: false for your ajax request since Ajax is asynchronous. Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called.


2 Answers

You are missing a comma after

'data': { 'request': "", 'target': 'arrange_url', 'method': 'method_target' } 

Also, if you want return_first to hold the result of your anonymous function, you need to make a function call:

var return_first = function () {     var tmp = null;     $.ajax({         'async': false,         'type': "POST",         'global': false,         'dataType': 'html',         'url': "ajax.php?first",         'data': { 'request': "", 'target': 'arrange_url', 'method': 'method_target' },         'success': function (data) {             tmp = data;         }     });     return tmp; }(); 

Note () at the end.

like image 62
Igor Avatar answered Oct 13 '22 18:10

Igor


This is all you need to do:

var myVariable;  $.ajax({     'async': false,     'type': "POST",     'global': false,     'dataType': 'html',     'url': "ajax.php?first",     'data': { 'request': "", 'target': 'arrange_url', 'method': 'method_target' },     'success': function (data) {         myVariable = data;     } }); 

NOTE: Use of "async" has been depreciated. See https://xhr.spec.whatwg.org/.

like image 21
joshuahealy Avatar answered Oct 13 '22 20:10

joshuahealy