Goal: Serialize data, send them in HTTP POST request using AJAX, proceed data in PHP (and answer)
Problem: PHP $_POST variable seems to be empty
JS/AJAX
var postData = [cmd, data];
alert(postData = JSON.stringify(postData));
$.ajax({
url: "./backendTag.php",
type: "post",
data: postData,
dataType: 'json',
success: function (response) {
alert(response); // Empty
//logToServerConsole(JSON.parse(response));
},
error: function(jqXHR, textStatus, errorThrown) {
logToServerConsole("E3"); // Communication Error
console.log(textStatus, errorThrown);
}
});
PHP
<?php echo json_encode($_POST);
The reason for the same is probably because you are not posting properly in javascript. Before i add the codes, let me add a couple of tips on how to debug in these situations.
First is, you check if the request is properly formed. Inspect the network in browser dev tools.
Second method could be to use var_dump on $_POST to list out all the post parameters and check if they have been recieved in PHP
Now as far as the code goes
here is the javascript
$.ajax({
method: "POST",
url: "url.php",
data: { name: "John Doe", age: "19" }
}).done(function( msg ) {
alert(msg);
});
and in php you can simply check using
<?php
print $_POST["name"];
?>
which would work perfectly. Notice how the data in javascript is a list, while from what you wrote seems to be json string
Apparently we can't pass an array directly after serializing him. The following code resolved the problem. (Split array)
data = JSON.stringify(data);
var JSONdata = {"cmd" : cmd, "data" : data};
$.ajax({
url: "./backendTag.php",
type: "post",
data: JSONata,
dataType: 'json',
/* Handlers hidden*/
});
JSON content won't be parsed to the $_POST globals. If you want to reach them, try to get from php://input with:
file_get_contents('php://input')
And I suggest giving the content-type during the ajax request:
contentType: 'application/json',
If it's not working, try to set the data as a string, with JSON.Stringify, like the following:
data: JSON.stringify(postData)
Related
I am working on a site using HTML/CSS/JS and AJAX for connecting to the server. (new to web development)
I currently have this to get data and put it in an array.
var addresses = [];
$.ajax({
type: "GET",
url: 'GetAddresses.php',
data: {"type":"check"},
success: function(response){
alert(response);
addresses.push(response) // add values from php to array
}
});
But what if php echoed an address, a name, and a city for example. How could I access those different values?
Thank you for your help.
Typically you would write PHP that outputs structured data, e.g. JSON, and then parse that on the client.
<?php
header("Content-Type: application/json");
$data = [ "address" => "foo", "name" => "bar", "city" => "baz" ];
echo json_encode($data);
?>
and then on the client:
$.ajax({
type: "GET",
url: 'GetAddresses.php',
data: {"type":"check"},
success: function(response){
alert(response);
console.log(response.address);
console.log(response.name);
console.log(response.city);
}
});
Unrelated to the focus of your question, pushing data into an array in the wider scope from an Ajax callback is likely to cause you problems.
I have a function that includes an AJAX to send a JSON object retrieved from localStorage. For some reason, in my PHP script, it never shows anything in the $_POST variable, despite me being pretty sure the AJAX call goes through successfully. My code is as follows:
The javascript:
function processResults(){
var finalResults = localStorage.getItem('results');
finalResults = JSON.stringify(finalResults);
$.ajax({
type: 'POST',
url: '../DB_add.php',
dataType: 'json',
data: {'answers': finalResults},
success: function(data){
console.log(data);
console.log('Success');
}
})
}
The php script:
if(isset($_POST['answers'])){
$obj = json_decode($_POST['answers']);
print_r ($obj);
}
Any help as to why this isn't working would be greatly appreciated. Thank you.
I've tried all of the options given so far, and nothing seems to be working. I'm at a total loss.
For those asking, the finalResult variable is structured as:
[{"answer":0,"elapsed_time":1378,"stimulus_id":"8","task_id":1},{"answer":1,"elapsed_time":157,"stimulus_id":"2","task_id":1},{"answer":1,"elapsed_time":169,"stimulus_id":"1","task_id":1}, etc....
dataType: 'json' requires that what you output in PHP (data accepted in success section) must be valid json.
So valid json will be in PHP:
if(isset($_POST['answers'])){
echo $_POST['answers'];
}
No need to decode it, it is json string already. No var_dump, no print_r
I would remove the dataType property in your Ajax request and modify the structure of your data :
$.ajax({
type: 'POST',
url: '../DB_add.php',
data: 'answers='&finalResults,
success: function(data){
console.log(data);
console.log('Success');
}
})
And in a second time I would test what I receive on PHP side :
if(isset($_POST['answers'])){
var_dump(json_encode($_POST['answers']));
}
Remove dataType: 'json', if you sending with JSON.stringify
JS.
function processResults(){
var finalResults = localStorage.getItem('results');
finalResults = JSON.stringify(finalResults);
$.ajax({
type: 'POST',
url: '../DB_add.php',
data: {'answers': finalResults},
success: function(data){
console.log(data);
console.log('Success');
}
})
}
PHP CODE:
if (!empty($_REQUEST['answers'])) {
$answers = json_decode(stripslashes($request['answers']));
var_dump($answers);
}
This question stems from this thread.
I've followed the answer below but am having trouble with passing the object into PHP. I think it's only a minor problem but I can't find it.
My ajax call
$('.actResult').click(function() {
var result = {};
$('.actResult tr').each(function(){
var $tds = $(this).find('td');
result[$tds.eq(0).html()] = $tds.eq(1).text();
});
console.log(result);
$.ajax({
type: 'get',
url: 'userpage.php',
data: result
});
$('.FindResults').dialog("close");
});
In userpage.php, I'm using this:
echo '<div id="data"><pre>', var_dump($_GET), '</pre></div>';
Possibly I might need to use stringify or json_decode, but this source tells me it's enough to do an ajax call.
The output is giving me an
array(0){
}
Which is strange. The array prints into the console so it's generated properly. The console also tells me the ajax is executed successfully. I'm using $_GET just because $_POST already has so many variables, it's easier to inspect $_GET for this request.
UPDATE:
From the comments below, the ajax call doesn't do anything when the query is successful. So I changed the call:
$.ajax({
type: 'get',
url: 'userpage.php',
data: result,
success: function(){
$('#data').text( data );
}
});
And the PHP
echo '<input type="text" id="data" /><pre>', var_dump($_GET), '</pre>';
I tried it with a div instead of a textbox. The result still is array(0){}
$.ajax({
type : "GET",
data : { result : JSON.stringify(result) },
dataType : "html",
url : "userpage.php",
beforeSend : function(){ },
success : function(data){ console.log( data ) },
error : function(jqXHR, textStatus, errorThrown) { }
});
in your php
echo '<div id="data"><pre>'. $_GET["result"] .'</pre></div>';
$.ajax({
type: 'GET',
url: 'userpage.php',
data: result,
dataType : 'json',
success: function(data){
console.log(data);
},
error: function(jqXHR, textStatus){
console.log(jqXHR);
console.log(textStatus);
}
});
look at the console log and check the problem...
ahh another thing on the userpage use like this:
echo json_encode($_GET);
You know what, I'm going out on a limb here, and taking a wild guess.
I think you're lying to us.
Based on this sentence in your question: I'm using $_GET just because $_POST already has so many variables.
You're doing a POST, not a GET. Why would $_POST contain anything if you're sending a GET?
Change your ajax from this
$.ajax({
type: 'post',
url: 'userpage.php',
data: result
});
to this
$.ajax({
type: 'get',
url: 'userpage.php',
data: result
});
I have a JSON string (stringified array of objects in javascript) which i intend to post to another page and then retrieve it from the $_POST variable. I used json =JSON.stringify(array).
The result gave me the following string
json = [{"keycodec":68,"eventc":"keydown","timec":1392849542994}
{"keycodec":65,"eventc":"keydown","timec":1392849543063},
{"keycodec":87,"eventc":"keydown","timec":1392849543084}]
Now I use
$( "#other").click(function() {
$.ajax({
url: 'some.php',
type: 'POST',
data: { kite : json}
});
On the page some.php I use
$kite=json_decode($_POST['kite'],true);
print_r($kite)
But nothing shows up. I have read many links on this topic and tried adding ContentType,dataType,processData parameters to the $.ajax() function but nothing helped.
What about this:
$( "#other").click(function() {
var json = [{"keycodec":68,"eventc":"keydown","timec":1392849542994}
,{"keycodec":65,"eventc":"keydown","timec":1392849543063},
{"keycodec":87,"eventc":"keydown","timec":1392849543084}];
$.ajax({
url: 'test.php',
type: 'POST',
data: "kite=" + JSON.stringify({ kite : json }),
success: function(msg){
alert(msg);
},
failure: function(errMsg) {
alert(errMsg);
}
});
});
And on your php code:
<?php
$obj=json_decode($_POST['kite']);
print_r($obj->{'kite'});
?>
Not in an elegant way on passing the json..
but this way you can still capture "kite" as post variable and decode your desired json string.
I'm using jquery and jason sending data to another contoller, but when I send the data, I check it in fire bug and it's fine, It sends it correctly but in the target page, when I var_dump the $_REQUEST or $_POST is returns null.
I'm using codeigniter by the way.
This my jquery code:
<script type="text/javascript">
function GetMovieLanguageCategory(Language)
{
$.ajax({
type: "POST",
contentType: "application/json",
url: "/admin/movie/get_language_category",
data: JSON.stringify({"Language":Language}),
success: function(Data)
{
alert(Data);
},
failure: function(ErrorMsg) {
alert(ErrorMsg);
},
});
}
</script>
And in my Controller:
var_dump($_REQUEST);
//var_dump(json_decode($_POST['Language']));
And it returns:
array(0) {}
Am I wrong somewhere?
You are sending JSON data, but marking it as application/x-www-form-urlencoded data and you are trying to parse it as application/x-www-form-urlencoded data.
Change:
data: JSON.stringify({"Language":Language}),
to
data:{"Language":Language},
and let jQuery encode it properly for you.
If you want to encode it yourself (don't!):
data: "Language=" + encodeURIComponent(Language);
If you really want to send JSON:
contentType: "application/json",
data: JSON.stringify({"Language":Language}),
then, in the PHP, get the body of the request and run it through json_decode.