Executing PHP file using Ajax request

Still grabbing Ajax, so I ask your patience. I am trying to run a php file from javascript using an ajax call with jQuery. I don't need to GET / POST any data, I just force the PHP code to run and the "hello world" message is written to the console (I intend to use it with a button with an onclick () function). The only thing that is logged is a success message. I want the PHP code to execute without leaving the current page, but I think it might be missing how AJAX works. Or perhaps there is a better way to achieve this. Thanks for the help.

PS: I see the resource "ajax.php" is loading as XHR using Safari web developer tools.

The content of the index file calling 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:

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

      

+3


source to share


3 answers


Appreciate that you take the initiative to learn PHP, jQuery and AJAX.

Just some changes and you are on your way:

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>

      

Ajax.php content:

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

      

+5


source


Your data is stored in a 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>

      

+1


source


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

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

      

Now the content of ajax.php will be:

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

      

But then you don't clear the JS without the tag script

-1


source







All Articles