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.
Related
My questions keep getting abandoned even though I am replying, so I am going to remake my question in the hopes that someone can see my error and help me out. I will try to be as thorough as possible.
Step 1: I have an array named divisionsLarge in the following form:
divisionsLarge = [{ "car":"Toyota", "color":"blue", "numberTires":"four" }, { "car":"Honda", "color":"red", "numberTires":"four"}, etc. etc. ... ]
(This data is fictional, but it's the process that is wrong somewhere (also ignore the fact that numberTires is being stored as a string instead of a int, it's fictional folks :P)
Anyway, I have 92 of the above entries, all with the same keys: car, color, and numberTires.
Now, I go through the array with the following function loop in order to build an array with just car & numberTires key:
var divisions = [];
for (var i = 0; i < divisionsLarge.length; i++) {
if(divisionsLarge[i].numberTires != "two"){
var obj = { "car": divisionsLarge[i].car,
"numberTires": divisionsLarge[i].numberTires};
divisions.push(obj);}
}
Ok, at this point, I THINK everything is good to go. If I use the console in FireBug and type in divisions[0] I get a beautiful object that consists of, for example,
Object { car = "Toyota", numberTires = "four"}
(I think there are still "" around the car & numberTires entries, this is just how FireBug displays the object, I could be wrong)
Now here's what I need help with. I've created more .ajax queries than I can count. I've used JSON.stringified, I've not used JSON.stringified, I've used json_decode(), I've just done print_r($_POST)...I've done so many things that I am completely unable to analyze what is affecting what in order to diagnose what the problem might be. It seems my .ajax POSTS might be wrong, it seems my PHP might be wrong. So here are the questions I would GREATLY appreciate being answered:
1) Is the divisions array being created by the javascript considered JSON, or in a format easily converted to JSON?
2) What does my AJAX call need to be? I have tried so many AJAX calls that I have NO idea what is considered right/wrong. Also, please use divisions and not the snippet of the array I provided above, as the divisions array is dynamically generated by what's contained in divisionsLarge.
3) What does my divisions.php PHP file need to look like? Right now it has an HTML skeleton around it with <script></script> tags that reference divisionsLarge.js and divisions.js [do these need to be in one .js file?] I have seen blank pages and Array() for so long that I'm even doubting the rest of the PHP file now.
4) How do I get, for example, the color value of the first index? This seems rudimentary but most examples that I see are just querying an array of just one object, e.g. echo $_POST["color"], but I have multiple entries of color, so I'm not sure how to just ask for the first one. I would like to know this mostly because I have had such bad success with testing whether the array is working or not - I have lost all faith in print_r($_POST) and var_dump($json).
Okay, First your questions. Then the code:
1.- Divisions is not considered JSON, it is just an object array. All javascript objects can easily be turned into JSON using JSON.stringify(); Look at the code below.
2.- Look at the code below.
3.- I am not sure what kind of processing you need in your PHP. The code below assumes you are posting this to another page, where you will do some processing and output something, that you can use in the complete function.
4.- Look at the code below.
I think this is what you want to do:
Javascript
divisionsLarge = [{ "car":"Toyota", "color":"blue", "numberTires":"four" }, { "car":"Honda", "color":"red", "numberTires":"four"}];
var divisions = [];
for (var i = 0; i < divisionsLarge.length; i++) {
if(divisionsLarge[i].numberTires != "two"){
var obj = { "car": divisionsLarge[i].car,
"numberTires": divisionsLarge[i].numberTires};
divisions.push(obj);}
}
//I am just going to send one of your array elements as a JSON object.
var postData = JSON.stringify(divisions[0]);
var url = "url where you want to post your data";
$.ajax(url, {
type: "POST",
data: { "jsonBeingSent" : postData },
success: function(data) {
//Do whatever you need to do with your PHP output here.
//If you are using something like my php sample then you will be receiving a JSON object(s)
}
});
Now, on your PHP you probably want something like this:
<?php
//You may want to do some checking about the sender, and so on.
$receivedData = json_decode($_POST['jsonBeingSent']);
//You should see something like this if you print_r $receivedData
// object(stdClass) {
// [car] => ...
// [numberTires] => ...
// }
//So you could access the car value like this
echo $receivedData->{'car'};
//Do your processing and then, if you are using an array or object you can use `json_encode()` to output your data.
?>
Hope that helps.
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.
In an earlier post today the answer has led me down the route of using a JSON feed to populate elements in my page.
Something new to learn!!
the JSON data is created from a PHP script which retrieves the data from a Mysql database. The php script retrieves a specific record which I need to pass to the php script with the getJson call.
I've had success with creating the url with the parameters added as a GET method but I can't find an example of a POST method - the parameters should go as an optional parameter. here's what I have so far...
function loadData(index) {
alert(index);//debug
$.getJSON('loadJSONholeData.php' ,
{hole: index} ,
function(data) {
I've found examples for a twitter feed which shows a parameter like option: "cat", but can't find an option where the value is in a variable.
I don't understand how to use the parameters - where am I going wrong. Appreciate this is probably a fundamental issue but I'm learning.
Thanks
Update:
I've revised the code per the responses below and used both suggestions to pass the POST parameter, but the receiving PHP code is not reading the POST parameter and just returns the default query values.
I even used as static value of 1 both as a value and as a string but no joy.
Here's my receiving PHP code which accesses the POST values:
$hole = 3;
if (isset($_POST['hole'])) {
$hole = $_POST['hole'];
}
I'm missing something basic here. The value in 'index' definitely exists as it shows in the debug and JSON data is being returned )(but the default). I can go back to my GET method but want to see this work!!
Thanks
Update: Success!!
I played around further with the revised code. I removed the content type parameter from the code and it all works now, the PHP is returning the correct query.
I assume then that by specifying the JSON type in contentType it passes the POST parameter in a different way to PHP which expects it in anpther way?
Onwards and upwards - thanks
The $.getJSON() method does an HTTP GET and not POST. Try something like this -
$.ajax({
url: 'loadJSONholeData.php',
data: JSON.stringify({hole: index }),
type: 'POST',
contentType: 'application/json;',
dataType: 'json',
success: function (result) {
//(result.d) has your data.
}
});
Each key/value pair in the arguments object will represent a parameter in the HTTP POST. You can use variables as values, but I believe they will be converted to strings, so it's better to do the conversion yourself (so you can make sure they have the correct format). A simple example:
var dynamicValue = foo();
$.post('my/url', { var1:"static value", var2:dynamicValue }, function(data) {
// Your callback; the format of "data" will depend on the 4th parameter to post...
}, "json"); // ...in this case, json
Now, in case your server is expecting a json encoded object/list, you can pass it by using JSON.stringify:
function foo() {
return JSON.stringify({ my:"object" });
}
JSON should be available in most modern browsers, in case it's not, you can get it here (json2.js, under "JavaScript").
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>"
)
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.')
}
})