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

时间:2013-09-28 23:00:33

标签: javascript php ajax jquery

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

AJAX / jquery的:

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

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;

3 个答案:

答案 0 :(得分:7)

主要的例子,你可以做更多的事情来连接反馈和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();

?>

答案 1 :(得分:6)

要获得反馈并将其发送到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
}

在客户端,在success回调

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

或者您可以查看

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

此外,您的$price变量在哪里,我没有看到它,而且我在评论中提到$echo应该是echo

答案 2 :(得分:1)

在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();