Convert PHP-SQL Result variable to a Javascript object - javascript

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"

Related

Using square right bracket in php key

I am trying to post a dictionary using ajax. But I have run into some problems with json and "]" character.
Here's example of my code (javascript):
var dict = {"id":"patient","where":{"name[~]":"J"}};
$.post("./ajax.php",{data:dict},function(data){
});
And ajax.php (this file just deals with the json encoded data in $_POST array):
$where = $_POST["data"]["where"];
Basically i am trying to send json format message to php, and there I want to process with the data.
I tried whole bunch of combination with json_encode and decode on php side, also JSON.stringify() on javascript side, tried to use escape characters with the right bracket.
But when I dump $_POST["data]["where] there's value "J" with key "name[~" and not "name[~]". Right bracket disappears from the key.
Anyone having any advice, please?
Thanks for help, I've been struggling with this for hours...
//EDIT: I've figured out, that everything i place after "]" disappears from the key. So the key transforms from "name[~]asdf" -> "name[~"...
When you provide an object to the jQuery AJAX functions, it URL-encodes it. jQuery is sending the data.where parameter as:
data[where][name[~]]=J
and PHP apparently can't deal with nested brackets like that; it just matches the [ before name with the next ].
Probably jQuery needs to double-encode this property name to protect it, but obviously it doesn't.
The workaround is to encode dict as JSON, and decode it in PHP. JS:
$.post("./ajax.php",{data: JSON.stringify(dict)},function(data){
PHP:
$data = json_decode($_POST['data'], true);
$where = $data['where'];
var_dump($where);
I have tried JSON.stringify in junction with json_decode and the result looks fine:
JS
$.ajax({
url: './ajax.php',
method: 'post',
data: "data="+JSON.stringify(dict)
});
PHP
json_decode($_POST['data'], true);
I think you should have specified the JSON is associative, setting $assoc parameter to true. See this.
You can also send data as a JSON (not string) and then read the raw post data using php://input stream and use json_decode with $assoc set to true on the retrieved data yourself; since it appears that out-of-the-box method compiled into PHP is inefficient.
Another solution that worked for me:
JS
$.ajax({
url: 'recAjax.php',
method: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(dict)
});
PHP
var_dump(json_decode(file_get_contents('php://input'), true));
json_decode, php://input

convert jQuery array to php array

This is my jQuery Array:
var IDs=[];
$("#tags").find('.suggested-tag').each(function(){IDs.push(this.id);});
and I want convert this array in php array what should I?
If your array is in JSON format, you could write its contents within a hidden form field.
Then, when the form is submitted, you are able to read the field contents (still in JSON format) and convert it to php array through:
$some_array = json_decode($var_containing_json_text);
You can read more about json_decode() here.
You can't do it directly.PHP works server-side and JQuery works client-side So You can't use Js varaibles in PHP
But there is a trick that you can use Ajax to send Js variables to PHP. This is the only way.

Return Multiples Array in JavaScript from PHP

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");

How to make IF statement in Javascript based on the json result in PHP

Well, sorry for my bad grammar, but any help will be much appreciated..
Ok, here I'm trying to encode string by using json inside PHP then using JavaScript to read the json string. It will have 2 cases here.
The first one is, the application will running normally, so does the encode. The json string will be like this :
{"employee":
[{"id":"1","firstName":"aaa","lastName":"abc","timeIn":"08:00:00","timeOut":"17:00:00"},
{"id":"2","firstName":"bbb","lastName":"def","timeIn":"08:00:00","timeOut":"16:45:00"}]}
and the second one is, the PHP can't read the MySQL database, so in PHP the json encode will be like this :
{"errorProcess":{"text":SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it. }}
The question is, in JavaScript how can I make an IF statement in JavaScript based on the result string in json?
Maybe it will be like this, but I don't know how to write it in JavaScript.
IF (in json string has employee){then result}
else if(in json string has errorProcess){then result}
Thanks for your help
You can check for errorProcess key using
if(json.hasOwnProperty('errorProcess')){
//do struff
}
JSON keys and values are accessed using dot (.) notation in Javascript. Assuming you already have the JSON as an object (not a string), you can simply write
if (json.employee) {
// do something
}
else if (json.error) {
// do something else
}
where json is a variable referencing your returned JSON from the php.
If your JSON is still in string format, you need to parse it into an object. This can be done with the built in JSON object.
var json = JSON.parse(jsonAsString);
First you need to parese JSON like this
var jsonObject= jQuery.parseJSON(yourJsonObj);
if(jsonObject.hasOwnProperty('employee')){
// Add your code
}else if(jsonObject.hasOwnProperty('errorProcess')){
// Add your code
}

How to pass a javascript object to a PHP file while using ajax

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

Categories