Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery ajax return value [duplicate]

How can I return the value "pinNumber" from jquery ajax so I can append it outside of the ajax. Here is my code

var x = pinLast + 1;
    for(i=x;i<=pinMany;i++) {
        var i = x++;
        var cardNumber = i.toPrecision(8).split('.').reverse().join('');
        var pinNumber = '';

        jQuery.ajax({
            type: "POST",
            url: "data.php",
            data: "request_type=generator",
            async: false,
            success: function(msg){
                var pinNumber = msg;
                return pinNumber;
                //pin number should return
            }
        });

        jQuery('.pin_generated_table').append(cardNumber+' = '+pinNumber+'
'); // the variable pinNumber should be able to go here }

Please ask me if you don't understand.. ^^ thanks

like image 580
Jorge Avatar asked Feb 13 '11 07:02

Jorge


5 Answers

AJAX is asynchronous by default, you cannot return a value from the callback without making a synchronous call, which you almost certainly don't want to do.

You should supply a real callback function to the success: handler, and put your program logic there.

like image 104
meagar Avatar answered Nov 14 '22 02:11

meagar


var pinNumber = $.ajax({
    type: "POST",
    url: "data.php",
    data: "request_type=generator",
    async: false
}).responseText;
jQuery('.pin_generated_table').append(cardNumber+' = '+pinNumber+' ');
like image 25
Amjad Masad Avatar answered Nov 14 '22 02:11

Amjad Masad


It has to do with variable scope. The local variable pinNumber you create is not accessible outside its wrapping function.

Perhaps declare pinNumber globally or if it'll do the trick, simply stick your .append() inside your success function.

like image 4
octopi Avatar answered Nov 14 '22 03:11

octopi


var _successEvent = function(response){
    $('.pin_generated_table').append(cardNumber + ' = ' + response);
};

$.ajax({
    type: "POST",
    url: "data.php",
    data: "request_type=generator"
}).done(_successEvent);
like image 3
kayz1 Avatar answered Nov 14 '22 01:11

kayz1


You can use this example:

window.variable = 'some data';

This make you variable global and you can access to this from anywhere

like image 1
Grigoriy Avatar answered Nov 14 '22 01:11

Grigoriy