Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for response in $.post jQuery

PHP returns value with 1-2 second delay jQuery.post doesn't wait for response.

How do you think, is it possible to fix that problem and wait for response?

    $.post( sSource, aoData, function (data) {    
        oCache.lastJson = jQuery.extend(true, {}, data);
        if ( oCache.iCacheLower != oCache.iDisplayStart )
        {
            data.aaData.splice( 0, oCache.iDisplayStart-oCache.iCacheLower );
        }
        data.aaData.splice( oCache.iDisplayLength, data.aaData.length );
         abc(oCache);
        fnCallback(data); 
    },"json" );

Note the same function with get works well

    $.getJSON( sSource, aoData, function (json) { 
        /* Callback processing */
        oCache.lastJson = jQuery.extend(true, {}, json);

        if ( oCache.iCacheLower != oCache.iDisplayStart )
        {
            json.aaData.splice( 0, oCache.iDisplayStart-oCache.iCacheLower );
        }
        json.aaData.splice( oCache.iDisplayLength, json.aaData.length );

        fnCallback(json)
    } );
like image 866
heron Avatar asked May 13 '12 21:05

heron


People also ask

Does post wait for response?

post() or . get(), the script is not waiting for the answer or the result of that function. Instead, the script will immediately continue. So, before your variable can be set to another value (loading the script finally takes a little time), the variable is already outputed and therefore has still its initial value.

Does AJAX wait for response?

ajax() function with the default settings, any JavaScript code after this AJAX request will be executed without waiting for a response. In most cases, this is the desired behavior, but there are some situations where you will want to prevent further execution until there has been a response to the AJAX call.

Does JavaScript wait for response?

JavaScript code execution is asynchronous by default, which means that JavaScript won't wait for a function to finish before executing the code below it.

How to wait for AJAX call to complete in JavaScript?

Your answer You may need to run certain code only after all Ajax requests have completed when working with many Ajax requests. To do this, use the when function in jQuery. It takes any number of arguments and executes once all of the parameter functions have been performed.


1 Answers

$.post is asynchronous, you need to use $.ajax and set async to false, that way you will be able to wait for the response. You can read more about it here: http://api.jquery.com/jQuery.ajax/

like image 117
Vitaly Avatar answered Oct 05 '22 15:10

Vitaly