Ajax call not sending to POST - javascript

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);
}

Related

Complete JSON being outputed

The output consists of the complete JSON, which is:
{reply:"Login success"}
The expected output is only the value for the key 'reply' ,
Login success
The required code:
HTML
<div id="resp" style="color:red;"></div>
JS AJAX JQUERY
$.ajax({
url: 'tt.php',
method: 'POST',
data: {'pass': pass , 'uname':uname},
success: function(data) {
document.getElementById("resp").innerHTML = data;
}
});
PHP
$data['reply'] = "Login Success";
echo json_encode($data);
Solutions tried to print the necessary data
data[0]
data[1]
data[reply]
data.reply
data["reply"]
The PHP code you show us is not outputting what you say your expected output should be but, you can tell the AJAX call to expect JSON to be returned by adding dataType: 'JSON', to the properties of the call.
Then you can address the reply as data.reply
$.ajax({
url: 'tt.php',
method: 'POST',
dataType: 'JSON', // added this line
data: {'pass': pass , 'uname':uname},
success: function(data) {
// then you can address the reply like this
document.getElementById("resp").innerHTML = data.reply;
}
});

Pass variable via ajax to api.php

I am trying to pass a js variable via ajax to the php side. My js code is:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
var sAgentId = 'hi'
$.ajax({
url: "api-test.php",
method: "POST",
data : { id:sAgentId}
}).done(function(){
console.log('done')
})
and in the php file, I am trying to get the variable via post:
$sAgentId = $_POST['id'];
But finally in api i get the notification that says
Notice: Undefined index: id in C:\xampp\htdocs\webdev-php-exam-prep\exercise\api-test.php on line 2
Can anyone tell me what I am doing wrong?
Try adding this to your AJAX method:
dataType: "json"
Try also console logging the response back to check $_POST['id'] is being set.
.done(function(data) {
console.log("Data: ", data);
});
and in your PHP just return $_POST['id']
var sAgentId = 'hi'
$.ajax({
url:'api-test.php',
type: "POST",
data: {id: sAgentId },
cache: !0,
dataType: 'json',
success: function(data) {
console.log(data);
}
});
try replace method by type:
type: "POST",

PHP $_POST empty during AJAX post request

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)

Return json from php to ajax

I'm trying to get back a json object from php to then use in my ajax.
My ajax is
$( document ).ready(function() {
var eventsListPath = "/php/eventsList.php";
$.ajax({
type: 'get',
url: eventsListPath,
data: {},
success: function(data) {
var json = JSON.parse(data);
$('#eventInformation').html(json[table]);
}
});
});
and then my php does stuff but I basically want to return a string (plus more, but getting the string to work first would probably help the rest):
$obj->table="hey";
echo json_encode($obj, JSON_UNESCAPED_SLASHES);
But the line
$('#eventInformation').html(json[table]);
seems to only give me back an error:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
What am I doing wrong?
first, use the Network Monitor to see the result of the HTTP request
e.g. in Firefox : https://developer.mozilla.org/en-GB/docs/Tools/Network_Monitor
then, try this code who let jQuery do the JSON parsing in the AJAX call :
$(document).ready(function () {
var eventsListPath = "/php/eventsList.php";
$.ajax({
type: 'get',
url: eventsListPath,
data: {},
result: "json"
success: function (dataJson) {
$('#eventInformation').html(json.table);
}
});
});
Try to use . operator, also there is no need to parse the JSON string it is already in JSON form :)
$(document).ready(function () {
var eventsListPath = "/php/eventsList.php";
$.ajax({
type: 'get',
url: eventsListPath,
data: {},
success: function (data) {
$('#eventInformation').html(data.table);
}
});
});
ON PHP, ensure that you are instantiating the response data like below
$obj = new StdClass;
$obj->table="hey";
First of all you should check the response is properly parsed as json. if any data is present before the json array, javascript will throw exceptions. Use the chrome's developer tools response tab in the network option for seeing the response. If it's ok , try the below code.
$(document).ready(function () {
var eventsListPath = "/php/eventsList.php";
$.ajax({
method: "get",
url: eventsListPath,
dataType : "json",
data: {}, //data
success: function (data) {
$('#eventInformation').html(data.table);
}
});
});

Passing this javascript object from jQuery to PHP?

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
});

Categories