Skip to content Skip to sidebar Skip to footer

Wait Ajax Finish To Do Other Function

I am updating some values in my page using Ajax. And then, after is finishes I need to do other function, using that values. I am putting one function after the other, but even in

Solution 1:

It's actually really simple with jQuery Ajax.

$.ajax({
    url:"data/retrieve",
    success:function(result){
       //call your function
       Function2(result);
 }});

Have a look at jQuery Ajax documentation here: http://api.jquery.com/jquery.ajax/

Edit: Since you're using GET as your request type, why not use jQuery.get? Here, you can use this code. Simple and clean.

Also, don't forget to mark this as the answer if it works for you. We don't want answer-less questions here at StackOverflow, do we?

$(document).ready(function(){
    $(".data").blur(function(){
        var id = $(this).attr('id');
        var value = $(this).html();
        var ad = id.split(';');

        Update(value, id); 
    });
});


function Update(value, id){
    $.get("update.php", {value: value, id: id}, function (data) {
         //call your function
         Function2(data);
    });
}


function Function2(ad){
    var name_1 = $("#name_1").html(); //This part is updated inside a <span> by the Ajax function
    $('#'+ad).html(name_1);  
}

Solution 2:

You have to call function2 inside the handler function, that is inside the function that you assign to onreadystatechange.

In addition, I suggest to use jQuery to make you ajax calls, since its API its a lot simpler and cross-browser. See the documentation of jQuery.ajax() for some examples: http://api.jquery.com/jquery.ajax/


Solution 3:

The best solution I usually use is an ajax function with a return statement

        function ajax_func(value,id)
        {
            if (window.XMLHttpRequest)
                AJAX=new XMLHttpRequest(); 
            else
                AJAX=new ActiveXObject("Microsoft.XMLHTTP");
            if (AJAX)
            {
                AJAX.open("GETT", "update.php", false);
                AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                AJAX.send("value="+value+"&id="+id);
                return AJAX.responseText;                                         
            } 
            else
                return null;
        } 

All you need to do is to get the result and execute your other function

var Result = ajax_func("value","id");
new_func();

Post a Comment for "Wait Ajax Finish To Do Other Function"