简体   繁体   English

将变量传递到PHP文件时出现AJAX错误

[英]AJAX error when passing a variable to a PHP file

How my page works: 我的页面如何工作:

  1. The quiz php page loads and the user generates a score with a function inside quiz.js . 测验php页面加载,用户使用quiz.js的函数生成分数。 The score is then saved in a variable score inside quiz.js 然后将分数保存在quiz.js中的可变score
  2. After generating the score, the user has to press a button to go to the next question in the quiz inside the same page. 生成分数后,用户必须按下按钮才能转到同一页面内测验中的下一个问题。 Pressing the button would send the score to my database with a sql query I have in sendData.php , without reloading the page. 按下按钮会将分数通过sendData.php的sql查询发送到我的数据库,而无需重新加载页面。

My button looks like this: 我的按钮如下所示:

<form id="sendData" action="sendData.php" method="post">
  <button type="submit" name="send" onclick="sendAjax()">Send</button>
</form>

sendData.php is already finished and working, but for some reason, sendAjax() doesn't work at all: sendData.php已经完成并且可以工作,但是由于某种原因,sendAjax()根本无法工作:

function sendAjax() {
  $.ajax({
    url:  "sendData.php",
    type: "POST",
    data: {
      score: score,
      numQuiz: numQuiz
    },
    success: function() {
      alert("Data succesfully sent");
    },
    error: function() {
      alert("There has been an error");
    }
  })
}

And my PHP file being like this: 我的PHP文件是这样的:

if (isset($_POST['score']) and isset($_POST['numQuiz'])) {
    $score = $_POST['score'];
    $numQuiz = $_POST['numQuiz'];
    // SQL query and stuff goes here
}

But it seems that $_POST['score'] and $_POST['numQuiz'] aren't set. 但是似乎未设置$_POST['score']$_POST['numQuiz'] Also, I can see the error pop up inside sendAjax before it loads the PHP file. 另外,在加载PHP文件之前,我可以看到该错误在sendAjax内部弹出。 I've tried adding to the form the attribute action="" but it doesn't work either. 我尝试将属性action=""添加到表单中,但是它也不起作用。

 <form id="sendData" action="sendData.php" method="post"> <button type="submit" name="send" onclick="sendAjax()">Send</button> </form> 

You're running the JS when you click a submit button in a form. 单击表单中的提交按钮时,您正在运行JS。

So the JS runs, then the browser immediately navigates to a new page (submitting the form, with no data in it, to the PHP) and the XMLHttpRequest object is destroyed before it receives a response. 这样就运行了JS,然后浏览器立即导航到新页面(将其中没有数据的表单提交给PHP),并且XMLHttpRequest对象在收到响应之前被销毁。

You then see the result of the standard form submission. 然后,您将看到标准表单提交的结果。

If you just want a button to trigger some JavaScript, then use a non-submit button ( <button type="button" ), and don't put it in a form. 如果您只想让按钮触发一些JavaScript,请使用非提交按钮( <button type="button" ),不要将其放入表单中。

Better yet: 更好的是:

  1. switch away from onclick attributes (they have a variety of issues) in favour of addEventListener providing a submit event listener on the form 放弃onclick属性(它们有很多问题),转而使用addEventListener在表单上提供submit事件侦听器
  2. Use preventDefault() to stop the form submission when the JS is successful JS成功后,使用preventDefault()停止表单提交
  3. Put form controls in the form so it submits useful data when the JS isn't successful 将表单控件放入表单中,以便在JS不成功时提交有用的数据

ie write Unobtrusive JavaScript then provides Progressive enhancement . 例如,编写不引人入胜的JavaScript,然后提供渐进式增强

Two things: 两件事情:

You need to tell jQuery to use the application/json content-type: 您需要告诉jQuery使用application / json内容类型:

function sendAjax() {
  $.ajax({
    url:  "sendData.php",
    type: "POST",
    contentType: 'application/json',
    dataType: 'json',
    data: {
      score: score,
      numQuiz: numQuiz
    },
    success: function() {
      alert("Data succesfully sent");
    },
    error: function() {
      alert("There has been an error");
    }
  })
}

PHP's $_POST variable is not populated as you think it is as the payload is not urlencoded as is standard with say a form submit. PHP的$ _POST变量未按您认为的那样进行填充,因为有效载荷没有按照表单提交的标准进行urlencode编码。 So we can parse the JSON payload (body) ussing: 因此,我们可以使用以下方式解析JSON有效负载(正文):

$myData = json_decode(file_get_contents("php://input"));
var_dump($myData->score);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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