error trasfering php array to javascript - javascript

I have this array:
$men['display']=array(
"edit" =>"1",
"description" =>"2",
"phone" =>"3",
"mail" =>"4"
);
I tried to transfer it to javascript by using:
<?php $disArray = json_encode($men['display']);?>
then, I sent it to javascript:
<select id="selectBoxHere" onChange="loadInnerHTML('<?php $disArray ?>')";>
For some reason, my javascript function 'loadInnerHTML' dosen't send my array to javascript.

You forget the echo statment.
And if you use single quotes, it makes this a string. For a javascript object you don't need the single quotes, json_encode will ensure it is javascript safe.
loadInnerHTML(<?php echo $disArray ?>)
I'd also recommend that you store this variable directly in javascript first, rather than passing it into a function. Otherwise you have to worry about double quotes inside double quotes, breaking your <select> tag.
var disArray = <?php echo $disArray ?>;
Then you can just use that variable.
loadInnerHTML(disArray)

Echoing an array in php will result in
var dis_array = Array
which js couldn't understand. Try:
var disArray = JSON.parse( '<?php echo json_encode( $disArray ) ?>' );

Related

JavaScript call function with PHP-Variable as transfer parameter

I am calling the JavaScript-function getElementById. As transfer parameter I want to use the PHP-Variable $currentTab
var currentTab = document.getElementById(<?php $currentTab ?>);
You need to add quotes, and output your variable with echo. Maybe add the # character if it is not in your php variable
document.getElementById('<?php echo $currentTab; ?>');
Just add ' or " around <?php $currentTab ?>, for getElementById() accept a string. And in javascript a string is surrended by ' or ".

Can I force PHP implode function to print quotes around string values?

$axisLabel = array(
"HI",
"MOM"
);
echo implode(',', $axisLabel);
Prints:
HI,MOM
I want
"HI", "MOM"
I need quotes values for insertion of values into JavaScript
If you want to pass array to javascript you should use json_encode() function:
echo json_encode($axisLabel);
This is what I always do
echo '"'.implode('","', $axisLabel).'"';

Pass PHP array values to JavaScript variable

I am trying to get the values of PHP Array in JavaScript variable.
Here is my code:
$qry="select * from optin";
$rlt1=mysql_query($qry);
$em_ary=array();
while($row= mysql_fetch_array($rlt1)){
$em_ary=$row;
echo $em_ary['timer'];}// this echo show all records that I have in data base and I want to get all the values in Javascript
<script>
var tmr=[];
tmr='<?php echo json_encode($em_ary['timer']); ?>';
alert(tmr);// this alert only shows the last record in the database
<?script>
Where I am going wrong or is there any other way to accomplish this?
Thanks in advance!
You need to update this line:
$em_ary = $row;
and change it to:
$em_ary[] = $row;
You are overwriting the array each time you want to add a new element to it.
Then, in the JS part, update this line:
tmr = '<?php echo json_encode($em_ary['timer']); ?>';
to:
tmr = JSON.parse('<?php echo json_encode($em_ary); ?>');
Hope this helps! Cheers!
You are overwriting values within your $em_ary array in order to make an array of values you need to place [] after $em_ary which will result you an array
$em_ary[]=$row;
You need to update this also from
tmr='<?php echo json_encode($em_ary['timer']); ?>';
into
tmr="<?php echo json_encode({$em_ary['timer']}); ?>";

JavaScript - Bring multiple variables from PHP

I have the following PHP code. It creates multiple variables using $a; for example: $numtoken1.
$sql ="SELECT token, dispositivo FROM dispositivos WHERE idcliente=1";
mysql_select_db('localiza');
$retval = mysql_query( $sql, $conn );
$num_rows = mysql_num_rows($retval);
while($row = mysql_fetch_array($retval, MYSQL_BOTH))
{
$numtoken['$a']=$row['token'];
$numdispositivo['$a']=$row['dispositivo'];
$a=$a++;
}
Using JavaScript, I want to call all the PHP variables using that code, but it only get the last $a number.
My question is: In a JavaScript loop, how can I dynamically insert the value for $a? Because in the above PHP, I have multiple values for $a.
var accessToken = "<?= $numtoken['$a']; ?>"a;
var deviceID = "<?= $numdispositivo['$a']; ?>";
I suggest JSON:
var accesstoken = JSON.parse("<?= json_encode($numtoken); ?>");
var deviceID = JSON.parse("<?= json_encode($numdispositivo); ?>");
So the first thing I noticed when looking at this is that you are wrapping $a in single quotes (') instead of double quotes (") this means that instead of evaluating $a the key in the array will be the string "$a", so you'll be overwriting the value in each iteration of the while loop. See - http://php.net/manual/en/language.types.string.php#language.types.string.parsing for more info.
That being said the actual answer to your question varies, but the simplest method might be to use the json_encode function to convert your arrays into json objects.
var accessTokenArr = <?php print json_encode($numtoken); ?>
var deviceIdArr = <?php print json_encode($numdispositivo); ?>
Then you can iterate over the values in those arrays and do whatever you want to with the values. Fair warning - you may need to tweak that code a little as I haven't tested it to make sure it plays nicely.

passing php string of JSON ( with qoutes) to onclick function

I'm trying to pass an array of data from php to java script for "onclick" event.
I do it by converting the array data into JSON string in order to parse it back in the js function and work on it.
The problem is that JSON string contains double quotes , so it arises an error as the double quotes break the html string (Uncaught SyntaxError: Unexpected token ILLEGAL ). I did see several questions similar to this, but didn't find a solution to what I need, or maybe I didn't understood the correct solution. So I bring it up here with my specific case.
<?php
..some php code here..
$aData = array("You","Me",76,array(3,6));
$sJSONstr = json_encode($aData);
?>
<input type="button" name="formSubmit" value="Delete" onclick="analyze('<?php echo $sJSONstr; ?>')">
<?php
..some php code here..
?>
and the js function is as follows:
function analyze(i_sInputDataJSONStr)
{
var aInputData = JSON.parse(i_sInputDataJSONStr);
.. So something with the input data array..
}
Use single quotes for the onclick attributes instead of double quotes. Single quotes is equally valid as double quotes.
One more thing, since you already have your data in JSON format, there is no need to put it as a string in the analyze function call, since your JSON data is a valid JavaScript array (that's what JSON stands for: JavaScript Object Notation).
Therefore, you don't have to parse the input string in your analyze function declaration.
Consider the following example, this is perfectly valid code.
<?php
$arr = ["Hello", "World"];
$json = json_encode($arr); // $json = '["Hello","World"]'
?>
<div id="myDiv" onclick='doSomething(<?php echo $json; ?>)'>Click me</div>
<script type="text/javascript">
function doSomething(data){
for (var i = 0; i < data.length; i++) {
alert(data[i]);
}
}
</script>
create a javascript string and pass it:
<script type="text/javascript">
var myjson = '<?php echo $sJSONstr; ?>';
</script>
and then:
onclick="analyze(myjson)"
<input type="button" name="formSubmit" value="Delete" onclick='analyze(<?php echo $sJSONstr?>)'>
Replace the double quotes with single quotes in onclick='';
Worked like a charm for me.

Categories