skip to Main Content

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.

2

Answers


  1. 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
    
      }
    
    )};
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search