Javascript Convert PHP Json into a javascript array - php

In php I used json_encode(...) and then got the value in Javascript, looks as the following:
["float","float","float","float"] // PS: This is a string...
And I would like to make this into a normal javascript array, like so:
Arr[0] // Will be float
Arr[1] // Will be float
Arr[2] // Will be float
Arr[3] // Will be float
How is this possible?

It sounds like you're retrieving a JSON string in JavaScript (perhaps via AJAX?). If you need to make this into an actual array value, you'd probably want to use JSON.parse().
var retrievedJSON = '["float","float","float","float"]'; // normally from AJAX
var myArray = JSON.parse(retrievedJSON);
If you're actually writing out a value into the page, rather than using AJAX, then you should be able to simply echo the output of json_encode directly, without quoting; JSON itself is valid JavaScript.
var myArray = <?php echo json_encode($myPhpArray); ?>;

var myArray = <?= json_encode($myPhpArray); ?>;
Pretty simple. ;-)
Example:
<?php
$myPhpArray = array('foo', 'bar', 'baz');
?>
<script type="text/javascript">
var myJsArray = <?= json_encode($myPhpArray); ?>;
</script>
Should output (view-source):
<script type="javascript">
var myJsArray = ["foo","bar","baz"];
</script>
Example

I reccomend using jquery. The php file should look as such ...
//location.php
<?php
$change = array('key1' => $var1, 'key2' => $var2, 'key3' => $var3);
echo json_encode($change);
?>
Then the jquery script ...
<script>
$.get("location.php", function(data){
var duce = jQuery.parseJSON(data);
var art1 = duce.key1;
var art2 = duce.key2;
var art3 = duce.key3;
});
</script>

Related

MySQL/PHP Array to Javascript

