0

Dear Coders!

The purpose of my code:

Get URL of files listed in specific folder, then assign them to an Array in javascript.

How I'm imagining it: JavaScript function in test.php uses $.post() method to send a value to getURL.php file. After this, getURL.php uses this value to get specific file URLs in a specific folder. I'm getting the result(s) in the $.post() methods function(data) parameter. After this, the resulted value of the "data" is (/would be used) in JavaScript.

The problem: Inside the $.post() methods function: function(data,status) I'm satisfied with the result of the returned value of the data parameter; the PROBLEM is that I can't assign it's value outside this function:function (data,status)`.

TEST.php

<script src="jquery-1.9.1.js">
</script>
<script type="text/javascript">
    var imgPath; // <--He is who should get the value of "data"
    function getTargetUrl(szolg){
        $.post(
            "getURL.php",
            { x: szolg },
            function(data,status){
                alert("in function: " + data + " status: " + status);
                imgPath=data;
                alert (imgPath);
            }
        );
    }
    $(document).ready(function() {
        var a="szolg5"; //it will be "user defined", used in getURL.php
        getTargetUrl(a);
        alert(imgPath);
    });
</script>

getURL.php

<?php 
if(isset($_POST["x"])){
    $queryGlob='img/'.$_POST["x"].'/batch/*.jpg';
    foreach (glob($queryGlob) as $filename) {
        $imgFiles=json_encode($filename);
        $imgFiles=str_replace('\/','/',$imgFiles);
        echo $imgFiles;
    }
    //$data = str_replace('\\/', '/', json_encode(glob('img/'.$_POST["x"].'/batch/*.jpg')));
}
else{
    $imgFiles="FAIL";
    echo $imgFiles;
}
?>

Note: for testing I'm using Google Chrome.

So that's all I guess, hope someone can give me a solution and possible explanation.

RavatSinh Sisodiya
  • 1,596
  • 1
  • 20
  • 42
tormex
  • 127
  • 10
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Qantas 94 Heavy Feb 27 '14 at 13:09

3 Answers3

2

The post call is asynchronous, so in your code here:

$(document).ready(function() {
    var a="szolg5"; //it will be "user defined", used in getURL.php
    getTargetUrl(a);
    alert(imgPath);
});

...the alert occurs before the post call has completed, and so shows the old value of imgPath. What you want to do is pass a function into getTargetUrl that it will call when the post completes, and put the subsequent code in there.

Something like this:

var imgPath; // <--He is who should get the value of "data"
function getTargetUrl(szolg, callback){
    $.post(
        "getURL.php",
        { x: szolg },
        function(data,status){
            alert("in function: " + data + " status: " + status);
            imgPath=data;
            callback();
        }
    );
}
$(document).ready(function() {
    var a="szolg5"; //it will be "user defined", used in getURL.php
    getTargetUrl(a, function() {
        alert(imgPath);
    });
});

And you can do away with the global variable entirely by doing what post does and passing the data back as an argument:

function getTargetUrl(szolg, callback){
    $.post(
        "getURL.php",
        { x: szolg },
        function(data,status){
            alert("in function: " + data + " status: " + status);
            callback(data);
        }
    );
}
$(document).ready(function() {
    var a="szolg5"; //it will be "user defined", used in getURL.php
    getTargetUrl(a, function(path) {
        alert(path);
    });
});
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

No, AJAX is asynchronous meaning that the $.post method will return immediately. If you want to use the results of an AJAX call, the only safe place to do so is inside the success callback. Do not attempt to assign the result to global variables.

So you should put the alert inside the success callback.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

As explained by others the reason for this behavior is the asynchronous nature of ajax requests.

My solution will to return the ajax promise request from getTargetUrl and use it to register callback methods

function getTargetUrl(szolg){
    return $.post(
        "getURL.php",
        { x: szolg },
        function(data,status){
            alert("in function: " + data + " status: " + status);
            alert (data);
        }
    );
}
$(document).ready(function() {
    var a="szolg5"; //it will be "user defined", used in getURL.php
    getTargetUrl(a).done(function(data){
        alert('from callback' + data);
    });
});
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531