In php I return this from a function:
return json_encode(array($array1, $array2, $array3, $array4));
Each array contains single elements, loaded lke this:
while ($obj = $DB->next($res)) {
$array1[] = $obj->the_data;
}
Now in JavaScript, I alert data[0], it shows me "["
Of course the entire data looks similar to this:
[["element1", "element2", "element3"],["element1", "element2", "element2" ... etc
Am I loading the array's incorrectly in php? or am I parsing them incorrectly in JavaScript?
this is being returned in a jQuery Ajax .post call.
I also am using this question as a reference
It looks like the data is a string instead of an array. This suggests that you aren't decoding the JSON.
jQuery will do that automatically if the response from the server is marked as JSON.
By default PHP marks responses as HTML, you need to explicitly say you are returning JSON:
header("Content-Type: application/json");
Related
I'm working on autofilling an html form based on data from a sqlite database.
I'm using a modified version of the code from this site and in its basic feature it works as expected.
The main input element calls, "onkeyup", a javascript function called "lookup", that in turn calls a external php script passing the current string to query the database.
The script returns a string to update the input form:
echo '<li onClick="fill(\''.$result->value.'\');">'.$result->value.'</li>';
The javascript function "fill" is as follows:
function fill(thisValue) {
$('#inputString').val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
"#inputstring" is simply an input element.
What I would like to do instead of returning a string is to return an array and parse it inside the "fill" function to assign the different values to different elements in html.
The problem is that to pass the php array to javascript I have to convert it somehow. I've tried to make it a json string as suggested many times here on stack, but for what I suppose is a problem of quotes, it always return a null value.
I've tried:
$valuetopass = json_encode($query_result);
whithout
echo '<li onClick="fill('.$valuetopass.');">'.$query_result['text'].'</li>';
and with quotes
echo ''.$query_result['text'].'';
And both fail.
I'm aware that similar question have been already asked 1, 2,ecc... But all of the answers suggest to embed php when assigning the javascript variable. In my case the php is called from the function "lookup" and from that php script I want to return to the function "fill".
How can I produce from inside php a string that includes a json string with a format that can be passed to the "fill" function?
Or alternatively how can I rework the problem so that I don't need to do it at all?
Your JSON string is likely to contain ", so of course you get a syntax problem when you insert that into onClick="fill(...);" untreated.
Using PHP’s htmlspecialchars should be able to fix this in this instance.
In the long term, you might want to look more into the separation of code and data though.
Attaching event handlers using inline HTML attributes is kinda “old-school”, today that should rather be done from inside the script, using addEventListener resp. whatever wrapper methods a JS framework might provide for that. The JSON data could then for example be put into a custom data attribute, so that the script can read the data from there.
I am making a simple web app, in one part of it, the result of SQL query is to be passed from PHP to JavaScript with AJAX.
This is the SQL Query:
$meta_query = mysql_fetch_row(mysql_query("SELECT * from meta WHERE user_id='$user_id'"));
This is how I pass it to JavaScript
var_dump($meta_query);
This is what I am getting at JavaScript (as a string):
array(30) {[0]=>string(1) "3"["id"]=>string(1) "3"[1]=>string(2) "14"["user_id"]=>string(2) "14"[2]=>string(10) "29-06-2014"["date"]=>string(10) "29-06-2014"[3]=>string(1) "0"["present"]=>string(1) "0"[4]=>string(1) "0"["future"]=>string(1) "0"}
How, how do I convert this into a proper JavaScript object so that the output is something like:
{"id":"3","user_id":"14","date":"29-06-2014","Present":0,"Future":0}
How do I convert data from the first format to the second in JavaScript? Or should I do something else entirely in PHP to get the data out in some other format? Or should I convert the data to the required format somehow in PHP?
You might want to use
echo json_encode($meta_query);
from php side toy should convert php array to json object using
<?php echo json_encode($array)
here is tutorial how to do this
Don't forget to put in your jquery request dataType: "json"
I have a javascript function that calls an external program and I need to put the result into an object, which will contain multiple rows with multiple values for each, example below:
$.get(programcall , function(data) {
var dealers = {};
data = {0:{'name':'name1','address':'address1','phone':'phone1','miles':1.2},1:{'name':'name2','address':'address2','phone':'phone2','miles':2.2}};
dealers = data;
});
This test works because "data" is not enclosed in quotes, however when the content of "data" is returned from the called program, it just becomes text content in "dealers".
How can I get the value stored as an object?
The called program is MINE, so I can change the format if necessary to make it work.
The data will be a list of customers with name, address etc, which I want to process using javascript and to populate a DIV.
If the string is valid JSON, use the native JSON.parse function to turn it into an object.
For example:
data = JSON.parse('{"mything": 3}')
One thing to look out for: JSON needs double quotes around key names, so {"mything": 3} works but {'mything': 3} will not validate.
Your external server call is returning string content as the data object. This is, hopefully, a valid JSON format but it is still just a string.
What you probably want to do is use jQuery's getJSON function instead of a simple $.get, since it will take care of converting the response to a JSON object similar to your example.
$.getJSON(programcall, function(data) {
// data is now a JSON object not a string, if it's valid json from your server response
I have a javascript object which I want to pass to a PHP file while using jQuery's ajax-implementation.
I've tried to directly pass it to it but this doesn't work, because it isn't escaped or anything. I've tried to use JSON.stringify but this isn't working for me either.
Is there a way to 'serialize' a javascript object to a POST-string?
Update, I'm using JSON.stringify() again. The result is:
The result of JSON.stringify() is:
{\"label\":\"Borne, Overijssel, Nederland\",\"value\":\"Borne, Overijssel, Nederland\",\"geocode\":{\"address_components\":[{\"long_name\":\"Borne\",\"short_name\":\"Borne\",\"types\":[\"locality\",\"political\"]},{\"long_name\":\"Borne\",\"short_name\":\"Borne\",\"types\":[\"administrative_area_level_2\",\"political\"]},{\"long_name\":\"Overijssel\",\"short_name\":\"OV\",\"types\":[\"administrative_area_level_1\",\"political\"]},{\"long_name\":\"Nederland\",\"short_name\":\"NL\",\"types\":[\"country\",\"political\"]}],\"formatted_address\":\"Borne, Nederland\",\"geometry\":{\"bounds\":{\"ca\":{\"b\":52.2832527,\"f\":52.3151634},\"ea\":{\"b\":6.688658900000064,\"f\":6.801415300000031}},\"location\":{\"Ya\":52.3002366,\"Za\":6.753725799999984},\"location_type\":\"APPROXIMATE\",\"viewport\":{\"ca\":{\"b\":52.2832527,\"f\":52.3151634},\"ea\":{\"b\":6.688658900000064,\"f\":6.801415300000031}}},\"types\":[\"locality\",\"political\"]}}
When I do a json_decode it results to NULL. Any suggestions?
If your passing an object as a string thats in legitmate JSON format, to PHP try using
json_decode() on the php side of things. Example
<?php
$ojb = json_decode($_POST['my_json_string']);
?>
What this will do is turn your object into an array or object depending on which version of PHP you are using, and in some cases the object will turn into an array with multiple objects in it.. example:
Array(
[0] stdClass (
'key1'=>'val1'
'key2'=>'val2'
'key3'=>'val3'
)
)
which I know the above isnt a good representation, but its a representation in the lines there of.
After that PHP side you can work with the variable $ojb like any other array/object.
$something = $ojb[0]->key1;
EDIT
I notice your string now. The fact that the quotes are escaped in the string, breaks the fact that its a JSON object, with that you can do one of two things.. Either just pass the object to PHP through your post/get as is, without running it through strigify or.. you could try on the PHP side, if there is a need to strigfy it..
$ojb = stripslashes($_POST['my_json_string']); $ojb = json_decode($ojb);
which will attempt to remove the slashes from the quotes, before putting it through the decode process.
http://php.net/manual/en/function.json-decode.php
You can specify a raw body of the POST request. The raw data would be the result of a JSON.stringify call which would mean that you should specify an appropriate Content-Type header.
$.ajax(url, {
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(data),
processData: false // prevent escaping and other processing
});
You can then deserialize the object in PHP like this:
$json = file_get_contents('php://input');
$data = json_decode($json);
The raw request body is mapped onto the special path php://input
I currently have the following javascript array:
var stuffs = ['a', 'b'];
I pass the above to the server code using jQuery's load:
var data = {
'stuffs': stuffs
};
$(".output").load("/my-server-code/", data, function() {
});
On the server side, if I print the content of request.POST(I'm currently using Django), I get:
'stuffs[]': [u'a', u'b']
Notice the [] at the prefix of the variable name stuffs. Is there a way to remove that [] before it reaches the server code?
This is default behavior in jQuery 1.4+...if you want the post to be &stuffs=a&stuffs=b instead of &stuffs[]=a&stuffs[]=b you should set the traditional option to true, like this:
$.ajaxSetup({traditional: true});
Note this affects all requests... which is usually what you want in this case. If you want it to be per-request you should use the longer $.ajax() call and set traditional: true there. You can find more info about traditional in the $.param() documentation.
When an array is submitted using a GET request, through a form or AJAX, each element is given the name of the array, followed by a pair of optionally empty square brackets. So the jQuery is generating the url http://example.com/get.php?stuff[]=a&stuff[]=b. This is the only way of submitting an array, and the javascript is following the standard.
POST requests work in exactly the same way (unless the json is sent as one long json string).
In PHP, this is parsed back into the original array, so although the query string can be a little strange, the data is recieved as it was sent. $_GET['stuff'][0] works correctly in PHP.
I'm not sure how Django parses query strings.
The [] indicates that the variable is an array. I imagine that the appending of the [] to your variable name is Python/Django's way of telling you it is an array. You could probably implement your own print function which does not show them.