PHP/Ajax/jQuery - Passing a jquery value to a php script
Asked Answered
S

5

6

I have a bookings.php page which has a jqgrid that displays all the bookings that have been made online. When you double click a row, this opens a jq dialog that displays all the details about there booking. Also, when you double click, I have a variable defined which is the booking reference which I want to pass to a php script:

var brData = rowData['bookref'];

I am sending this variable via ajax:

function getGridRow(brData) {

   $.ajax({

    // Request sent from control panel, so send to cp.request.php (which is the handler)
    url: 'scripts/php/bootstrp/all.request.php',
    type: 'GET',

    // Build data array - look at the '$_REQUEST' parameters in the 'insert' function
    data: {


        //ft: "getDGRow",
        rowdata: 'fnme=getDGRow&row_data='+brData,
        data: brData,

        // Either pass a row id as the 'id' OR a where clause as the 'condition' never both
        id: null,
        condition: null
    },
    dataType: 'text',
    timeout: 20000,
    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(response){

        // Refresh page

       // response = brData;
       // alert(response);

    }
});


}

Here is the switch case for all.inc.php:

case 'getDGRow':
//header('Content-type: text/xml');
DatagridController::getGridRow($_REQUEST['rowdata']);
break;

This is the PHP function that I am sending the jquery variable to, to use within my PHP code:

public static function getGridRow($rowdata) {

    $rowdata = $_GET['data'];
    echo $rowdata;

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

    try {

        $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']);



        $stmt->closeCursor();

    }

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

    $dbh = null;

}


}

I have put echo $rowdata; in the PHP function to see if the variable is being passed which it is as I can see 'BR12345' in the firebug console. The problem is that this query:

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

is not fetching any results. If I was to put:

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

it does fetch the results that I need so I can't understand why this query isn't working when the variable brData is being passed to $rowdata

Any suggestions?

Supreme answered 8/6, 2012 at 8:31 Comment(8)
As a GET request, shouldn't you be doing 'scripts/php/bootstrp/all.request.php?data=BR12345'? Otherwise, the data probably won't be sent (it would be in $_POST, if the AJAX was POST). Since I don't know JQuery, I could be wrong. Also, you should really be using mysql_real_escape_string() on the data in PHP.Pyrophoric
Have you tried, to use the full path URL request? ( eg. domain.com/phpfile.php ), and also be careful of cross domain issues, ajax will not work on cross domain most specially, calling it with www. or without www.Calve
@ScottS PDO::quote is the PDO "equivalent" for mysql_real_escape_string(). Read up on PDO, or mysqli_* they are recommended for use instead of the mysql_* functions.Isa
I have tried all suggestions on here but still can't seem to get this to work, can't see why it will not work? :/Supreme
@Supreme are you really really sure the variable has the right value? do an echo "DATA=[$rowdata]"; exit; in your code and check the value carefully.Reduce
Hi Jack, I have done echo $rowdata; in the php function and this definately does return the correct value (where $rowdata = $_GET['data'];)..Supreme
I've just tried echo "DATA=[$rowdata]"; but that doesn't return anything..Supreme
@Supreme I've updated my answer, take a look .. basically you have to start debugging properly.Reduce
S
0

Try to aislate your problem first. You say you have no problem with firebug, try to put here the console.dir() response to validate.

Mean while do the following:

Then see yor $_REQUEST var with a print_r(). Is your variable there?. If so, do a var_dump($_REQUEST['rowdata']) and check.

In public static function getGridRow($rowdata) see that you overwrite $rowdata to see the echo. And finally if you have all alright by now prepare correctly your query

Sallyanne answered 8/6, 2012 at 17:18 Comment(0)
D
2

Wondering why you have a prepared statement in your code but not actually using it properly.

$stmt = $dbh->prepare("SELECT * FROM tblbookings WHERE bookref = :data");
$stmt->execute(array(
    ':date' => trim($rowdata),
));

I've added trim() to make sure there are no spaces or newlines around it that could mess things up.

Update

It's debug time:

public static function getGridRow($rowdata) {

    $rowdata = $_GET['data'];
    echo $rowdata;

Add the following lines:

    echo "=====DEBUG====== ";
    var_dump($rowdata); 
    echo " =====DEBUG====== ";
    exit;

This will write the value and immediately stop your script so you can inspect its value in detail.

Dugas answered 8/6, 2012 at 8:47 Comment(3)
Hi Jack, you were right, when I add the lines above, the page displays =====DEBUG====== string(0) "" =====DEBUG====== - any idea why this is not working?Supreme
@Supreme probably because it's not passed via $_GET? You can do a var_dump($_GET) as well to find outReduce
The problem is that if I do var_dump($rowdata); exit;, the bookings.php page doesn't load the datagrid as $rowdata is null, $rowdata will only have a value once a row is dblClicked as that is when the .ajax request is being sent. This is really giving me a headache, would you be able to see why this is happening if I show you more code or show you the problem by giving you the link?Supreme
C
1

Use functions

HtmlSpecialChar() 
Trim()

then display $rowdata variable and if string is in correct format then

try this

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

or

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

PHP can see variable without -> '

Crookback answered 8/6, 2012 at 8:38 Comment(2)
His single quotes were inside double quotes, thus PHP would evaluate the variable inside.Carbrey
This is dangerous code and won't even work in this case, because the passed value is a string and not a number ... again, dangerousReduce
W
0

My answer is wrong, I don't delete it so no one else posts this wrong answer
Proof I am wrong: http://codepad.org/fvHM81Uh

Try

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

In PHP vars in strings are handlet so:

$variable = "Hello";
echo "$variable"; //=> Hello
echo '$variable'; //=> $variable

BUT:

 echo "'$variable'"; //=> 'Hello'
Witwatersrand answered 8/6, 2012 at 8:41 Comment(5)
But his single quotes are inside double quotes, so this doesn't apply... see here --> ideone.com/x2JWtCarbrey
@BenEverard are you talking about his example where he demonstrates how the variable is echoed or his solution to the query?Monofilament
Your right! Here is an online editor link, so you all can play around: codepad.org/fvHM81UhWitwatersrand
your solution to the query is not wrong. I've been using it myself on one of my websites to collect data from databasesMonofilament
Yeah, but in this case its wrong, because my query will be the same as his, so its not an answer to his question. So the answer is wrong in this context.Witwatersrand
W
0

Not really sure form the above whether $rowdata is an array, but I'm assuming it's not. In that case, have you tried:

$query = "SELECT * FROM tblbookings WHERE bookref = " . $rowdata;
Wyler answered 8/6, 2012 at 15:59 Comment(0)
S
0

Try to aislate your problem first. You say you have no problem with firebug, try to put here the console.dir() response to validate.

Mean while do the following:

Then see yor $_REQUEST var with a print_r(). Is your variable there?. If so, do a var_dump($_REQUEST['rowdata']) and check.

In public static function getGridRow($rowdata) see that you overwrite $rowdata to see the echo. And finally if you have all alright by now prepare correctly your query

Sallyanne answered 8/6, 2012 at 17:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.