user1493339
user1493339

Reputation: 429

How to retrieve return value from $.post function

as my subject / title. here is my code

$(document).on("keyup","[name=BNAM]",function(){
    var nam = $(this).attr("name");
    var val = $(this).val();
    var typ = $(this).prev().val();

    $.post(
        "pro/bulletins_handle.php",
        {BTN:"QCHKNAM",BTYP:typ,BNAM:val},
        function(data){ 
        alert(nam+":"+val+":"+data); //display to check the return value of data
        var reTURN = data; //assign data into reTURN
            alert($(this).html());//Error: it say undefined
        });
    alert(reTURN); //Error: reTURN is not defined
});

** my return from post is 0 or 1 **


Questions:
1). How to retrieve return value from $.post function?
2). Why it say undefined? $(this) is not = [name=BNAM] ??

Upvotes: 0

Views: 89

Answers (2)

Stian Jensen
Stian Jensen

Reputation: 150

First, you have to move the line with alert(reTURN); up and into the function(data) block. The code within this function will execute when the data is successfully loaded. The code below (even though it is below) will execute before the data is ready, becase of js' asynchronous nature.

Also, the this variable you're using within your $.post block does not mean what you think. This code should work better:

$(document).on("keyup","[name=BNAM]",function(){
    var $this = $(this);
    var nam = $this.attr("name");
    var val = $this.val();
    var typ = $this.prev().val();

    $.post(
        "pro/bulletins_handle.php",
        {BTN:"QCHKNAM",BTYP:typ,BNAM:val},
        function(data){ 
            alert(nam+":"+val+":"+data); //display to check the return value of data
            alert($this.html());
            alert(data);
        });    
});

Upvotes: 3

Explosion Pills
Explosion Pills

Reputation: 191819

1

All ajax requests (including $.post) execute asynchronously. This means that any part of the code that may be after the request but outside the callback will most likely execute before the ajax requests completes, and you cannot depend on access to that data.

If you want to use the data, you must use it in the callback to the ajax request.

2

this in the context above is a jQuery XMLHttpRequest object, not a DOM element. It does not have an html method. Do something like this:

$(document).on('keyup', '[name=BNAM]', function () {
   var $this = $(this);
   //$this is now available as the DOM element in the ajax callback

Upvotes: 2

Related Questions