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.
Related
In my local environment I'm using the PHP7 and I developed a Restful API to an AngularJS application. I need do a get request to the Api and pass an array as parameter, so I did it:
$http.get("/Api/MyUrl.php", {
params: {
"Names[]": ["Foo", "Bar"]
}
})
.then(function(response){ //fires in success
console.log(response.data);
}, function(response){ //fires in error
console.log(response.statusText);
});
In MyUrl.php file I printed the parameters in the screen like this:
<?php
print_r($_GET);
?>
When it was executed, exactly what I imagined was printed on the browser console:
Array
(
[Names] => Array
(
[0] => Foo
[1] => Bar
)
)
Until here there's no problem. But, when I uploaded the application in the server, that supports only the 5.6 PHP version (I don't know if it's correlated, but I think so), the parameter with the array is gotten by the PHP in another way, and what is printed on console is that:
Array
(
[Names%5B%5D] => Bar
)
It "undestands" the [] signals as its HTML codes (%5B and %5D), get only the last element of the array and interprets as a commom variable.
What I need to do to read the parameters in the server in the same way that I do in the local environment?
Good question. I suggest you checkout this old issue in angularjs project where it reads:
There is no particular standard for how arrays should be serialized into query strings. Different back ends expect different formats. This current method (in 1.1.x) was chosen specifically because it allows the developer the most flexibility.
The way you are passing params to $http.get() seems to work for php7.0 because php7.0 may be smart enough to infer that brackets are being passed. But the fact is that the query string in your angular code is not properly URI-encoded so it fails against your server.
Interestingly, a similar issue has been reported here the answer to which references documentation from jQuery which has the same behavior:
Because there is no universally agreed-upon specification for param strings, it is not possible to encode complex data structures using this method in a manner that works ideally across all languages supporting such input. Use JSON format as an alternative for encoding complex data instead.
What is the solution?
For a start, you can try URI-encoding your params.
Another solution would be to pass your query as json encoded data:
$http.get("/Api/MyUrl.php", {
params: {
"data": JSON.stringify({'names': {'Foo', 'Bar'}})
}
})
and json_decode($_GET['data']) to access your parameters in backend.
And lastly, you can take advantage of AngularJS's paramSerializer to define your own serializer and pass your params as you used to.
In this particular case, paramSerializerJQLike will be useful:
$http.get("/Api/MyUrl.php", {
params: {
"Names[]": ["Foo", "Bar"]
}
paramSerializer: '$httpParamSerializerJQLike'
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
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 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.
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 an interactive web application powered by jQuery where users can manipulate visual objects on the screen. When done, the "state" of JavaScript objects should be sent to PHP to store into database. I'd prefer to use GET for this, but solution that uses POST to submit the data is also viable.
I'm currently thinking to serialize all JS objects using something like base64 encoding and just use something like:
var str = encode_objects();
document.location = 'result.php?result='+str;
However, something tells me there has to be some, more elegant, way than writing my own base64 encoding function in JavaScript. Isn't there something already built into JavaScript that can do the job?
Update: decoding in PHP is not the problem. I know how to decode base64, JSON, whatever in PHP. The problem is how to encode data on JavaScript side.
AJAX is out of the question. It has to be a clean GET or POST with page reload.
json_decode() should serve you well here.
If you simply append a string containing the JSON representation of your javascript object to your HTTP request, you can json_decode() it in PHP and have a PHP object ready to go.
Edit: I should mention that this page has a link to a Javascript JSON stringifier, which will convert your JS objects into the necessary JSON.
first of all, if you're updating the objects state, it should be a POST. try to keep all your GET idempotent.
second, even if you don't want to do any AJAX, JSON is still your friend. the easiest way would be to serialize your objects into JSON and send the resulting string in the POST dataload. there are many ways to decode JSON in PHP, and you're all set.
You can use this serialize function, and then unserialize it on the PHP end.
GET or POST will probably depend on the size of your data : there is a limit on the amout of data you can pass through GET (something like 2000 bytes ; more, depending on the browser).
There is also an other thing to take into account : if you are modifying data, you should use POST ; not GET, which is used to... get... data.
About the format, I would really not go for anything like a custom function doing any kind of stuff like base64 : I would definitly go for JSON, which is a native Javascript notation.
You can for instance have a look at :
wikipedia
http://www.json.org/
There are many JS libraries that can generate JSON (probably every JS Framework can ; and there are standlone libraries like this one) ; and since PHP 5.2 there are functions in PHP to encode/decode it (see json_encode and json_decode)
If it's just a simple flat array you don't need to do anything fancy, as PHP has a built in feature to parse array syntax from GET/POST variable names. Rough example below.
Javascript side:
// Do the parameter-building however you want, I picked the short/messy way
var arrayvalues = [1, 2, 'a'];
var querystring = "var[]=" + arrayvalues.join("&var[]=");
querystring += "&var[something]=abcdef";
// querystring is now "var[]=1&var[]=2&var[]=a&var[something]=abcdef"
PHP side:
var_dump($_POST);
// Remember to validate the data properly!
if ( is_array($_POST['var']) ) {
count($_POST['var']);
echo $_POST['var']['something'];
array_map('do_something_interesting', $_POST['var']);
}
I've used Jquery/JSON.
var jsonArray = $.toJSON(jsArray);
Then sent it via JQuery/Ajax