So I want to store all of my MySQL results in an array I can manipulate with javascript/jQuery.
Here is my current code:
<?php
$sql = "SELECT * FROM potentials";
$result = mysql_query($sql) or die(mysql_error());
$potential = mysql_fetch_array($result);
echo json_encode($potential);
?>
And my Javascript:
<script type="text/javascript">
$(document).ready(function(){
var myArray = "<?php print(json_encode($potential)); ?>";
console.log(myArray)
)};
</script>
I keep getting "Unexpected number" or "unexpected identifier". Whats going on?
json_encode() returns an object using JSON notation. Strangely, you surrounded it with quotes. Try removing them :
<script type="text/javascript">
$(document).ready(function(){
var myArray = <?php print(json_encode($potential)); ?>;
console.log(myArray);
});
</script>
(and it's not an array, it's an object, so you might want to rename your variable ;) )
You are using json_encode() twice, however if you want to use it, you need to parse it. In jQuery this can be done via jQuery.parseJSON like this
var myArray = jQuery.parseJSON('<?php print json_encode($potential); ?>');
Also if you want all the results, you need to loop the query (e.g. with while) and then save it to an array
$array = array();
while ($row = mysql_fetch_array( mysql_query( $query ) )
{
$array[] = $row;
}
<script>
var data = '<?php echo $data; ?>';
var json = JSON.parse(data);
console.log(json[0]); //etc
</script>
Notice that var data = ... is SINGLE QUOTED, so you catch the echo from php as a String

javascript/php single quote

i'm trying to this:
<?php $php_array = array ('var1' => "l'ape"); ?>
<script type="text/javascript">
var my_javascript_object = jQuery.parseJSON('<?php echo json_encode($php_array); ?>');
</script>
I got this error "Uncaught SyntaxError: Unexpected identifier".
The problem is the single quote in the value of var1 in $php_array.
This doesn't work
<?php $php_array = array ('var1' => "l\'ape"); ?>
You don't need to parse your json with JSON.parse in this case. Just use it as an object literal instead of a Javascript string:
var my_javascript_object = <?php echo json_encode($php_array); ?>;
The problem is that you try to put the JSON in a JavaScript string.
Do this instead:
var my_js_obj = <?php echo json_encode($php_array); ?>;
A JSON string is a valid JavaScript expression which you can simply put directly in your JS code.
If you really wanted to create a string containing JSON (you don't!), you'd do it like this:
var my_json_string = <?php echo json_encode(json_encode($php_array)); ?>;
var my_js_obj = $.parseJSON(my_json_string);

Passing a php array into javascript using JSON

I have a multidimensional array, here:
$noticeDate = json_encode( $noticesDates );
and I want to pass the array into javascript:
var unavailableDates[] = $noticeDate;
Both variables are in the same php file so there is little point using $.getJSON, which basically looks for the variable in an external file. However, how do I pass the object into the javascript array in the same script.
Cheers
You cant directly assign php variables to js, but you can use something like that:
<script>
var unavailableDates = jQuery.parseJSON('<?php echo json_encode($noticeDates) ?>');
</script>
use this
var array = JSON.parse("<?php echo json_encode($noticesDates) ?>");
Try this one:
$.pareseJSON()
here is example:
var json = "<?php echo json_encode($noticesDates); ?>";
jsArray = jQuery.parseJSON(json);

How to get value to array in javascript

$array = array("1" => "box of chocolates", "2" => "mylar balloons", "3" => "stuffed animals");
<?php
$productWithItem = $array;
foreach ($productWithItem as $pwi) {
?>
<?php echo $pwi->name ?></div>
<?php
}
?>
<script type="text/javascript">
jQuery(function(){
var value_array = ?;
});
</script>
I Want get array value from id="product_name", but I don't know get value from on this javascript, you can help me, thank you
If you are intending to keep your <script> in your html code, build your array in php and use echo:
<script type="text/javascript">
jQuery(function(){
var value_array = <?php echo $yourarray ?>;
});
</script>
That's not an elegant solution, though.
Make product_name as id into class . now $('.product_name') this will be automatically array of objects
example markup
aaa</div>
bb</div>
cc</div>
using each you can extract array
$('.product_name').each(function(){
alert($(this).text());
});
Put your array string in the name attribute of the <a>.
Then you can use jQuery to get it back:
jQuery(function(){
var ele= [YOUR ELEMENT]
var value_array = $.parseJSON($(ele).attr("name"));
});

Storing php $_GET variable in a javascript variable? [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I am passing two pieces of info to a php page using the $_GET method (team1, team2).
I'd like to use these as variables in some javascript. How can I do this?
Thanks
Since $_GET just access variables in the querystring, you can do the same from javascript if you wish:
<script>
var $_GET = populateGet();
function populateGet() {
var obj = {}, params = location.search.slice(1).split('&');
for(var i=0,len=params.length;i<len;i++) {
var keyVal = params[i].split('=');
obj[decodeURIComponent(keyVal[0])] = decodeURIComponent(keyVal[1]);
}
return obj;
}
</script>
Original answer:
In your .php file.
<script type="text/javascript">
var team1, team2;
team1 = <?php echo $_GET['team1']; ?>;
team1 = <?php echo $_GET['team1']; ?>;
</script>
Safer answer:
Didn't even think about XSS when I blasted this answer out. (Look at the comments!) Anything from the $_GET array should be escaped, otherwise a user can pretty much insert whatever JS they want into your page. So try something like this:
<script type="text/javascript">
var team1, team2;
team1 = <?php echo htmlencode(json_encode($_GET['team1'])); ?>;
team1 = <?php echo htmlencode(json_encode($_GET['team1'])); ?>;
</script>
From here http://www.bytetouch.com/blog/programming/protecting-php-scripts-from-cross-site-scripting-xss-attacks/.
More about XSS from Google http://code.google.com/p/doctype/wiki/ArticleXSSInJavaScript.
Cheers to the commenters.
Make sure you use something like htmlentities to escape the values so that your application is not susceptible to cross-site scripting attacks. Ideally you would validate the variables to make sure they're an expected value before outputting them to the page.
<script type="text/javascript">
var team1 = '<?php echo htmlentities($_GET['team1']); ?>';
var team2 = '<?php echo htmlentities($_GET['team2']); ?>';
</script>
<script type="text/javascript">
var team1 = <?php echo $_GET['team1'] ?>;
var team2 = <?php echo $_GET['team2'] ?>;
</script>
Another way to do this with javascript :
var team1 = $_GET('team1');
function $_GET(q,s) {
s = s ? s : window.location.search;
var re = new RegExp('&'+q+'(?:=([^&]*))?(?=&|$)','i');
return (s=s.replace(/^?/,'&').match(re)) ? (typeof s[1] == 'undefined' ? '' : decodeURIComponent(s[1])) : undefined;
}
The other methods are kind of dirty, and there can be some problems. Your better off just using javascript:
<script>
function get_data(name){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if(results == null) return "";
else return results[1];
}
var var1 = get_data('var1');
var var2 = get_data('var2');
</script>
But this still isn't super secure.
Another way of doing this, which I just thought of, is to print the $_GET array. I don't know if that would work, though. Anyway, if it does, then here it is:
<script>
var _get = <?php print_r($_GET); ?>
var team1 = _get['team1'];
var team2 = _get['team2'];
</script>
And you would want to run array_walk(or something like that), on a function to clean each string.
Make sure your $_GET vars are available and not empty and use the following:
<script type="text/javascript">
var team1 = <?php echo $_GET['team1']; ?>;
var team2 = <?php echo $_GET['team2']; ?>;
</script>

Categories