[ACCEPTED]-Using AJAX to run PHP code-jquery

Accepted answer
Score: 11
  • Don't include = in your data variable names 16 (just say 'myString': scriptString)

  • Always include the form submission 15 method for $.ajax ( method: 'get' )

  • In the PHP code, instead 14 of $myString, use $_GET['myString']

  • Consider using a <button> instead of a 13 <div> to send the data to the server - this is 12 more standard.

But most importantly:

  • You're not actually doing anything with the returned data! You also need a success function in the $.ajax options that does something with the data from the server.

Try this 11 code:

(JavaScript)

var scriptString = 'THIS IS MY STRING';
$('#clickMe').click(function(){
    $.ajax({
      method: 'get',
      url: 'index.php',
      data: {
        'myString': scriptString,
        'ajax': true
      },
      success: function(data) {
        $('#data').text(data);
      }
    });
});

(PHP and HTML)

<?php
if ($_GET['ajax']) {
  echo $_GET['myString'];
} else {
?>
<button type="button" id="clickMe">CLICK ME TO RUN PHP</button>
<pre id="data"></pre>
<?php } ?>

Note that 10 the PHP code will now do different things 9 based on whether or not it is handling an 8 AJAX request. For AJAX requests, you don't 7 want to return the HTML for the page - just 6 the data you're interested in. For this 5 reason, it might be better to have two pages: one 4 index.php page, and one ajax.php page which handles AJAX 3 requests.

Also, in this simple examle, you 2 could have just used a plain HTML form, which 1 wouldn't require any JavaScript or AJAX.

More Related questions