array php to javascript with chrome - javascript

In chrome, I have the following problem. (I don't have the problem in firefox.)
Here is my code:
echo $name[0]; // outputs: apple
and I use in Javascript:
var name= <?php echo json_encode($name ); ?>;
document.write(name[0] + "<br>"); // outputs: a
I want the name[0] showing apple but not a. How can I fix it?

I've written what you've described here:
<?php
$name = ['apple', 'banana', 'pear'];
?>
<html>
<body>
<script type="text/javascript">
var array = <?php echo json_encode($name);?>;
document.write(array[0]+'<br>');
</script>
</body>
</html>
And appleis written in the document body as you wanted. Now this only happens if your array (variable $name) actually has an array with "apple" as the first element.
You might be getting the error you've described if $name contains "apple" (a string) , in which case PHP tries to acces the first letter in "apple".

Related

Pass php object to a javascript function

I was wandering if it is possible to send a php object/array from a database into a javascript function through html?
Here is what I am trying to accomplish:
<?php
$test = array('Apple', 'Banana', 'Lemon');
?>
Send object
<script type="text/javascript">
function myfuntion(test)
{
console.log("What is first fruit: "+test[0]);
}
</script>
I get this error in my console:
Uncaught SyntaxError: Unexpected end of input
myfuntion([
What am I missing? Hoping for help and thanks in advance :-)
It is because string generated by json_encode contains double quotes and conflict with onclick="..."
Try to wrap it with htmlspecialchars
Send object
To avoid quotes collision just store your json as an object somewhere:
<?php
$test = array('Apple', 'Banana', 'Lemon');
?>
Send object
<script type="text/javascript">
var data = <?php echo json_encode($test) ?>;
function myfuntion()
{
console.log("What is first fruit: "+data[0]);
}
</script>
Or using an argument:
<?php
$test = array('Apple', 'Banana', 'Lemon');
?>
<script type="text/javascript">
var data = <?php echo json_encode($test) ?>;
</script>
Send object
<script type="text/javascript">
function myfuntion(jsonObj)
{
console.log("What is first fruit: "+jsonObj[0]);
}
</script>
Instead of pass in function direct use $test array json in js like this.
<?php
$test = array('Apple', 'Banana', 'Lemon');
?>
Send object
<script type="text/javascript">
function myfuntion()
{
var test = <?php echo json_encode($test); ?>;
for(var i=0; i<test.length; i++){
console.log("What is first fruit: "+test[i]);
}
}
</script>
If you pass in a tag then it passes a string instead of json.
Hope this is helpful to you.
You are missing parentheses for PHP code inside myfuntion.
Send object
You are doing correct only thing missing is, you need to surround passed argument in parentheses as below.
<a href="javascript:;"
onclick="myfuntion('<?php echo json_encode($test) ?>');">Send object</a>
Because your code will echo json encoded values/string in argument (and string must be inside single of double quotes) and function arguments must needs to be surrounded in parentheses. But if it is number then it will work but when you are dealing with objects and array you must need to enclose them in ''.
And in your js code just parse that argument to JSON using JSON.parse method.

phpcoding special characters

When I load a php page, i put within a javascript function, a name. The problem comes when this string has special chars like '.
Here I paste the code of a click event:
showSocialShare(event, '<?php echo $object->slug; ?>', '<?php echo htmlspecialchars($object->title); ?>', '<?php echo $object->image; ?>')
I thought that the function htmlspecialchars code somehow the string but the result is:
showSocialShare(event, '4049269', 'collection-'Noun'', '/img/Original.jpg')
As can be seen, at the second parameter, the name contains characters like ' and arises an error.
How can I avoid this?
Never output text from PHP directly into a Javascript context. As you're finding out, it's VERY easy to generate JS syntax errors.
Always use json_encode: e.g. given this
<?php $foo = 'bar'; ?>
<script>
var badly_broken = <?php echo $foo ?>;
var working_fine = <?php echo json_encode($foo); ?>;
</script>
You'll end up with
<script>
var badly_broken = bar; // oops - undefined variable "bar"
var working_fine = "bar";
</script>
And note that if you're outputting JS into an HTML attribute, you not only have to generate valid Javascript, you have to output valid HTML AS WELL:
<?php $foo = array('bar' => 'baz'); ?>
<a onclick="brokenCall(<?echo json_encode($foo) ?>)">
<a onclick="workinCall(<? echo htmlspecialchars(json_encode($foo)) ?>)">
produces:
<a onclick="brokenCall({"bar":"baz"})">
^--start attribute
^--end attribute - ruhroh
<a onclick="workingCall({"bar":"baz"}")>

converting with json_encode()

<?php
$array = array("first elem", "second elem");
?>
<html>
<head>
</head>
<body>
<script>
var js_array = '<?php echo json_encode($array); ?>';
for (var i = 0; i < js_array.length; i++)
{
document.write(js_array[i]);
document.write("<br>");
}
</script>
</body>
I have PHP array with two elements, when I converting this array to javascript array with json_encode()javascript divide my PHP array into set of chars, so in javascript array in a result i have a lot of elements. How to convert PHP array with two elements to javascript array with the same two elements?
You php function json_encode will give you a valid object, that's in fact what it means, JavaScript Object Notation.
So by using it as it is you will create an object in your JavaScript code. By enclosing it between apostrophes you are making it a string (who's value can be parsed as JSON).
So the simplest change would be to remove the apostrophes. So this line:
var js_array = '<?php echo json_encode($array); ?>';
Should become
var js_array = <?php echo json_encode($array); ?>;
The problem is that you have enclosed the json_encode in colons so you are converting it to a string. The javascript it produces is like this:
var js_array = '["first elem","second elem"]';
Here js_array is an string but you want an array. What you have to do is to produce the json directly as it will yield an array:
var js_array = <?php echo json_encode($array); ?>;
Replace you code with the following code..
<?php
$array = array("first elem", "second elem");
?>
<html>
<head>
</head>
<body>
<script>
var js_array = <?php echo json_encode($array); ?>;
for (var i = 0; i < js_array.length; i++)
{
document.write(js_array[i]);
document.write("<br>");
}
</script>
</body>
I hope its help you.....

Embed PHP into javascript with Ajax in order to store MySQL data in javascript objects

Have googled a solution for this question for quite some time and it seems a lot of people are asking about the same thing. Haven't found a good answer that works though.
What I want to do:
I have a simple database called "fruitStand". It has a single table called "fruitTable" which contains two columns:
**fruit** **cost**
apple 5
pear 4
banana 2
orange 6
I can easily fetch the rows with a PHP script and display the result directly on the screen. However, I want to be able to get the result into my javascript arrays so I can build some graphs based on it.
After considering this post, I decided to use Jquery Ajax to glue the HTML/javascript code with the PHP code. I'm using the two files below (index.html and getData.php) along with the database. This generates the following HTML output when I hit the "Get data!" button:
apple5pear4banana2orange6
Now to the actual question:
How could I modify the code so I'm able to return the results in js array/object form? I want it to look something like this:
array1 = ["apple", "pear", "banana", "orange"]
array2 = [5,4,2,6]
The ultimate goal is to use these arrays when plotting the interactive graphs (will later on add buttons to select fruits/cost).
The index.html file:
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({
type: "GET",
url: "getData.php",
dataType: "html",
success: function(response){
var store = $("#responsecontainer").html(response);
}
});
});
});
</script>
<body>
<table border="1" align="center">
<tr>
<td> <input type="button" id="display" value="Get data!" /> </td>
</tr>
</table>
<div id="responsecontainer" align="center"></div>
</body>
</html>
The PHP file:
<?php
mysql_select_db('fruitStand',$con);
$result=mysql_query("select * from fruitTable",$con);
$con=mysql_connect("localhost","root","password");
if (!$con){
die('Could not connect: ' . mysql_error());
}
while($data = mysql_fetch_row($result)){
echo "$data[0]";
}
?>
If I were wanting to share an array of data from php to Javascript, I would use JSON.
Format the array that you want it to be used in php, then use json_encode php method to convert the php array to JSON.
In the js, use JSON.parse to decode the JSON into a Javascript object.
<html>
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<?php $phpArray = array(); ?>
<?php $phpArray = array(array('fruit' => 'green', 'cost' => 10), array('fruit' => 'blue', 'cost' => 9),array('fruit' => 'red', 'cost' => 8), array('fruit' => 'yello', 'cost' => 7));?>
<script>
var fruit = [];
var cost = [];
var jsString = '<?php echo json_encode($phpArray);?>';
var jsArray = JSON.parse(jsString);
for(var i in jsArray){
fruit[i] = jsArray[i]['fruit'];
cost[i] = jsArray[i]['cost'];
}
console.log(fruit);
console.log(cost);
</script>
Expected console output:
["green", "blue", "red", "yello"]
[10, 9, 8, 7]
this should help you get started. Loop through PHP NOT JAVASCRIPT.
<script>
<?php
$i = 0;
while($row = mysql_fetch_array($result)){
echo "fruit[$i] = '" . $row['fruit'] . "';";
echo "cost[$i] = '" . $row['cost'] . "';";
$i++;
}
?>
</script>

