Note that there are some explanatory texts on larger screens.

plurals
  1. POJquery and scope issues with $.post
    primarykey
    data
    text
    <p>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.</p> <p>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.</p> <pre><code>&lt;? if($_REQUEST['action'] == 'test') { echo "OK"; die; } ?&gt; &lt;script type="text/javascript" src="jquery-1.6.1.js" &gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; 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() ); } &lt;/script&gt; &lt;form id=newform name='testform'&gt; &lt;input type="hidden" name="newexample" value="1"&gt; Enter Something: &lt;input name="something" id='something1' value="" type="text"&gt; &lt;input type="button" value="Submit" name="Submit" onclick="ajax_post('index.php?action=test', $('#newform').serialize() ); return false;"&gt; &lt;/form&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload