Reputation: 1301
I have read many articles related to my predicament but I do not understand my what my problem is so please someone help explain it to me:
I want to use jQuery ajax to post a value to a PHP file:
$().ready(function(){
"use strict";
$("#ansSubmit").click(function() {
$.ajax({
type: "POST",
url: "updateScore.php",
dataType: "json",
data:{
data : JSON.stringify(flag)
},
success: function(data) {
alert(data.reply);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("jqXHR: " + jqXHR.status + "\ntextStatus: " + textStatus + "\nerrorThrown: " + errorThrown);
}
});
$("#infoDiv").load("updateScore.php"); // to see what $_POST contains
});
});
The flag variable being sent is an integer.
Here is my updated updateScore.php (the PHP file I am posting to):
<?php
session_start();
$returned = array("reply" => "no data received");
if(isset($_POST["data"])) {
$returned["reply"] = $_POST["data"];
}
print_r($_POST);
echo json_encode($returned);
?>
"no data received" is returned so at least I know it reached updateScore.php but now I need help establishing why it not sending anything through - I am 100% sure flag has a value.
Additional information:
Upvotes: 1
Views: 3078
Reputation: 943751
First you tell the server that you are sending it JSON:
contentType: "application/json",
Then you pass an object to data
. This gets encoded as application/x-www-form-urlencoded
(which is not JSON although it happens to have JSON embedded inside it).
data:{ data : JSON.stringify(flag) },
Then in the PHP you try to read from $_POST
if(isset($_POST["data"])) {
… but $_POST
is empty because you told the server you were sending JSON so didn't try to decode it.
Remove this line:
contentType: "application/json",
… because it is a lie that breaks your code.
Alternatively
You could actually send JSON:
contentType: "application/json",
data: JSON.stringify(flag),
… and then read it from the raw request body instead of (the still unpopulated) $_POST
.
$json = file_get_contents('php://input');
$data = json_decode($json);
Upvotes: 1
Reputation: 15847
From your examples, you are expecting a json object to be returned BUT you are echoing it works ....
.
try this sample code in php:
$returned = array("reply" => "not found");
if(isset($_POST["data"])) {
$returned["reply"] = "It works!" . $_POST["data"];
}
echo json_encode($returned);
basically this sample code sets an array returned
with reply
by default as not found
. If data is available, it sets reply
to your message. Then after that it echoes
a json version of the message.
Upvotes: 0