DVCITIS
DVCITIS

Reputation: 1037

Using data passed to PHP via .load() to execute database query

I am trying to get an AJAX query to work. Im passing data to a PHP script using:

$(".example").click(function(){
x = this.innerHTML;
$("#example").load("ajax.php",{"data":x});
});

If ajax.php just includes the following (did this as a test), everything is fine; I've passed JS data successfully to PHP.

echo $_POST['data'];

My goal is to query my DB using $_POST['data'] though. As another test, I made sure the DB connection was all ok. The following works:

$example = $dbc->prepare("SELECT x, y, z, a FROM clue WHERE userID=?");
$example->bind_param('s',$_SESSION['user_id']);
$example->execute();
$example->bind_result($x,$y,$z,$a);
while($example->fetch()){
echo '<h3>'.$x.'</h3>';
echo '<p>'.$y.'</p>';
echo '<p>'.$z.'</p>';
echo '<p>'.$a.'</p>';
}

When I amend the below lines however, nothing is returned from the script.

$example = $dbc->prepare("SELECT x, y, z, a FROM clue WHERE userID=? AND a=?");
$example->bind_param('ss',$_SESSION['user_id'],$_POST['data']);

The puzzling thing is that the data being passed from JS initially was obtained from the database. When I use alerts, the words are exactly the same as my my DB record.

Any suggestions? Could this be something to do with datatype? do I need to make sure $_POST['data'] is converted to a string somehow?

When I look in firebug, I see the following POST details ('Test Title' is the data used in my query)

Parameters
data    Test Title

Source
data=+Test+Title

Do the + signs represent spaces? perhaps I need to trim a space from beginning of data?

Upvotes: 0

Views: 57

Answers (1)

DVCITIS
DVCITIS

Reputation: 1037

This was due to white space. Fixed with the following:

$(".example").click(function(){
y = this.innerHTML;
x = y.trim();
$("#example").load("ajax.php",{"data":x});
});

Upvotes: 0

Related Questions