最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AJAXJquery - Get response from php file - Stack Overflow

programmeradmin9浏览0评论

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:

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;

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:

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;
Share Improve this question edited Sep 28, 2013 at 23:06 M9A asked Sep 28, 2013 at 23:00 M9AM9A 3,27615 gold badges55 silver badges81 bronze badges 5
  • $echo should be echo. – The Alpha Commented Sep 28, 2013 at 23:05
  • @SheikhHeera Fixed. Also price is a variable declared earlier on – M9A Commented Sep 28, 2013 at 23:07
  • If there is an error setting $conn, I imagine $stmt = $conn->prepare("INSERT INTO data (price) VALUES (:price)"); is going to fail... Might want this whole code in your try block. – guydog28 Commented Sep 28, 2013 at 23:07
  • @guydog28 but how will that alert me via the ajax code whether it was successful or not? – M9A Commented Sep 28, 2013 at 23:09
  • @Matt9Atkins it does not. The answers below show you how to return the result. I'm just helping you see see that you have other dangers lurking. You'll need to return results like the answers below at the end of your try block, and additionally at the end of your catch block return an error message. – guydog28 Commented Sep 28, 2013 at 23:13
Add a ment  | 

3 Answers 3

Reset to default 8

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

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

?>

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

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 success callback

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

Or you may check it like

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

Also, where is your $price variable, i didn't see it and as i mrntioned in ment that $echo should be echo.

In PHP section you can do this:

$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();
发布评论

评论列表(0)

  1. 暂无评论