Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX/Jquery - Get response from php file

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;
like image 629
Matt9Atkins Avatar asked Sep 28 '13 23:09

Matt9Atkins


People also ask

How can I get specific data from Ajax response?

You can't as it's asynchronous. If you want to do anything with it, you need to do it in a callback. How? Because it's asynchronous, javascript will fire off the ajax request, then immediately move on to execute the next bit of code, and will probably do so before the ajax response has been received.

How php can be used in AJAX application?

Create an XMLHttpRequest object. Create the function to be executed when the server response is ready. Send the request off to a PHP file (gethint. php) on the server.

Can we use jQuery in php?

All you need to do to use jQuery with PHP is to include the jQuery javascript file in your HTML document in the head tag.


3 Answers

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

?>
like image 180
Tom Avatar answered Oct 08 '22 23:10

Tom


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 comment that $echo should be echo.

like image 45
The Alpha Avatar answered Oct 08 '22 23:10

The Alpha


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();
like image 1
Akinak Avatar answered Oct 09 '22 00:10

Akinak