Reputation: 11
I'm having some issues on how to use the data returned by jQuery's $.post function. I'm trying to test if a picture exists on my server or not.
Here is the javascript :
$.post("ajax_test_file.php",
{filename: filetocheck},
function(data){
if(data==1){
var img_ref_up = 'value 1';
}else{
var img_ref_up = 'value 1';
}
}
);
[Following code trying to use img_ref_up's value]
And here is the ajax_test_file.php content :
$filename = $_POST["filename"];
if (file_exists($filename)) {
echo 1;
} else {
echo 0;
}
What i'm trying to do is to use the value of img_ref_up right after the $.post(...)
Does anyone have a clue about this? Thanks in advance
Upvotes: 1
Views: 349
Reputation: 2550
As the request is asynchronous the [Following code] section will likely be executed before the post has completed. You should do this instead.
$.post('url', function(data) {
var img_ref_up;
if (data == 1) {
img_ref_up = 'value 1';
}
doSomethingWithRefUp(img_ref_up);
});
function doSomethingWithRefUp(img_ref_up) {
[Following code]
}
Upvotes: 1
Reputation: 21275
You can not/should not - ajax calls are asynchronous (you can make it synchronous but it's highly discouraged). You have to process the result inside the callback method:
$.post("ajax_test_file.php",
{filename: filetocheck},
function(data){
if(data==1){
var img_ref_up = 'value 1';
}else{
var img_ref_up = 'value 1';
}
///// DO WHATEVER YOU NEED HERE
[Following code trying to use img_ref_up's value]
}
);
Upvotes: 1
Reputation: 25766
$.post
is running asynchronously so it looks like you're accessing the value before the ajax request has finished. You could move your code into the success callback and that would assure that the value of image_ref_up
is set before you use that variable.
$.post("ajax_test_file.php",
{filename: filetocheck},
function(data){
if(data==1){
var img_ref_up = 'value 1';
}else{
var img_ref_up = 'value 1';
}
// move your code here
}
);
Upvotes: 1