How to Pass a PHP array to JavaScript function?

First of all, this question looks a duplicate of Pass a PHP array to a JavaScript function, but I actually used the first solution of Pass a PHP array to a JavaScript function - and it doesnt seem to work:
More specifically, the php echo line in the code below seems to create erroneous js output according to console error message( Uncaught SyntaxError: Unexpected token <); the console shows created html starting with "var s1 = <br />
<font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1'..."
...while I'd expect a clean var s1 = [1,2,3,4,5,6,7,8,9] - the result I also see when I tested the echo line in ideone.com
Any idea why the echo line is creating this stuff, and how to fix this?
Related joomla php code:
<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
$document = JFactory::getDocument();
//add jqplot libraries
JHtml::_('jquery.framework');
JHTML::script(JUri::root() .'media/system/js/jquery.jqplot.min.js');
//$document->addStyleSheet(JUri::root() .'media/system/js/jquery.jqplot.min.css');
JHtml::stylesheet( JUri::root() . 'media/system/js/jquery.jqplot.min.css' );
JHTML::script(JUri::root() .'media/system/js/jquery.jqplot.min.css');
JHTML::script(JUri::root() .'media/system/js/jqplot.barRenderer.min.js');
JHTML::script(JUri::root() .'media/system/js/jqplot.categoryAxisRenderer.min.js');
JHTML::script(JUri::root() .'media/system/js/jqplot.pointLabels.min.js');
JHTML::script(JUri::root() .'media/system/js/jqplot.enhancedLegendRenderer.js');
JHTML::script(JUri::root() .'media/system/js/weqlib.js');
$chartvals = array(1,2,3,4,5,6,7,8,9);
?>
<head>
<script type="text/javascript">
jQuery(document).ready(function(){
var s1 = <?php echo json_encode(chartvals); ?>; //!the echo seems to create erroneous js output accoding to console(?)
plot1 = jQuery.jqplot ('chart1', [s1]); //copied from example at
}); //$(document).ready
</script>
</head>
You forgot the $ to referrence the chartvals var at the json_encode() function call:
var s1 = <?php echo json_encode(chartvals); ?>;
Should be
var s1 = <?php echo json_encode($chartvals); ?>;
To not trap into this sort of mistakes again you can add error_reporting(E_ALL); to the beginning of your script and set display_errors to on in your PHP config during development.
var s1 = <?php echo json_encode($chartvals); ?>; //!the echo seems to create

Categories