Reputation: 4367
I am using ajax call to grab some data from my mysql database. This is my ajax call:
$.ajax({
type: "POST",
url: "fetch.php",
data: id,
success: function(msg) {
var record = JSON.parse(msg);
$("#name").val(record.name);
$("#description").val(record.description);
switch(record.category) {
case ("Residential"):
$("#category").val("residential");
break;
case ("Modernisation & Domestic Extensions"):
$("#category").val("modernisation");
break;
case ("Feasibility Layouts"):
$("#category").val("feasibility");
break;
case ("Master Planning"):
$("category").val("master");
break;
default:
$("category").val("");
};
switch(record.featured) {
case ("y"):
$("#featured").val("y");
break;
default:
$("featured").val("n");
};
}
})
and this is my php file:
<?php
$dbc = mysqli_connect('XX','XX','XX','XX');
$id = $_POST['id'];
if($dbc) {
$row = fetchDataFromRecordWithId($dbc,$id);
}
else {
echo 'Database error';
}
function fetchDataFromRecordWithId($dbc,$id) {
$q = "SELECT * FROM Projects WHERE id = ".$id;
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
mysqli_close($dbc);
return $row;
}
echo json_encode($row);
?>
Everything work flawless but soon when I try to add if statement in my php file to check if there is any POST data than my ajax call is not getting any response. I tried different methods :
<?php if(isset($_POST)) { .. my whole php code here .. } ?>
<?php if(!empty($_POST)) { ..my whole php code here .. } ?>
<?php if($_POST) { .. my whole php code here .. } ?>
<?php if($_POST['id']) { .. my whole php code here .. } ?>
but nothing work! Ajax call is not getting json data back when I will use any of these if statements listed above.
I could not check for POST data and leave it like it is but I want to do is in proper way.
It seems like if statement is not executed (but POST data must be there as I am able to fetch $_POST['id']
value when if statement not used).
I also tried to put echo json_encode($row)
outside if statement but it didn't help either. Any ideas what is wrong?
Upvotes: 0
Views: 232
Reputation: 1467
you try follow testings on your code
check whether you have have the right request page for php .
see in google chromes right click inspect element then console tab any errors are showing
in your suceess:function(msg) add $("body").append(msg)
add function before success:function(result) {}
error:function(xhr,err){ alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status); alert("responseText: "+xhr.responseText); }
Upvotes: 0
Reputation: 96306
$.ajax({
type: "POST",
url: "fetch.php",
data: id,
http://api.jquery.com/jQuery.ajax/:
data: [...] Object must be Key/Value pairs.
So make that line
data: { id : id },
instead, then it should work.
Upvotes: 1
Reputation: 360692
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
die("Invalid request method: " . $_SERVER['REQUEST_METHOD']);
}
if (isset($_POST['id'])) {
... db code here ...
}
also note that your are WIDE open for SQL injection attacks.
Upvotes: 0