Reputation: 359
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 that way the second function is not waiting the Ajax to finish.
$(document).ready(function(){
$(".data").blur(function(){
var id = $(this).attr('id');
var value = $(this).html();
var ad = id.split(';');
Update(valor, id);
Function2(ad[1]);
});
});
function Update(value, id){
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("div_table").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","update.php?value="+value+"&id="+id,true);
xmlhttp.send();
}
function Function2(ad){
var name_1 = $("#name_1").html(); //This part is updated inside a <span> by the Ajax function
$('#'+ad).html(name_1);
}
Upvotes: 0
Views: 142
Reputation: 173
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);
}
Upvotes: 4
Reputation: 698
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/
Upvotes: 2
Reputation: 4798
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();
Upvotes: 0