javascript AJAX/Jquery - 从 php 文件获取响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19072592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:15:35  来源:igfitidea点击:

AJAX/Jquery - Get response from php file

javascriptphpajaxjquery

提问by Matt9Atkins

Hi I have a php file that when called by my ajax/jquery code inserts a row into a mySQL table. However I want some sort of feedback to know whether the insertion was successfull or not. Here is my current code:

嗨,我有一个 php 文件,当我的 ajax/jquery 代码调用它时,它会在 mySQL 表中插入一行。但是我想要某种反馈来知道插入是否成功。这是我当前的代码:

ajax/jquery:

阿贾克斯/jQuery:

$.ajax({
    url: "update.php",
    success: function(){
        alert("success");    
    },
    error:function(){
        alert("failure");
    }
});

PHP:

PHP:

$conn = "";
try {
    $conn = new PDO( "mysql:host=XXX;dbname=XXX", "XXX", "XXX");
    $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch ( PDOException $e ) {
    echo "Cannot connect to database, try again later";
}
$stmt = $conn->prepare("INSERT INTO data (price) VALUES (:price)");
$stmt->bindParam(":price", $price);
$stmt->execute();
$conn=null;

回答by Tom

principal example, you can do much more to connect feedback vs javascript handling

主要示例,您可以做更多的事情来连接反馈与 javascript 处理

$.ajax({
  url: "update.php",
  data: $('#form_id').serialize(),
  dataType: "json",
  timeout: 15000,    
  success: function(response){
    switch(response.status){
      case 'saved':
        alert(response.message); // do what you want
      break;
      case 'empty':
        alert(response.message);
      break;
      default:
        alert("unknown response");
    }  
   },
   error:function(){
    alert("failure");
   }
});


// remote php file
<?php

    // on database success or whatever
      $return_arr["status"] = 'saved';
      $return_arr["message"] = utf8_encode("Your data ".$name." was saved");
      echo json_encode($return_arr);
      exit();

?>

回答by The Alpha

To get a feedback and send it to the jQuery.ajaxyou may use

要获得反馈并将其发送给jQuery.ajax您可以使用

if($stmt->execute()) { // returns true on success
    exit('success'); // Prints success and exit the script
}
else{ // returns false on fail
    exit('error'); // Prints error and exit the script
}

In the client side, in your successcallback

在客户端,在您的success回调中

success: function(data){
    alert(data); // either error or success
}

Or you may check it like

或者你可以检查它像

if(data == 'success') {
    // ok
}

Also, where is your $pricevariable, i didn't see it and as i mrntioned in comment that $echoshould be echo.

另外,你的$price变量在哪里,我没有看到它,正如我在评论中指出的那样,$echo应该是echo.

回答by Akinak

In PHP section you can do this:

在 PHP 部分,您可以执行以下操作:

$conn = "";
try {
    $conn = new PDO( "mysql:host=XXX;dbname=XXX", "XXX", "XXX");
    $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch ( PDOException $e ) {
    echo "Cannot connect to database, try again later";
}
$stmt = $conn->prepare("INSERT INTO data (price) VALUES (:price)");
$stmt->bindParam(":price", $price);
$stmt->execute();
$count = $stmt->rowCount();// Returns the number of rows affected by the last SQL statement
$conn=null;
if ($count > 0)
{
    $res = "success";
}
else
{
    $res = "error";
}
//maybe you need to encode the result to use in your js ajax functions!
json_encode($res);
exit();