I have the following Ajax request:
// JavaScript
function myFunc(pid) {
$.ajax({
type : "GET",
url : "testback.php",
contentType : "application/json; charset=utf-8",
dataType : "json",
data : {
q : "testrequest",
pid : pid
},
success : function(data) {
console.log(data)
},
error : function(jqXHR, status, error) {
console.log(status, error);
}
});
}
// PHP
require_once ("dbconnect.php");
if (isset ( $_GET ['q'] )) {
if ($_GET ['q'] == "testrequest") {
$pid = $_GET ['pid'];
$query = "SELECT * FROM `tab1` WHERE `pid` = " . $pid;
$json = array ();
if ($result = $link->query ( $query )) {
while ( $row = $result->fetch_assoc () ) {
array_push ( $json, $row );
}
}
header ( "Content-type: application/json; charset=utf-8" );
die ( json_encode ( $json ) );
exit ();
}
die ();
}
It sends a request to my MySQL database and returns the expected output.
However, I now want to switch to POST
, rather than GET
.
When I just swap GET with POST:
// JavaScript
function myFunc(pid) {
$.ajax({
type : "POST", // POST
url : "testback.php",
contentType : "application/json; charset=utf-8",
dataType : "json",
data : {
q : "testrequest",
pid : pid
},
success : function(data) {
console.log(data)
},
error : function(jqXHR, status, error) {
console.log(status, error);
}
});
}
// PHP
require_once ("dbconnect.php");
if (isset ( $_POST ['q'] )) { // POST
if ($_POST ['q'] == "testrequest") { // POST
$pid = $_POST ['pid']; // POST
$query = "SELECT * FROM `tab1` WHERE `pid` = " . $pid;
$json = array ();
if ($result = $link->query ( $query )) {
while ( $row = $result->fetch_assoc () ) {
array_push ( $json, $row );
}
}
header ( "Content-type: application/json; charset=utf-8" );
die ( json_encode ( $json ) );
exit ();
}
die ();
}
I get the following error in the console:
parsererror SyntaxError: Unexpected end of JSON input
The request payload is still q=testrequest&pid=1
.
What else do I need to change, in order to switch from GET
to POST
?