Return json from php to ajax - javascript

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

Related

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

How to transfer json string to another page using jquery's ajax method?

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.

Get parameter from JSON

In data from server I get the following JSON:
{
"response": {
"upload_url": "http:\/\/cs9458.vk.com\/upload.php?act=do_add&mid=6299927&aid=-14&gid=0&hash=73e525a1e2f4e6a0f5fb4c171d0fa3e5&rhash=bb38f2754c32af9252326317491a2c31&swfupload=1&api=1&wallphoto=1",
"aid": -14,
"mid": 6299927
}
}
I need to get upload_url. I'm doing:
function (data) {
var arrg = JSON.parse(data);
alert(data.upload_url);
});
but it doesn't work (alert doesn't show).
How do I get parameter upload_url?
It looks like you need to access arrg, not data. Also you need to access the 'response' key first.
function (data) {
var arrg = JSON.parse(data);
alert( arrg.response.upload_url);
}
There are several correct answers here, but there is one trigger that decides how you should handle your returned data.
When you use an ajax request and use JSON data format, you can handle the data in two ways.
treat your data as JSON when it returns
configure your ajax call for JSON by adding a dataType
See the following examples:
returned data string:
{"color1":"green","color2":"red","color3":"blue"}
ajax call without dataType:
$.ajax({
method: "post",
url: "ajax.php",
data: data,
success: function (response) {
var data = JSON.parse(response);
console.log(data.color1); // renders green
// do stuff
}
});
ajax call with dataType:
$.ajax({
method: "post",
url: "ajax.php",
dataType: "json", // added dataType
data: data,
success: function (response) {
console.log(response.color1); // renders green
// do stuff
}
});
In your case you probably used JSON.parse() when the call was already configured for JSON. Hope this makes things clear.
If response is in json and not a string then
alert(response.id);
or
alert(response['id']);
otherwise
var response = JSON.parse('{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}');
response.id ; //# => 2231f87c-a62c-4c2c-8f5d-b76d11942301
Your code has a small error. try:
function (data) {
var arrg = JSON.parse(data);
alert(arrg.response.upload_url);
});

jquery not properly serializing json in ajax call

Let me start by saying I am not extremely familiar with Javascript and I cannot figure out what is going on here.
I have the following function:
self.search = function () {
var searchTerms = {
"City": this.cityName,
"State": this.stateName,
"StoreNumber": this.storeNumber,
};
$.ajax("/api/SearchApi", {
data: searchTerms,
type: "POST", contentType: "application/json",
success: function (result) {
alert(result);
}
}
});
When I submit, what happens is that instead of submitting a nice JSON object as expected, it submits a JSON objected formatted as so: "City=testing&State=AL&StoreNumber=test "
Ideally I would like to use a GET method that passes the object to my server so that I can return the results, but when I use a get method, it simply appends the above to the API call url resulting in a URL request formed as so: http://localhost:57175/api/SearchApi?City=testing&State=AL&StoreNumber=test
Any help would be appreciated.
Make sure you add the dataType of JSON to your $.ajax({ }); object. That should solve the problem!
$.ajax({
// ...
data : JSON.stringify( searchTerms ), // Encode it properly like so
dataType : "json",
// ...
});
2 Things
Add the json content type(not the data type) to your ajax object important to note is the charset your server is using in this case utf-8.
Use the Json2 Library to stringify and parse Json when sending and retrieving it can be found here : https://github.com/douglascrockford/JSON-js/blob/master/json2.js
$.ajax({
url: URL,
type: "POST",
//Stringify the data you send to make shure its properly encoded
data: JSON.stringify(DATA),
//This is the type for the data that gets sent
contentType: 'application/json; charset=utf-8',
//This is for the data you receive
dataType: "json"
}).done(function(data) {
var dataYouGet = JSON.parse(data);
}).fail(function(xhr, ajaxOptions, thrownError) {
}).always(function(data) {
});

Can't query JSON using jQuery

I'm using jQuery to grab some JSON data. I've stored it in a variable called "ajaxResponse". I cant pull data points out of it; I'm getting ajaxResponse.blah is not defined. typeof is a string. Thought it should be an object.
var getData = function (url) {
var ajaxResponse = "";
$.ajax({
url: url,
type: "post",
async: false,
success: function (data) {
ajaxResponse = data;
}
});
return ajaxResponse;
},
...
typeof ajaxResponse; // string
ajaxResponse.blah[0].name // ajaxResponse.blah is not defined
make sure you specify option dataType = json
$.ajax({
url: url,
type: "post",
dataType: "json",
async: false,
success: function (data) {
ajaxResponse = data;
}
});
Q8-coder has the right of it, but to give you some details: your server is really passing back a string that you've formatted into JSON. You'll need to tell jQuery what to expect, otherwise it just assumes it received a string.
Add the following to your $.ajax options:
dataType: "json"
Also, refer to the jQuery API for examples and documentation for these options.

Categories