I've read similar questions here and attempted a few of the solutions with no luck.
I'm trying to use var jQuery_my_array = <?php echo json_encode($my_array); ?>; to convert.
I know this returns a valid array called jQuery_my_array, but I can't get the array contents properly.
I've also tried
var jQuery_my_array = <?php echo json_encode($my_array); ?>;
var jQuery_my_array_parsed = JSON.parse(jQuery_my_array);
alert(jQuery_my_array_parsed[2]);
I'd like to just do something like alert(jQuery_my_array[2][0]); and get the strings I've stored in the php array.
Possible? I'm not a pro coder btw ;)
No need of JSON.parse
Try this
<?php
$my_array = array("sone"=>12, "sss"=>45);
?>
<script>
var jQuery_my_array = <?php echo json_encode($my_array); ?>;
console.log(jQuery_my_array);
</script>
Output of the above will be Object {sone: 12, sss: 45}
You can use these as jQuery_my_array.sone;
If your php array is like $my_array = array(12, "sss", 45);
Then can use json as console.log(jQuery_my_array[0]);
The problem you are encountering is due to the fact that you are trying to json_encode an array of objects. In order to do this you will need to transform those objects into an array, which can be done by implementing the JsonSerializable interface:
class imageObject implements JsonSerializable {
// your object code
public function jsonSerialize() {
// one implementation. You could also only return those values you actually need
return get_object_vars($this);
}
}
then in your javascript:
var jQuery_my_array = <?php echo json_encode($my_array); ?>;
console.log(jQuery_my_array_parsed);
Use console.log, not alert. To view the output of the console.log statement open your javascript console
Related
Im trying to query a database from a php file then return the results (userLOC of each row) to the calling Jquery function.
Calling Jquery:
$.post(url, data, function (data)
{
alert(data);
})
relavent PHP:
$sql = "Select * from location";
$result = mysql_query($sql);
$stack = array();
while($row = mysql_fetch_array($result))
{
array_push($stack, $row["userLOC"]);
}
return $stack;
The problem is that I cant return it correctly, if I "echo $stack" it does not work it says Im trying to convert the array to string. If I "echo $stack[0]" it will give me the first result in the array correctly so I know the values are being stored correctly (as are $stack[1], etc.) but this only sends the one value back. And if I "return $stack" as pictured nothing is alerted because nothing is echoed. How would I go about getting the whole array back so that I could iterate through and use them on the jquery side?
In PHP
$foo = array();
echo $foo;
will produce the literal string Array as output.
You need to convert your array into a string. Since you're dealing with a Javascript target, use JSON as the perfect means of doing so:
$foo = array('a', 'b', 'c', 'd', 'e');
echo json_encode($foo);
Then in your JS code:
$.get(...., function (data) {
alert(data[1]); // spits out 'b'
});
Just remember to tell jquery that you're expecting JSON output.
You need to wrap (serialize) the data in a way that can be transported to the client via HTTP and used to get the original data.
Usual container formats are XML and JSON. JSON is well suited for usage in JavaScript, so use the PHP function json_encode() and echo the result.
Youll want to use JSON!
Client-side:
jQuery.post(url, data, function( data ) {
//Data is already converted from JSON
}, "json");
Server-side:
return json_encode($stack);
Explanation
Hope this helps!
echo json_encode($stack); can help you
at jquery side use jQuery.parseJSON()
You need to convert the array to a JSON object like this : return json_encode($stack);
Just convert your array it to a JSON object and return it back to your JavaScript:
return json_encode($stack);
As others have said, you may wish to wrap the output using something like json:
echo json_encode($stack);
However, if you aren't looking for an output with the complexity of JSON formatting, you could just use implode() to output a comma separated list:
echo implode(',',$stack);
I'm trying to pass an array to Javascript after it has sent a GET request to PHP.
Sending and retrieving the data works perfectly but I couldn't find anything about passing the data back as an array like this:
<?php
$result = mysql_query('blablabla');
//converting $result to an array?
echo $result_as_javascript_array;
?>
<script>
$('result').innerHTML = httpGet.responseText
</script>
Convert the data you get from MySQL to JSON. First build a "normal" PHP array as you would normally do, then pass it through the json_encode() function and return it.
On the client you have to parse the JSON string into a JS array or object. See this SO question for details: Parse JSON in JavaScript?
And please use something else for accessing MySQL. The extension you are using is basically obsolete: http://si1.php.net/manual/en/faq.databases.php#faq.databases.mysql.deprecated
you should use json_encode, which works fine, when directly assigning output to a javascript variable
<?php
$result = mysql_query('blablabla');
//first convert result to an associative array
$myarray = array();
while($fetch = mysql_fetch_assoc($result)){
$myarray[]=$fetch;
}
//converting $result to an array?
echo "<script>";
echo "var myArray = ".json_encode($myarray).";";
echo "</script>";
?>
<script>
//now you can use myArray global javascript variable
$('result').innerHTML = myArray.join(",");
</script>
You are looking for json_encode.
Use json_encode like this:
<?php
$result = mysql_query('blablabla');
//converting $result to an array?
echo json_encode($result);
?>
You probably won't want to put the response text right into the innerHTML of your element though unless you are wanting to display the json text in the element.
$arr = array();
while ($row = mysql_fetch_array($result)) {
$arr[] = $row;
}
echo $arr;
However, mysql_ is deprecated, use mysqli instead.
If you want to pass it as JSON, use this:
echo json_encode($arr);
i have encoded my required data in the json object ,but i want to decode the json object into a javscript array, my json encoded object is :
{"product_id":"62","product_quantity":"65"}
however i want to use this json in my java script and want it to be available to a java script array
so if i do :
var arr = new Array()
arr = <?php json_decode('$json_object',TRUE); ?>;
however when i check my page source i get null i.e arr =
how can i assign my json object converted to array to java script array ?
further how to access the json objects from java script array ?
json_decode returns a PHP data structure. If you want to serialise that to a JavaScript data structure you have to pass it through json_encode (and then actually echo the string that it returns).
Note that json_encode outputs a JavaScript data structure that is safe for injecting into a <script> element in an HTML document. Not all JSON is safe to do that with (PHP adds additional escape sequences, and will transform plain strings, numbers, null values, etc (which aren't legal JSON on their own).
Note that there is also no point in creating a new array and assigning it to arr if you are going to immediately assign something else to arr.
Also note that '$json_object' will give you a string starting with the $ character and then the name of the variable. Single quoted string in PHP are not interpolated.
var arr;
arr = <?php echo json_encode(json_decode($json_object,TRUE)); ?>;
Also note that this JSON:
{"product_id":"62","product_quantity":"65"}
Will transform in to a PHP associative array or a JavaScript object (which is not an array).
So given this PHP:
<?php
$json_object = '{"product_id":"62","product_quantity":"65"}';
?>
<script>
var arr;
arr = <?php echo json_encode(json_decode($json_object,TRUE)); ?>;
alert(arr.product_id);
</script>
You get this output:
<script>
var arr;
arr = {"product_id":"62","product_quantity":"65"};
alert(arr.product_id);
</script>
Which alerts 62 when run.
You could push the JSON objects into javascript array and iterate through the array, selecting the appropriate fields you need.
Fixed it..
var json = {"product_id":"62","product_quantity":"65"};
var array = new Array();
array.push(json);
for(var i = 0; i < array.length; i++){
console.log(array[i].product_id)
}
Okay so to start off :
the json string generated in PHP can be used in Javascript as an Object. If you declare the variable as an array to start with then it might conflict.
anyway this should work :
<?php
$error_fields_structure = array(
'product_id' => 4531
,'main_product_quantity' => 2
);
$json_object = json_encode($error_fields_structure);
?>
<html>
<head>
<script>
var jsonstring = <?php echo (isset($json_object) ? $json_object : 'nothing here'); ?>
for( var i in jsonstring ){
alert( i +' == ' +jsonstring[i] );
}
</script>
</head>
<body>
</body>
</html>
I have stored array values in PHP session.
Now I want to retreive this array and convert it to javascript aray.
This is how I set PHP session:
var listone = ["one", "two", "three"];
function setSession(listone){
$.get(
"setSession.php",
{listone:listone}
);
}
So if once these values are set and I refresh the page, I check if the session has been set. If set, I want to do something like this:
<?php
session_start();
if(isset($_SESSION['listone']))
{
?>
listone = Array('<?php echo json_encode($_SESSION['listone']) ?>');
<?php
}
?>
When I do this, the 'listone' array is showing me like this:
listone[0] = [
listone[1] = "
listone[2] = o
listone[3] = n
listone[4] = e
listone[5] = "
.... etc
I know I am doing something wrong.
Is it the way I am storing the array in PHP session?
or
Is it the way I am retrieving it back to JS?
Thanks for any pointers. I am willing to dig more if guided properly :)
You may be trying to do one of two things here- either something to do with AJAX, which is expecting a JS response, or you're trying to access a session variable directly in JS.
If you simply wish to switch a PHP variable into a JS readable array, you can do:
json_encode($_SESSION['myarray']);
This would need to be a response readable & interpreted elsewhere by a JS script (e.g. an AJAX response).
PHP session variables arent accessable through JS directly, however, you can construct JS within PHP, wrapping the two together so you use PHP to output JS populated with the data held within your PHP session variable. The key here is the order of the code, and how your JS is structured- i.e. you will probably want to reference a global JS variable so the values are accessible by your other JS- or call a function etc...
So, you could have:
session_start();
if(!isset($_SESSION['myarray'])){
$_SESSION['myarray']=array('one', 'two', 'three');
}
echo "<script type='text/javascript'>
var myJSvariable = new Array();";
foreach($_SESSION['myarray'] as $key=>$value){
echo "myJSvariable[".$key."]=".$value.";";
}
echo "</script>";
Try to change your php file to this or a similar one
<?php
session_start();
$result = array();
if(isset($_SESSION['listone'])) {
$result['listone'] = $_SESSION['listone'];
}
echo json_encode($result);
?>
json_encode translate your array into a json array and you don't need to create a new one.
Plus I would put the required variables into an hash array and return just the json_encode of that array in order to have a cleaner code.
I have an array($my_array) that looks something like:
array(2) {
[25]=>int(10)
[30]=>int(8)
}
I'd like to assign it to a javascript array, but am having difficulties doing it. Any suggestions?
Edit: At first, I thought I could just assign it like a string, but that isn't working:
var photo_limit = $my_array;
I tried also doing a var_dump into my js value.
I'm currently trying to use something like:
for($i=0;$i<count($my_array); $i++){
echo "a[$i]='".$a[$i]."';\n";
}
Thanks.
The best way is to use json_encode. See json_encode reference
Used like this:
<script>
var array = <?php echo json_encode($array)?>;
</script>
Note, hovewer, that you'll receive Javascript object, instead of array. At a glance the only difference is if you have string keys in your array, you'll be able to access them in JS like array.*string key*, i.e. using dot notation.
1: json_encode your PHP array.
2: Decode the JSON string in JavaScript using eval(alternative: jQuery.parseJSON)
<script>
var arr = eval('(<?php echo json_encode($thePhpArray); ?>)');
</script>