Passing Jquery value to PHP Script
Asked Answered
E

3

11

I have a JQGRid that displays bookings with double click event as follows:

ondblClickRow: function(rowid)
{
    rowData = $("#bookings").getRowData(rowid);
    var brData = rowData['bookref'];
    getGridRow(brData);
},

This gets passed to getGridRow function:

function getGridRow(brData) {

    //$.post('bookings-dialog.php', { 'rowdata': brData } );
                 //  $("#cp-bookings-dialog").load('bookings-dialog.php').dialog({ show: "slide", hide: 'slide', height: 625, width: 733, title: 'Booking Reference: - '+ brData});

    $.ajax({
      url: 'bookings-dialog.php',
      type:'POST',
      data: {'rowdata' : brData },
      dataType: 'JSON', //this is what we expect our returned data as
    error: function(){
      alert("It failed");
      $('#cp-div-error').html('');
      $('#cp-div-error').append('<p>There was an error inserting the data, please try again later.</p>');
      $('#cp-div-error').dialog('open');
    },
    success: function(data){
        alert("IT WORKED!");
        //empty our dialog so we don't end up with duplicate content
        $('.cp-booking-info').empty();
        //we have told the browser to expect JSON back, no need to do any parsing
        //the date
        $('#cp-bookings-dialog').append('<p class="pno-margin">Booking Date: '+data.bookref+'</p>');


        //now let's manipulate our dialog and open it.
        $("#cp-bookings-dialog").dialog({
          show: { effect: 'drop', direction: "up" },
          hide: 'slide',
          height: 625,
          width: 733,
          title: 'Booking Reference: - '+ brData
        });
      }

    });

And this is the bookings-dialog.php:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<?php
require_once('deployment.php');
require_once('bootstrp/all.inc.php');;

require_once('models/sql.php');
require_once('models/bookingdocket.php');

    $pdo = new SQL();
    $dbh = $pdo->connect(Database::$serverIP, Database::$serverPort, Database::$dbName, Database::$user, Database::$pass);

    try {
           $rowdata = $_POST['rowdata'];

           $query = ("SELECT * FROM tblbookings WHERE bookref = '$rowdata'");

        $stmt = $dbh->prepare($query);

        $stmt->execute();

        $row = $stmt->fetch(PDO::FETCH_BOTH);

          /* BookingDocket::set_id($row['id']); */
           BookingDocket::set_bookref($row['bookref']);
          /* BookingDocket::set_bookdate($row['bookingdate']);
           BookingDocket::set_returndate($row['returndate']);
           BookingDocket::set_journeytype($row['journeytype']);
           BookingDocket::set_passtel($row['passengertel']);
           BookingDocket::set_returndate($row['returndate']); */

            $booking_ref = BookingDocket::get_bookref();


           return json_encode(array('bookref' => $booking_ref,
                                    )
                             );

        $stmt->closeCursor();

    }

    catch (PDOException $pe) {
        die("Error: " .$pe->getMessage(). " Query: ".$stmt->queryString);
    }

    $dbh = null;

?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title><? echo Company::get_name(); ?> :: Online Booking - Powered by</title>

</head>

<body>

<div id="cp-bookings-dialog">
  <div class="cp-tiles-wrapper-dlg">
    <div class="cp-booking-info left">
    </div>
  </div>
</div>

</body>
</html>

Basically what should happen is that the Booking Reference (brData), should be passed to booking-dialog.php and used in the query to select all booking from the booking database by the reference data that is being passed.

The problem that I am having at the moment is that at the moment, the value that I am getting on the booking docket is 'undefined'. Is there a problem with the headers being sent back from the server, or is it an issue with the structure of the JSON object?

If anybody can help me with this I would be very grateful, I've spent ages trying to get this to work and it seems so simple.

Evenhanded answered 24/8, 2012 at 8:46 Comment(6)
Does your brData var contain the correct data before executing the ajax request? Please log its value or check it using firebug or similarMandell
Are you sure that the server successfuly performs the query and returns a JSON object? Maybe it returns an error instead. You can use Firebug to check the exact response from the server.Haleyhalf
The variable brData is definately correct, I can alert this in success and it displays the correct value. At the moment the response in firebug that I am getting is: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="w3.org/1999/xhtml"> <headEvenhanded
Why do you have HTML output in your PHP script if you specified the dataType as JSON in your $.ajax call? How do you expect it to work? You get HTML back, but your JS will try to eval it as JSON (and it'll fail).Veinlet
Also, you never echo the json-encoded array anywhere. So it can't get returned to the javascript.Preface
Nice, an SQL injection gateway!Vaillancourt
S
2

I think the only thing to change is to replace :

title: 'Booking Reference: - '+ brData

By :

title: 'Booking Reference: - '+ data.bookref

brData looks undefined in the success callback

Shangrila answered 3/9, 2012 at 18:11 Comment(1)
This is the good answer. Scope creeping in. It should be accepted as such.Sammons
E
5

bookings-dialog.php should not display HTML elements, it should return JSON encoded string.

add your result, and another for error, then you can handle error from jQuery

eg:

<?php
    require_once('deployment.php');
    require_once('bootstrp/all.inc.php');;
    require_once('models/sql.php');
    require_once('models/bookingdocket.php');

    $pdo = new SQL();
    $dbh = $pdo->connect(Database::$serverIP, Database::$serverPort, Database::$dbName, Database::$user, Database::$pass);

    try {
        $rowdata = $_POST['rowdata'];
        $query = ("SELECT * FROM tblbookings WHERE bookref = :bookref");
        $stmt = $dbh->prepare($query);
        $stmt->execute(array(':bookref' => $_POST['rowdata']));
        $row = $stmt->fetch(PDO::FETCH_BOTH);

        BookingDocket::set_bookref($row['bookref']);

        echo json_encode( array('bookref' => $row['bookref'], 'date' => $row['bookingdate'], 'error' => 'no') );
        $stmt->closeCursor();
    }
    catch (PDOException $pe) {
        die(json_encode(array("error" => "Error: " .$pe->getMessage(). " Query: ".$stmt->queryString)));
    }

    $dbh = null;

?>

also in your getGridRow check for error field:

success: function(data){
    if(typeof console != "undefined"){ console.log(data); } // this will prompt data in console
    if(data.error == 'no'){
        alert("IT WORKED!");
        $('.cp-booking-info').empty();
        $('#cp-bookings-dialog').append('<p class="pno-margin">Booking Date: '+data.date+'</p>');
        $("#cp-bookings-dialog").dialog({
            show: { effect: 'drop', direction: "up" },
            hide: 'slide',
            height: 625,
            width: 733,
            title: 'Booking Reference: - '+ data.bookref
        });
    } else {
        alert(data.error);
    }
}
Enesco answered 24/8, 2012 at 9:17 Comment(2)
Okay, I have changed this and echo json_encode( array('bookref' => $booking_ref) ); I can see in firebug console shows {"bookref":"BR1278"}. However that value being shown on the bookings-dialog is still undefined, any ideas?Evenhanded
Add console.log(data); at the top of the success function to see what you're getting back.Urbana
S
2

I think the only thing to change is to replace :

title: 'Booking Reference: - '+ brData

By :

title: 'Booking Reference: - '+ data.bookref

brData looks undefined in the success callback

Shangrila answered 3/9, 2012 at 18:11 Comment(1)
This is the good answer. Scope creeping in. It should be accepted as such.Sammons
H
1

If you're asking for a JSON string, php should return that exact type. Javscript is waiting for the application/json content type.

So in php you need to add some header code:

require_once('deployment.php');
require_once('bootstrp/all.inc.php');
require_once('models/sql.php');
require_once('models/bookingdocket.php');

header('Content-Type: application/json');

$pdo = new SQL();
$dbh = $pdo->connect(Database::$serverIP, Database::$serverPort, Database::$dbName, Database::$user, Database::$pass);

try 
{
       $rowdata = $_POST['rowdata'];
       $query = ("SELECT * FROM tblbookings WHERE bookref = '$rowdata'");

       $stmt = $dbh->prepare($query);
       $stmt->execute();

       $row = $stmt->fetch(PDO::FETCH_BOTH);

      /* BookingDocket::set_id($row['id']); */
       BookingDocket::set_bookref($row['bookref']);
      /* BookingDocket::set_bookdate($row['bookingdate']);
       BookingDocket::set_returndate($row['returndate']);
       BookingDocket::set_journeytype($row['journeytype']);
       BookingDocket::set_passtel($row['passengertel']);
       BookingDocket::set_returndate($row['returndate']); */

       $booking_ref = BookingDocket::get_bookref();

       echo json_encode(array('bookref' => $booking_ref));

       $stmt->closeCursor();

}
catch (PDOException $pe)
{
    echo json_encode(array("Error: " .$pe->getMessage(). " Query: ".$stmt->queryString));
}
finally
{
    $dbh = null;
}
Hispanicism answered 3/9, 2012 at 20:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.