简体   繁体   中英

Executing a PHP file using Ajax request

Still grasping Ajax, so I beg your patience. I am trying to run a php file from within javascript using an ajax call with the help of jQuery. I do not need to GET / POST any data, I just intent the PHP code to be executed and the message 'hello world' logged to the console (I intend to use this in a button with an onclick() function). The only thing that gets logged is the "success" message. I want the PHP code to execute without leaving the current page, but I think I may be missing how AJAX works. Or perhaps there is a better way to accomplish this. Thanks for helping out.

PS: I can see the resource "ajax.php" is being loaded as a XHR, by using Safari's web developer tools.

Content of the index file that calls ajax.php is:

<script>
$.ajax({
  url : 'action/ajax.php',
  type : 'POST',
  success : function (result) {
    console.log ('success');
  },
  error : function () {
    console.log ('error');
  }
});
</script>

Content of ajax.php is:

<?php
echo '<script>console.log("hello world");</script>';
?>

Appreciate that you are taking initiative to learn PHP, jQuery and AJAX.

Just some modifications and you are on track:

Javascript (jQuery):

<script>
   $.ajax({

     url : 'action/ajax.php',
     type : 'POST',
     success : function (result) {
        console.log (result); // Here, you need to use response by PHP file.
     },
     error : function () {
        console.log ('error');
     }

   });
</script>

Content of ajax.php is:

<?php
    //echo '<script>console.log("hello world");</script>';
    // Change above line to:
    echo "hello world";
?>

Your data is stored in callback function

<script>
 $.ajax({
  url : 'action/ajax.php',
type : 'POST',
 success : function (result) {
 //this is where you need to call your data which is result and not success
 console.log (result);
 },
error : function () {
 console.log ('error');
 }
 });
</script>

You need to execute the returned javascript if you want it to run

success : function (result) {
    eval(result); //run the result code
    console.log ('success');
},

Content of ajax.php will now be:

<?php
   echo 'console.log("hello world")';
?>

But then you nead clean JS without the script tag

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM