I am trying to learn how to retrieve data from a json obj that I return from PHP but I can not figure out how to get the values. My data looks something like this:
[{"user_name":"herp"},{"email":"herp.derp#gmail.com"},{"yy":"yyyy"},{"mm":"mm"},{"dd":"dd"}]
My client-side script looks something like this:
$.ajax({
type : 'POST',
url : 'serverside/get_installningar.php',
dataType : 'json',
success : function(data) {
}
});
I would like to type something like data.user_name to retrieve the user_name and so on. But is there a method for doing this? I have looked in the forum but can't find the right thing.
What you have is an array of objects and so you going to need to know where it is to get user_name,
data[0].user_name
see below for structural details,
[
{"user_name":"herp"}, // <-- data[0]
{"email":"herp.derp#gmail.com"}, // <-- data[1]
{"yy":"yyyy"}, // <-- data[2]
{"mm":"mm"}, // <-- data[3]
{"dd":"dd"} // <-- data[4]
]
As AndrewR pointed out,
This will work, but it would be better to fix the JSON format coming from PHP. {"user_name":"herp","email":"herp.derp#gmail.com","yy":"yyyy","mm":"mm","dd":"dd"} and then his original plan will work.
as of jquery 1.4.1 you can do this natively
jQuery.parseJSON
Do that on the data.responseJSON to convert to JS object.
See How do I convert a JSON string to a JavaScript object in jQuery?
Use data.parseJSON();. It returns an object exactly the way you want it.
You are actually returning an array not a json object
Your data needs to look like this:
{{"user_name":"herp"},{"email":"herp.derp#gmail.com"},{"yy":"yyyy"},{"mm":"mm"},{"dd":"dd"}}
Try installing Firebug to debug the return value of your page if its a properly formatted JSON.
use it like:
console.log(data[0].user_name);
For a easy acces members of your json, try virtualising it in a nice format so you can understand where you have array and where you have object.
[] means array
{} means object
I recommand a chrome extension: JsonView
and for example, take a JSON request like this.
Just open it in a tab and it will be nicely formated.
Also it shows you in the bottom left corner how to access what you are hovering over.
Related
Assume I have this object in JavaScript which is built like this:
var obj = {};
var fields = ['table_name[field_name]', 'tale_name[field_name_2]']
for(var i; i < fields.length; i++){
obj[fields[i]] = someBulkOfData;
}
when logged in the console, obj will output
{
table_name[field_name] : {...},
tabke_name[field_name_2] : {...}
}
This works all fine, until I pass the object through PHP by jQuery.ajax().
When I receive my request in PHP, the array looks as follow:
[
['table_name[field_name'] => ...,
['table_name[field_name_2'] => ...
]
So what happens here is that somewhere between sending the AJAX-request and receiving the data in PHP, the last square bracket of every key dissappears.
Could someone explain to me why this happens, and if there is a neat way to solve this problem?
I have one criteria for the solution, and that is that I cannot change the keys (as in something like 'table_name\[field_name\]').
have you tried using $.serialize()?
use serialize to turn a javascript object into a string that can be transmitted with AJAX easily - like this:
var ajaxableString = $(obj).serialize();
You could solve that issue by restructuring your JS object:
{
table_name : {
field_name_1 : {...},
field_name_2 : {...}
},
another_table : {
...
}
}
That way you avoid that weird naming convention.
Also, I suspect you are hiding something from us. There is something (an operation) between the this and PHP, maybe somewhere in your AJAX code, that you are not telling us. Maybe you are serializing this object into a string and passing the string as one query parameter to the server. This serialize step might be the cause.
But just to be sure, you can check the Net section of the debugger and check the request headers if the data sent is formatted perfectly.
As far as I know, jQuery.ajax accepts a JS object as data, and perfectly converts it into querystrings. By that, you don't need to serialize it manually.
The solution is, thanks to #fab , to encode the data with JSON:
$.ajax({
data : {
obj:JSON.stringify(obj)
},
...
});
In PHP:
json_decode($_REQUEST['obj']);
This will output a perfectly nice stdClass object, with preserved keys.
I have an AJAX request that fetches some info from a SQL database in PHP.
The problem is, I need to send it back to AJAX in variables. Not to just echo it all out on screen.
Is this possible? If so, how would I go about doing something like this?
Thanks.
Yes, you could json_encode the variable you want to send back to client.
echo json_encode( array('variable' => 'your value' ) );
The client will receive the data through a callback when the request is completed. Without more clarification on specifics that's all i can offer, with some more details i can provide code samples depending on whether you're using a JavaScript library such as jQuery or doing a raw XHR request.
Edit: so in jquery to retrieve the variable above you would do the following.
$.getJSON('yourfile.php', function(data){
console.log( data.variable );
});
If I understand you right, you'll want to build a php array and use json_encode to dump the array out as your response. Then in JS you can use the resutling JSON text to form an object.
ajaxpage.php
$resultArray = buildArrayOfItems('Select * from products order by price');
//I usually have my sql records returned directly as an array.
//that's all buildArrayOfItems does
die(json_encode($resultArray));
The PHP should yield something like this
results
{[
{
"id" : "2643",
"name" : "Leather Jacket",
"price" : "249.99"
},
{
"id" : "2645",
"name" : "Suede Jacket",
"price" : "289.99"
},
...
]}
and your JS will look like this (if you're using jQuery)
JS
$.getJSON('ajaxPage.php', {'someVariable':'someValue'}, function(obj){
console.log(obj.count); //will show number of resulting items
console.log(obj[0].id); //will show id of first item (2643)
});
//If you do not use jQuery, you'll need to use eval() or something evil like that
//to convert the string to an object
This site has a great example regarding what you're trying to achieve. http://ditio.net/2008/07/17/php-json-and-javascript-usage/
In short you'll want to use php's json_encode() to convert an array into a json compatible string and each that back to the client.
If you're using jQuery then you'll need to dataType property of $.ajax() to "json", from there you can interact directly with the response as a json object.
If you're using the standard XmlHttp.
var json = JSON.parse(xmlHttp.responseText);
You can always return something like:
echo "code you need to send back to AJAX &&& response text"
Then you can subdivide it into 2 variables with text.split("&&&").
So I'm building a web application and I have an ajax request that pings a database (or database cache) and echos back a big thing of json. I'm totally new to json, and when the php pulls from the database I echo json_encode($databaseResults), then it shows up in my html page as a long string. My question is, how do I convert it and pull out the pieces I need into a nice format?
Thanks!
The Json result that was in the page looks like:
"[{\"currentcall\":\"1\",\"timecalled\":\"15:30\",\"etaTime\":\"15:35\",\"departmentID\":\"1\",\"memberID\":\"1\",\"callinnum\":\"1\",\"location\":\"Fire House\",\"billed\":\"N\",\"date\":\"2\\/12\\/11\",\"firstName\":\"Phil\",\"lastName\":\"asdf\",\"email\":\"pasdf#gmail.com\",\"homephone\":\"+19111111111\",\"cellphone\":\"+11234567891\",\"cellphone2\":null,\"workphone\":null,\"phonenumber5\":null,\"phonenumber6\":null,\"streetAddress\":\"10 asdfnt Dr\",\"city\":\"\",\"username\":\"pgsdfg\",\"password\":\"0623ab6b6b7dsasd3834799fbf2a08529d\",\"admin\":\"Y\",\"qualifications\":\"Interior\",\"rank\":null,\"cpr\":null,\"emt\":null,\"training\":null,\"datejoined\":null,\"dateactive\":null,\"state\":\"DE\",\"zip\":\"51264\",\"pending\":\"NO\",\"defaultETA\":\"7\",\"apparatus\":\"asdKE-286\"}]"
There can be multiple results... this is only one result
EDIT:
Basically, I'm trying to pass a bunch of rows in an array into an html file, and take out only the data I need and format it. I don't know if json is the best way to do this or not, just one solution I came up with. So if anyone has a better solution that would be awesome.
Edit2:
This is the jquery I have that makes the request, the php just has echo json_encode ($DBResults);
function getResponder(){
var responders = $.ajax({
type : "POST",
url: "/index.php/callresponse/get_responders",
success: function(html){
$("#ajaxDiv").html(html);
}
});
setTimeout("getResponder()", 10000);
}
As you flagged this as jquery I assume that you're using jQuery. If you're only going to get the one string you can skip the json part and use jQuery .load() like this $('#result').load('ajax/test.php'); that will load the contents from ajax/test.php into #result
However if you want to use json you can take a look over at getJSON on the jQuery documentation. You can also use the jQuery parseJSON function which will return the json an javascript object containing the jsonData.
Here's an example how you can use parseJSON
var object = $.praseJSON(jsonString); //jsonString is the string containing your actual json data
alert(object.location) //Will alert "Fire House" with the given json string
Here's an example of how you can use getJSON in the same way
$.getJSON('ajax/test.php', function(object) {
alert(object.location); //Will alert "Fire House" with the given json string
});
If you want to pass parameters as well you can do it like this
$.getJSON('ajax/test.php',
{
Param1 : "Value1",
Param2 : "value2"
},
function(object) {
alert(object.location); //Will alert "Fire House" with the given json string
}
);
If you are trying to send json from javascript to php you can use
$jsonArray = jsonDecode($_GET['key']);
Of course if you're using post you'll write $_POST instead.
You have to parse the data into a JSON object, then you can use properties of the object as you wish.
Without seeing the specifics, I can tell you that you'll need to use the JSON object to parse the text. See more here: http://www.json.org
var obj = JSON.parse(ajaxResponseText);
You should use php function json_decode which will give you an object or array with all the properties.
Then you should iterate recursively through this object and add the content of the properties to a string, which should be your final HTML.
Normally to display JSON response in an html element after jquery(for example) by web request, try this:
$("#box-content-selector").append(
"<pre>"+
JSON.stringify(JSON.parse(data), null, 4)+
"</pre>"
)
I have a global variable I'm using to store a bunch of information in a project I'm working on. It is an object with various values and I guess other objects in it. For example...
$.myVar {
currentProj : "Project 1",
allProjs : [],
toggleVar : 0
}
Now as the program runs and I do things, I'm actually adding arrays within allProjs. I want to use the array index as the name of the project, and then it contains a bunch of information. Here is a sample of what the object looks like after running the program for a few minutes.
(copied from Chrome's console):
$.myVar
Object
currentProj: "McB2"
toggleVar: 0
allProjs: Array[0]
McB1: Array[0]
length: 0
__proto__: Array[0]
McB2: Array[4]
0: "02070124"
1: "02030036"
2: "02090313"
3: "02090450"
length: 4
Now I want to pass this data to a PHP file using $.post so I can convert it to JSON and save it on the server.
I do this basically by just running:
$.post('saveJSON.php', $.myVar, function(data) {
$('#dumpspace').html(data);
});
For debugging I've got the PHP file just outputting:
print_r($_REQUEST);
Now I would expect a multi-dimensional array that I could convert to JSON and then save, but all it is spitting out is:
Array ( [currentProj] => McB2 [toggelVar] => 0 )
So I can see that it's not sending the the allProj section of the object, but I'm not sure why! It does seem to show up when I look at the object in the console, so I'm not sure what I'm missing.
Any help is appreciated.
Thanks!
Clarification
The first section, where I declare allProjs, is it possible I'm doing something wrong there? When I run Stringify, I end up with a similarly wrong result:
JSON.stringify($.myVar)
"{"currentProj":"McB2","allProjs":[],"toggleVar":0}"
You need to .stringify the object / array into a JSON string. All "modern" browsers do support this natively with JSON.stringify(obj). If you need to support "older" browser version aswell, you need to go to http://www.json.org and download the json2.js lib which offers the same functionality.
The other way around, if you want to receive a JSONized string from a server, you need to either tell jQuery that you're expecting a json string by passing 'json' into your $.post() call, or you need to parse the received data yourself by again accessing the JSON object. JSON.parse(json_string) will return a Javascript object from a passed in JSON string.
Figured out my problem. When I was declaring the object originally I was making allProj and Array by putting in []. If I put it in as allProj : {}, then it works perfectly! Thanks for the suggestions, helped narrow down my mistake.
-M
I believe you must first convert your array to the JSON format before posting to PHP.
This is the method I have used in the past:
var jsonOb = JSON.stringify(yourArray);
$.post(
"yourPage.php",
{jsonOb:jsonOb},
function(r){
//your success response
}
);
Hope this does the trick brother!
W.
ok, i guess I need help ! I searched with every keyword I could think off, but I still cant figure out, please help. Am more of a php guy, and I've just started with jQuery.
Basically, what I am trying to do is to send a jQuery post from a click function. And based on whatever is returned by my php function, show/hide 2 divs. My php function returns a "json_encode" array with 2 simple values, like such :
//==================PHP code ==================================
$message_for_user = "blah blah";
$calculatedValue = 1230;
$responseVar = array(
'message'=>$message_for_user,
'calculatedValue'=>$calculatedValue
);
echo (json_encode($responseVar));
//==================PHP code End ==================================
My javascript code is supposed to accept the values returned by php :
//==================Javascript code ==================================
$("div.calculator_result").click(function()
{
$.post('myCalculator.php' ,{qid:itemID},function(response)
{
$("div.calculation_value").show(500).html(response['calculatedValue']);
$("div#message_for_user").show(500).html(response['message']);
}
}
//==================Javascript code End ==================================
Unfortunately, on the javascript side of my project, the divs are not updated with the values returned by my php functions .... where am I wrong? I hope I was clear in my question, if not, do let me know, and I shall provide any extra info required.
Another thing is that earlier, I was echo'ing only a single value, that is the calculated value (echo $calculatedValue), and everything worked fine, its only after I shifted to echo'in the json encode array that things dont work
var json = $.parseJSON(response); alert(json.message);
Try setting the dataType option:
$.post('myCalculator.php' ,{qid:itemID},function(response)
{
$("div.calculation_value").show(500).html(response['calculatedValue']);
$("div#message_for_user").show(500).html(response['message']);
}, 'json');
NB I have also added the closing brackets ) where you have missed them.
You must parse the JSON response. jQuery has this built-in functionality (thankfully, because otherwise IE6 and 7 don't natively support JSON). Set a variable equal to this:
$.parseJSON(response)
And then, if you're not familiar with JSON format, check the response headers (using Firebug or similar,) and that will help you pick which keys' values you want. If you're looping, I would look into for in statements once the response has been parsed.
EDIT: Using $.getJSON, the parsing is done automatically. Write less, do more. :)
All you gotta do, its tell the Ajax call that you're receiving data type "json". In other words...
$.ajax({
url: "external_file",
method:"post",
dataType: "json", // **************** Note dataType****************
success:function(response){
console.log(response)
// Response will be a javascript array, instead of a string.
},
error: function(){
alert('something went wrong.')
}
})