javascript/php single quote - php

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

Related

2 php vars with json encode in javascript

I have a problem with my script. If I have two JSON_ENCODE lines my script doesn't work anymore.
var time= <?php echo json_encode($time_cell); ?>;
var time2= <?php echo json_encode($time_cell2); ?>;
Why? Is there any other method to get this PHP vars?
JSON encoded string needs to be parsed in Javascript.
You can do somthing like this:
var time=JSON.parse("<?php echo json_encode($time_cell); ?>");
var time2=JSON.parse("<?php echo json_encode($time_cell2); ?>");
You mey read more here on this link.

Convert Multidimensional PHP array to javascript array

I'm trying to convert a PHP multidimensional array to a javascript array using the JSON encoder. When I do a var_dump, my php array looks like this:
array (size=2)
'Key' => string 'a' (length=1)
'Value' => string 'asite.com' (length=9)
This is the code I'm currently using in my view to try to convert it to a JavaScript array:
var tempArray = $.parseJSON(<?php echo json_encode($php_array); ?>);
Whenever I run this code in the browser, the output of the conversion in the console is this:
var tempArray = $.parseJSON([{"Key":"a","Value":"asite.com"}]);
Is this the correct structure for a javascript multidimensional array? I'm asking because it keeps giving me this error on the line above:
SyntaxError: Unexpected token o
You do not have to call parseJSON since the output of json_decode is a javascript literal. Just assign it to a variable.
var tempArray = <?php echo json_encode($php_array); ?>;
You should be able then to access the properties as
alert(tempArray[0].Key);
This worked for me.
<script type='text/javascript'>
<?php
$php_array = array(
array("casa1", "abc", "123"),
array("casa2", "def", "456"),
array("casa3", "ghi", "789" )
);
$js_array = json_encode($php_array);
echo "var casas = ". $js_array . ";\n";
?>
alert(casas[0][1]);
</script>
Do not use parseJSON, that's for a string.
Just do:
<?php
$php_array = array ('Key'=>'a', 'Value'=>'asite.com');
?>
<html>
<head>
<script type="text/javascript">
var tempArray = <?php echo json_encode($php_array); ?>;
console.log(tempArray);
</script>
</head>
<body>
</body>
</html>
This give me in the console:
Object { Key="a", Value="asite.com"}
Just add single quotes in the js function,like
var tempArray = $.parseJSON('<?php echo json_encode($php_array); ?>');

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

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 pass array string in JavaScript function from PHP end as a argument?

I am getting the error missing ) after argument list in my Firebug console.
emissing ) after argument http://a8.sphotos.ak.fbcdn.net/hphotos-ak-snc7/s720x720/393131_320846714645076_100001592501599_911297_470580896_n.jpg
My question is how to pass $char_data variable in JavaScript function as a argument
Define php variable:
<?php
$chart_data = "['NBA',1],['NFL',2],['MLB',3],['NHL',4]";
$div = "graph";
?
Call JavaScript function with define argument
<script>
dynamicChartArray('<?php echo $div;?>','<?php echo $chartdata;?>')
</script>
A function of JavaScript
<script>
function dynamicChartArray(div,chartdata){
var myData = new Array(chartdata);
var myChart = new JSChart(div, 'pie');
alert(chartdata+div);
}
<script>
Rather than creating an array out of a string in javascript, why not just just get the PHP to output it as an array to start with?
Just add an extra set of [] which javascript reads as an array.
$chart_data = "[['NBA',1],['NFL',2],['MLB',3],['NHL',4]]";
then ditch the quotes on the output (which are responsible for causing the error messages)
dynamicChartArray('<?php echo $div;?>', <?php echo $chartdata;?>);
and then myData can just equal chart data (since its already an array)
var myData = chartdata;
'<?php echo $chartdata;?>'
This is going to echo '['NBA',1],['NFL',2],['MLB',3],['NHL',4]'. Note how there are single quotes inside the single quotes.
new Array(chartdata)
This will just make an array, with one element, the string "['NBA',1],['NFL',2],['MLB',3],['NHL',4]".
Try doing dynamicChartArray('<?php echo $div;?>',[<?php echo $chartdata;?>])
This will make chartdata an array of arrays.
Instead of
$chart_data = "['NBA',1],['NFL',2],['MLB',3],['NHL',4]";
Use
$chart_data = "[\"NBA\",1],[\"NFL\",2],[\"MLB\",3],[\"NHL\",4]";
Change your call to this:
dynamicChartArray('<?php echo $div;?>',[<?php echo $chartdata;?>])
And function to this:
function dynamicChartArray(div,chartdata){
var myData = chartdata;
var myChart = new JSChart(div, 'pie');
alert(chartdata+div);
}
change this:
dynamicChartArray('<?php echo $div;?>','<?php echo $chartdata;?>')
to this:
dynamicChartArray('<?php echo $div;?>', [<?php echo $chart_data;?>]);
and see if it works
You dont need var myData = new Array(chartdata);.
chartdata is already an array.
Take a look at json_encode.
$chart_data = json_encode(array(array('NBA',1),array('NFL',2)));
which will produce a json string ready to echo into your script
string(21) "[["NBA",1],["NFL",2]]"
You should have a look at the output. I bet it is:
dynamicChartArray('graph','['NBA',1],['NFL',2],['MLB',3],['NHL',4]')
and you can already see that you have problems with the quotes.
Instead of creating a string, I suggest to create an array and use json_encode:
$chart_data = array(
array('NBA',1),
array('NFL',2),
array('MLB',3),
array('NHL',4)
);
and
dynamicChartArray('<?php echo $div;?>', <?php echo json_encode($chartdata); ?>)
JSON happens to be valid JavaScript as well and it gives you more possibilities to process the data on the server side.

Categories