Passing this javascript object from jQuery to PHP? - javascript

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

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

value missing on AJAX response

I can't find what the error is in an AJAX call.
I have a PHP file output:
[{"value":"123","name":"My Name"}]
and this output is correct. And my AJAX call returns undefined after success:
$.ajax({
type: "POST",
url: "correct_file_location.php",
data: $(this.form).serialize(),
dataType: "json",
success: function (pk) {
alert(pk.value);
$("#label_id_name").text(pk.value);
},
error: function (){
alert("error");
}
});
Since the result is an array of objects, you need to first get the object from the array, and then access the properties of that object.
pk[0].value
should work.
*It is showing undefined because you are getting an array of objects and not only object *
try what #freedomn-m suggested in the comments
Try below code it will be work.
$.ajax({
type: "POST",
url: "correct_file_location.php",
//data: $(this.form).serialize(),
dataType: "json",
success: function (pk) {
var data1 = JSON.parse(pk[0].value);
console.log(data1);
// $("#label_id_name").text(pk.value);
},
error: function (){
alert("error");
}
}) ;
Your code will also work but your php response code must be in javascript object.
Please add below code in 'correct_file_location.php' and check with your ajax code.
'{"value":"123","name":"My Name"}';

unable to iterate through json array from $.ajax

I am facing some problem in assigning data to div on my view page.
The code is something like this:
$.ajax({
url: "/api/Flight/SearchFlight",
type: "Post",
data: $('form').serialize() + '&' + $.param({
'TokenId': $("#pageInitCounter").val()
}, true),
success: function(data) {
alert(data);
$('#responsestatus').text(data.Response);
$('#divResult').html(data);
});
Here, as you can see, I can see the whole data in alert box. also, I have assigned the whole data to div and i can see whole data perfectly on my page.
The Sample Response which i got back is a huge data so i am posting link for it http://pastebin.com/eEE72ySk
Now I want to iterate through each and every data but unable to do it.
Example:
$('#responsestatus').text(data.Response.ResponseStatus);
Then error is:
UncaughtTypeError:Cannot read property 'ResponseStatus' of undefined
Please Someone tell me what is wrong here. Why cant I iterate over data in response
You are getting your response back as a string, but trying to operate on it like it were a javascript object.
There is one of two things you could do
Tell the server you're expecting json data back
Parse the string response to json after it is received.
The first should be as simple as setting the datatype property on the request
$.ajax({
url: "/api/Flight/SearchFlight",
type: "Post",
datatype: 'json',
data: $('form').serialize() + '&' + $.param({
'TokenId': $("#pageInitCounter").val()
}, true),
success: function(data) {
$('#responsestatus').text(data.Response.ResponseStatus);
});
The second involves parsing the response before using it
$.ajax({
url: "/api/Flight/SearchFlight",
type: "Post",
data: $('form').serialize() + '&' + $.param({
'TokenId': $("#pageInitCounter").val()
}, true),
success: function(data) {
var result = JSON.parse(data);
$('#responsestatus').text(result.Response.ResponseStatus);
});
Use Json datatype..i wrote a sample here..
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});

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)

Ajax call not sending to POST

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

Categories