user591162
user591162

Reputation: 559

Jquery and scope issues with $.post

I am having one small problem with my code. I am sending a POST request to my page, after I am done it should return "OK" meaning it worked. From inside my handler function I call set_var(data) to set my global variables text, but the problem is my print_info() returns undefined.

I've spent a lot of time on this and realize my problem has to do with scoping somehow but I am not sure how to go about fixing it. If anyone can provide any pointers, that would be great.

<?
if($_REQUEST['action'] == 'test')
{
    echo "OK";
    die;
}

?>

<script type="text/javascript" src="jquery-1.6.1.js" ></script>

<script type="text/javascript">
var ajax_post_result;

function set_var(data)
{
    //PRINTS MY TEXT OK
    alert("SET:: " + data);

    //SET TO MY GLOBAL VARIABLE
    ajax_post_result = data;

    //ALSO PRINTS OK
    alert("SET2:: " + ajax_post_result);
}

function return_handler(data, textStatus)
{
    //THESE BOTH WORK ... BUT ONLY HERE AND WITHIN set_var()
    //alert("1: " + data); //PRINTS WHAT I NEED

    //CALL FUNCTION TO SET GLOBAL VARIABLE
    set_var(data);
}

function print_info()
{
    return ajax_post_result;
}

function ajax_post(file, data )
{
    $.post( file, data, return_handler);

    //PRINTS UNDEFINED
    alert("RETURN:: " + print_info() );
}

</script>

<form id=newform name='testform'>
<input type="hidden" name="newexample" value="1">
Enter Something: <input name="something" id='something1' value="" type="text">
<input type="button" value="Submit" name="Submit" onclick="ajax_post('index.php?action=test', $('#newform').serialize() ); return false;">
</form>

Upvotes: 0

Views: 235

Answers (2)

John Flatness
John Flatness

Reputation: 33789

AJAX requests are, as evidenced by the first A in the acronym, asynchronous. So, when you call $.post(), execution of the ajax_post function continues on its merry way more or less immediately, without waiting for the request to finish. You get to your "RETURN" alert before your return_handler has run to set the global variable.

You can use jQuery.ajax and set the async option to false, which will get you a synchronous request.

Or, and I recommend this strategy, move all the things that need to happen only after the request is done to the success handler.

Upvotes: 2

Phil
Phil

Reputation: 164892

Your problem is due to the asynchronous nature of AJAX.

You should do all your post AJAX processing in the callback function. Something like this (using your current functions)

$.post(file, data, function(data, textstatus) {
    return_handler(data, textstatus);
    alert("RETURN:: " + print_info());
});

Though you could easily combine your functions into the one closure (minus the alerts), eg

$.post(file, data, function(data, textstatus) {
    ajax_post_result = data;
});

Upvotes: 2

Related Questions