JSON is quite confusing and I haven't been able to find a post that can help me so I decided to ask the question myself.
Quick Summary
I need my php array to show up as [object Object] for every array containing an id, label,and type -- when passed through to my JavaScript using json. Here is what I've tried:
if( $node_id == NULL ) {
echo json_encode(array(
0 => array( array("id" => 1, "label" => "A lunch", "type" => "folder"), array("id" => 2, "label" => "A lunch", "type" => "folder"))
));
}
When I run this code I keep getting my alert to display:
{"0":{"0":{"id":1,"label":"A lunch","type":"folder"},"1":{"id":2,"label":"A lunch","type":"folder"}}}
when it should look like
[object Object],[object Object]
so could someone please help convert it to that format through json, or however it might be done?
You're alerting a string, so it seems that jQuery is not recognizing your response as JSON, and it is not being parsed. Try this:
$.ajax({
url : "php/resource.php",
data : { node_id: node_id },
dataType : "json"
}).done(function(data) {
alert(data);
return callback(null, data);
}).fail(function() {
return callback("AJAX error");
});
Also, you may set content type to application/json in your php
header('Content-Type','application/json');
Related
I'm a React Native beginner, please excuse basic questions. I'm having trouble handling json returned from PHP in react native using axios get.
My php returns (have tried both with and without headers part, and also tried with/without json_encode):
<?php
$json ="[{
id: 1,
title: 'List Item One',
description: 'test1'
},
{
id: 2,
title: 'List Item Two',
description: 'test2'
}]";
header('Content-Type: application/json; charset=utf-8');
echo json_encode($json);
My react native function is below (with the part I'm trying to get to work commented out)
const [messages, setMessages] = useState([]);
useEffect(() => {
loadMessages();
}, []);
const loadMessages = async () => {
let res = await axios.get('https://example.com/test_messages.php');
//setMessages(res.data);
console.log(res.data);
}
return (
<Screen style={styles.screen}>
<FlatList
data={messages}
keyExtractor={message => message.id.toString()}
renderItem={({item}) => (
The console.log seems to work and returns:
[{
id: 1,
title: 'List Item One',
description: 'test1'
},
{
id: 2,
title: 'List Item Two',
description: 'test2'
}]
but when I try to use the commented part instead, I get this error:
"undefined is not an object ('evaluating message.id.toString')"
It seems to just be formatting the output because the console.log seems fine. Further, when I hard code the array into a variable and use it in the useState function, it works fine also.
The format of this json maybe incorrect, you can check it at https://jsonlint.com/. The correct format should be like the output of JSON.stringify below
I need to iterate through data that get via JSON with this code:
setInterval(function() {
console.log("running");
$.ajax({
type : 'get',
url : 'data.txt',
dataType : 'json',
success : function(response) {
console.log(response.bookings) // returns undefined
$.each(response.bookings, function(index, booking) {
sc.status(booking.seat_id, 'unavailable');
console.log(booking.seat_id); // returns nothing
});
}
});
}, 3000); //every 3 seconds
The data is currently formatted like this:
[{
"bookings": [
{
"seat_id": "1_4"
},
{
"seat_id": "4_2"
}]
}]
But that doesn't seem to be working. What is the correct format that I need to use? I tried a ton of options but can't get it working.
UPDATE:
The error I now get in the console is:
jquery-1.11.0.min.js:2 Uncaught TypeError: Cannot read property 'length' of undefined
at Function.each (jquery-1.11.0.min.js:2)
at Object.success ((index):145)
at j (jquery-1.11.0.min.js:2)
at Object.fireWith [as resolveWith] (jquery-1.11.0.min.js:2)
at x (jquery-1.11.0.min.js:4)
at XMLHttpRequest.b (jquery-1.11.0.min.js:4)
and line 145 is:
$.each(response.bookings, function(index, booking) {
You have options here. key value {"key":value} or {"name":john} is one way. You can do more info like "employee":{ "name":"John", "age":30, "city":"New York" }
as you said I think you are response.bookings array like this $arr = [1,2,3,4,5];.
if you iterate like below
$.each($arr,function(i,k){
console.log(i,k)
})
you will get output 0,1 1,2 2,3...
but I didn't get booking.seat_id means..? can you give us booking array format?
I finally found the solution. Thank you to everyone who helped. It's pretty simple and stupid. I only had to change the JSON response from:
[{
"bookings": [
{
"seat_id": "1_4"
},
{
"seat_id": "4_2"
}]
}]
to
{
"bookings": [
{
"seat_id": "1_4"
},
{
"seat_id": "4_2"
}]
}
Basically get rid of the []
I chose to use JIT.js rgraph for a project I am working on. What I've done was taken the examples and began slowly merging the js into the projects core files. Simple! The hang up I've run into has me literally stumped.
example.js has (assumed to be hand written at some point) json like so.
var json = {
id: "190_0",
name: "Pearl Jam",
children: [{
id: "306208_1",
name: "Pearl Jam & Cypress Hill",
data: {
relation: "<h4>Pearl Jam & Cypress Hill</h4><b>Connections:</b><ul><li>Pearl Jam <div>(relation: collaboration)</div></li><li>Cypress Hill <div>(relation: collaboration)</div></li></ul>"
},
children: [{
id: "84_2",
name: "Cypress Hill",
data: {
relation: "<h4>Cypress Hill</h4><b>Connections:</b><ul><li>Pearl Jam & Cypress Hill <div>(relation: collaboration)</div></li></ul>"
},
children: []
}]
},...
I need the json file dynamically generated in a sense and the most productive way for me to use the json is to create a static file if/when relative parts of the project are updated instead of generating json every time the page loads. Makes sense right?
json.php looks like this
$project = array(
"id" => "1",
"name" => "Testing Project",
"children" => array (
"id" => "2",
"name" => "Sub 1",
"data" => array(
"relation" => "<h4>Testing Project</h4><b>Structure:</b><ul><li>Sub1</li><li>Section 1</li></ul>"
),
"children" => array(
"id" => "3",
"name" => "Section 1",
"data" => array(
"relation" => "<h4>Section 1</h4><b>Structure:</b><ul><li>Testing Project</li><li>Sub 1</li></ul>"
),
"children" => ''
)
)
);
// header('Content-type: application/json'); /* DOES NOTHING */
echo json_encode($project);
my Arrays are hand written at the moment to make sure the process works as intended before programmatically generating the arrays from the database. There are other pieces to the puzzle I do not believe are at all involved at this time but the next piece we need to look at is the ajax call to fetch json.php which is in my custom.js file.
function init() {
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': true,
'url': 'js/json.php',
'dataType': "json",
'success': function (data) {
json = data;
console.log(data);
}
});
return json;
})(); ... continue with JIT.js functions
I added console.log(data) to see if the json was coming back formatted and this is what that looks like console.log screenshot using custom.js ajax call So then I reused the example.js file and console.log(data) give us console.log screenshot using example.js
The only obvisou difference is that the example.js json is be represented as an array, not an object. Even stranger still is that when I run the example using the custom.js file with the ajax call "Testing Project" does appear on the graph but no children elements. In the screenshot for custom.js console.log shows all the children elements as children: object, not children:Array[] like example.js
My first thought was to see if I can ensure that all json_encoding forced the associative arrays into "arrays". And yea... lots of time wasted looking at the obvious. So my next thought was it must be in the formatting. example.js used [{ for each child element but json_encode does not. I cannot locate any information to confirm if that really is the problem or not, but, none the less I cant rule that out. I also checked into sequential indexes. example.js certainly does not have sequential indexes. I even went ahead and sorted the arrays before encoding json_encode(array_values($project)); to see what happens and while it outputs to a browser with indexes it of course shows nothing in the graph.
I feel like im spinning in circles ( not in the good eagle circling prey kinda way ) but getting to far off focus to figure this out. I need some fresh perspective and ideas what might be going wrong.
**Edit
I've also tried to convert the strings manually with PHP. still not working. Any ideas?
WOW, Just over 24 hours and I end up doing something like this. It works by making each child with content an array of arrays.
$test = array(
'id' => "1",
'name' => "testing sample",
'children' => array(
array(
...
),array(
...
'children' =>array(),
),
)
);
echo json_encode($test);
I have a textarea that I want to submit via ajax. When I try to output the value, I only get [object Object]
Jquery (ajax)
$("#insertAddresses").click(function() {
$.ajax({
type: "POST",
url: "insertAddr.php",
data: 'addresses=' +
}).done(function(list) {
//getList(); // run query to get addresses and populate list
});
});
PHP (i've tried)
$_POST['addresses'];
or
$addresses = explode("\n", $_POST['addresses']);
Regardless of anything i've tried, always returns
[object Object]
Help?!
Your serverscript is returning a json object, which is correctly recognized by JavaScript as an object. You can do a whole lot of things with that object, but you can't just put it on your website, as it is not html or text.
Here is a short description of json: http://en.wikipedia.org/wiki/JSON
I don't know how your data is structured, so i can't tell you how you can access your data. But in a json like this (example from wikipedia):
{
"firstName": "John",
"lastName" : "Smith",
"age" : 25,
"address" :
{
"streetAddress": "21 2nd Street",
"city" : "New York",
"state" : "NY",
"postalCode" : "10021"
},
"phoneNumber":
[
{
"type" : "home",
"number": "212 555-1234"
},
{
"type" : "fax",
"number": "646 555-4567"
}
]
}
You could, ie., excess the firstName simply with:
data.firstName
An voila, there is your excpected data.
You're data should be an object:
data: { adresses: "value" }
Just a little tip: the shorthand ajax-call for what you're doing in jQuery is $.post(.... and then you can lose the "type". Does exactly the same, but I think it's just a little neater.
I've been trying to get DataTables to work with my existing Ajax search function - which works by itself.
I have the following code:
$('#SearchResults').dataTable({
"bProcessing": true,
"bServerSide": true,
"bRetrieve": true,
"sAjaxSource": "process.php?action=searchArtifact",
"fnServerData": function (sSource, aoData, fnCallback){
aoData.push({
"name": "searchName",
"value": $('#ArtifactSearch').attr('value')
});
$.ajax({
"dataType": "json",
"type": "POST",
"url": sSource,
"data": aoData,
"success": fnCallback
});
}
});
The PHP is returning a valid JSON object (using JSON_FORCE_OBJECT):
{"0":{"ARTIFACT_ID":"4E2FE3BCE356C","ARTIFACT_NAME":"123","ARTIFACT_TYPE":"UI","ARTIFACT_LABEL":"Test_Int_EAS_123","ARTIFACT_LOCATION":"Int","ARTIFACT_DOMAIN":"ABC","ARTIFACT_AUTHOR":null,"REGISTERED_EMAIL":"test#test.com","REGISTERED_DATE":"27-07-2011","REGISTERED_TIME":"11:09:00"}
I can see this all fine in FireBug, but my empty table is not being populated with this data.
Any ideas?
#Kyle: Errr - thats it. I guess I don't have one? This is my first attempt (struggle) with DataTables and I'm just copying from the documentation: http://www.datatables.net/usage/callbacks#fnServerData
#MarcB: Added that - but still no data displayed. Thanks for the help
I was having a similar problem. Turns out I wasn't forming the JSON response properly. This worked for me:
<?php
$arr = array ('aaData' => array(
array('3','35','4', '$14,500', '$15,200','$16,900','5','1'),
array('1','16','4', '$14,200', '$15,100','$14,900','Running','1'),
array('5','25','4', '$14,500', '$15,600','$16,900','Not Running','1')
)
);
echo json_encode($arr);
?>
This plugin expects the returned JSON object to be an object, with a property which is an array of arrays. This property should be called 'aaData'. You are not returning an object; you are just returning the array.
Check out this json resource example from DataTables.net: http://datatables.net/examples/examples_support/json_source.txt. Notice that you are returning json with brackets as compared to the example's braces.
you can remove the $.ajax part, instead you can use the $.getJSON method.
You can also add the following to avoid adding an extra object like "aaData":
"sAjaxDataProp": ''
What are you setting sEcho to?
Your JSON should have this structure:
{
"sEcho": 'refer to "sEcho" in $_GET or $_POST; don't forget to sanitize',
"iTotalRecords": 'for pagination',
"iTotalDisplayRecords": 'number displayed',
"aaData" => { /* your data here */ }
}
This is a few years late but might help someone. :)
DataTable cannot render null values. See defaultContent to set content when data return is null.
See link: https://datatables.net/reference/option/columns.defaultContent
For legacy dataTables, see http://legacy.datatables.net/ref and search for sDefaultContent