-4

I was wondering, is it possible to run a PHP file's script when an AJAX event is called?

I was thinking, if on the AJAX error that it would send the data to the error.php file and log the error, send an email to the admin, and whatever other notifications I wanted.

I can obviously can do this via javascript, but was wondering if while sending an AJAX call to a PHP file already, is it possible to piggyback and so it for each function?

$.ajax({
    method:     "POST",
    data:        mb_ajax_form_data,
    contentType:    false,
    processData:    false,
    error:      function(error){
                <?php include error.php; ?>
            }
});

error.php

// send email
mail();

// add to log file
fopen();

// etc.
markb
  • 1,100
  • 1
  • 15
  • 40
  • Ajax IS JavaScipt so what do you mean by piggybacking? – mplungjan Jan 01 '20 at 08:31
  • Do you mean this? https://stackoverflow.com/questions/17989961/jquery-catch-any-ajax-error – mplungjan Jan 01 '20 at 08:43
  • @mplungjan added some code to hopefully clarify – markb Jan 01 '20 at 08:47
  • Client side is client side. Server side is server side. – mplungjan Jan 01 '20 at 08:51
  • Does this answer your question? [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – Alon Eitan Jan 01 '20 at 09:00
  • You can't combine php code and javascript code, you can however call a php code from javascript using ajax. You must understand that php runs only on the SERVER (I didn't downvote BTW) – Alon Eitan Jan 01 '20 at 09:01
  • Sendind mail is php part creat a new page which is sending mail, create an ajax function like my answer, and call to mail.php in second function, if first function success then second will call to your mail.php. SEE this comment system https://www.webslesson.info/2017/12/comments-system-using-php-and-ajax.html –  Jan 01 '20 at 09:07

2 Answers2

0
if(data == success){
 do what ever you want here.
}

You can do something like this first function to post form values

$(document).ready(function(){

/*Post function*/

 $('#comment_form').on('submit', function(event){
  event.preventDefault();
  var form_data = $(this).serialize();
/*Ajax post here */


/* And second function */

 myfunction();
)};

Then do second function here, when first function success it will start second one.

function myfunction(){

  Now it will do what you told to do, send ping back

  }

)};
  • thank you, I used your code and had a second ajax function, and placed it in the error portion - that called the error.php file – markb Jan 01 '20 at 09:06
  • I just posted a link, check that ajax function you will see what I mean. and glad I helped. –  Jan 01 '20 at 09:08
0

The easiest way to do this is run a XHR request

create this file in PHP for your error script

   <?php
// Headers
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods, Authorization, X-Requested-With');

if($_POST)
{
echo json_encode($_POST);
// USE this portion if it is a success 
//Note weather your data passed or failed you have to respond back to the XHR request in the front end with json_encode...
//Your PHP code 

  echo json_encode(
      array('message' => 'Post Created')
 );

}else{

echo json_encode(
        array('message' => 'Post Not Created')
);
}



?>

This is the XHR Ajax send with a special method to extract the form values

let xtart = document.getElementById('xhrStart');


xtart.addEventListener('click',function(){console.log('Xstarted')

            // First iterate over the form and get all the form Values
            var element = {};
            var data = new FormData(theForm);

            // Display the key/value pairs
            for(var pair of data.entries()) {
                   // console.log(pair[0]+ ', '+ pair[1]);
                   element[ pair[0].toString() ] = pair[1];
            }
            console.log(element);


            // Time to send the control over to PHP to do its magic

            let xhr = new XMLHttpRequest();

            xhr.open('POST', 'post.php');
            xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");


            xhr.responseType = 'json';
            xhr.send(JSON.stringify(element));
            //xhr.send();

            // the response is {"message": "Hello, world!"}
            xhr.onload = function() {
              let responseObj = xhr.response;
              alert(responseObj.message); // Hello, world!
 };



 });

and example of a html form to invoke the XHR

    <form id='theForm'>
<div id="rows">
<div class="sitting-days" style="display:flex; justify-content:center; margin-bottom:20px;">
    <div class="select-date" style="margin-right:30px;">
        <h4 style="text-align:center;">Select Date</h4>
        <input type="date" id="house-sitting-date" name="house_sitting_date" value="">
    </div>
    <div class="yes-no">
        <h4 style="text-align:center;">Yes/No</h4>
        <select name="house_sitting_date_yes_no" id="house-yes-no" style="height:24px;">
            <option value="nada" selected>Please choose an option</option>
            <option value="yes">Yes</option>
        </select>
      </div>
   </div>
</div>
<input type='button' value='Submit' id='xhrStart'>

This is the same method as we use in a rest API and should help your purposes with error and script handling

JonoJames
  • 1,117
  • 8
  • 22
  • I don't see a reason to enable CORS by default and for no valid reason... The OP is asking about ajax and probably running the code from the same domain – Alon Eitan Jan 01 '20 at 09:09
  • Correct however if he is creating an central API that is used by many projects for example a e-mail facility or set of classes he would use across various systems and api its good to have it in to avoid the duplication of the entire library. The header functions are not well understood by some of the junior coders so its also valuable exercise to include it . – JonoJames Jan 01 '20 at 09:48