是否可以从AjaxEvent运行PHP脚本?

时间:2020-01-01 08:27:15

标签: javascript php jquery ajax

我想知道,在调用AJAX事件时是否可以运行PHP文件的脚本?

我当时在想,如果在AJAX error上它将把数据发送到error.php文件并记录错误,然后向管理员发送电子邮件,以及我想要的其他任何通知。 / p>

我显然可以通过javascript做到这一点,但想知道是否已经在向PHP文件发送AJAX调用时,是否可以搭载,因此对于每个函数都如此?

$.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 个答案:

答案 0 :(得分:0)

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

您可以执行以下操作 发布表单值的第一个功能

$(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();
)};

然后在此处执行第二个功能,当第一个功能成功时,它将启动第二个功能。

function myfunction(){

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

  }

)};

答案 1 :(得分:0)

最简单的方法是运行XHR请求

使用PHP为您的错误脚本创建该文件

   <?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')
);
}



?>

这是XHR Ajax发送的一种特殊方法,用于提取表单值

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!
 };



 });

以及调用XHR的html表单示例

    <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'>

这与我们在rest API中使用的方法相同,应该可以帮助您实现错误和脚本处理的目的

相关问题