Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>$.post</code> and <code>$.get</code> are just shorthand versions of the more structured <code>$.ajax()</code>, so I prefer using the latter. The additional structure keeps me straight.</p> <p>Since you are using jQuery anyway, I would re-structure your code like this:</p> <pre><code>$('#q1').click(function() { var test = "Hello there"; $.ajax(function() { type: "POST", url: 'ajax.php', data: 'ans=' +test+ '&amp;anothervarname=' + anothervarvalue, success: function(recd_data) { alert('Rec'd from PHP: ' + recd_data ); } }); }); </code></pre> <p>Note that the <code>data:</code> line is for example purposes and does not match with your code -- just showing you how to pass variables over to the PHP side.</p> <p>Of course, the above includes removing the inline javascript -- never a good idea -- from your anchor tag HTML, thus:</p> <pre><code> &lt;a href="#" id="q1" &gt;click&lt;/a&gt; </code></pre> <hr> <p>Also, on the PHP side, you can verify that things are working by adding a test at the top. Matching with the <code>data:</code> line in the example AJAX code, it would look like this:</p> <p><strong>ajax.php</strong></p> <pre><code>&lt;?php $a = $_POST['ans']; $b = $_POST['anothervarname']; $response = '&lt;h1&gt;Received at PHP side:&lt;/h1&gt;'; $response .= 'Variable [ans] has value: ' . $a . '&lt;br&gt;'; $response .= 'Variable [anothervarname] has value: ' . $b . '&lt;br&gt;'; echo $response; </code></pre> <p>Important: Note the use of <code>echo</code>, not <code>return</code>, to send values back to the AJAX script.</p> <p>Also note that you <strong>must</strong> deal with the stuff returned from PHP <strong>in the AJAX <code>success:</code> function ONLY</strong>. If you need access to that data outside of the <code>success:</code> function, then you can stick the data into a hidden <code>&lt;input type="hidden" id="myHiddenInput"&gt;</code> element, like this:</p> <pre><code>success: function(recd_data) { $('#myHiddenInput').html(recd_data); } </code></pre> <hr> <p>Here are some additional examples of simple AJAX constructions:</p> <p><a href="https://stackoverflow.com/questions/13734395/form-inside-of-load-not-posting-correctly/13734466#13734466">A simple example</a></p> <p><a href="https://stackoverflow.com/questions/17887098/two-post-requests-one-after-the-other-second-post-request-doesnt-get-execut/17887642#17887642">More complicated example</a></p> <p><a href="https://stackoverflow.com/questions/16924082/dynamic-drop-down-box/16924652#16924652">Populate dropdown 2 based on selection in dropdown 1</a></p>
 

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