JavaScript call function with PHP-Variable as transfer parameter - javascript

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 ".

Related

How can i pass multiple parameters in location.href in php?

example (this is not working)
location.href = 'freecreate?fname=+fname+"&Mnumber="+Mnumber+"&sitename="+sitename';
Add double quotes(") after fname= , Use this:
location.href = "freecreate?fname="+fname+"&Mnumber="+Mnumber+"&sitename="+sitename;
If you are working with php variables just Declare them,
assign values and append them
using . operator
See the example below:
<?php
$fname="bhansa";
$Mnumber ="number";
$sitename ="stack";
echo "<script>window.location = 'freecreate?fname=".$fname."+&Mnumber=".$Mnumber."+&sitename=".$sitename."'</script>";
?>
Use #Dhara Parmar's method if you want to use in javascript.

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.

Escaping javascript onclick with json data

I've got a button I build with php to fire a javascript onclick event:
<button onClick='edit(this, "<?php echo $this->result[$i]["type"]; ?>","<?php echo $quality; ?>", "<?php echo json_encode($stuff); ?>", ...)">
</button>
I just added the json data $stuff. Now when I'm in javascript to get some values:
jQuery(stuff).each(function(index) {
console.log( "The key is " + this.name + " and the value is " + this.hash );
});
I get this error: SyntaxError: missing ) after argument list
This is because json data is using double quotes so the result looks something like this:
"foo", "bar", "[{"name":"test","hash":"123"},{"name":"test1","hash":"456"},..."
In this onclick event I've tried changing the quotes to single quotes or vice versa. I've tried escaping quotes with backslashes. It seems nothing works. What am I missing?
Have you tried escaping the quotes for the json that you are returning? You can do so like this:
echo json_encode($this->result[$i]["type"]);.
It will make your json like this:
\"foo\", \"bar\", \"[{\"name\":\"test\",\"hash\":\"123\"}....
If your code is already in json, json_encode() shouldn't change anything except adding the blackslashes.
... "<?php str_replace('"', '\"', $this->result[$i]["type"]); ?> ...
Maybe it's because in text you show (type) is " character.

error trasfering php array to 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 ) ?>' );

Modifying a JSON object returned with PDO

I'm trying to return use a JSON object with handlebars. Making a small todo list to learn how to use it.
My PHP API is as follows :
$query = "SELECT *
FROM table";
try
{
$db = getConnection();
$response = $db->query($query);
$todo = $response->fetchAll(PDO::FETCH_OBJ);
$bdd = null;
echo json_encode($todo);
}
It then returns something like :
[{"id":"1","todo":"Do something","who":"Me","is_done":"0"},{"id":"2","todo":"Learn JSON","who":"Me","is_done":"0"}]
But I'd actually need it to be like this :
{todos: [{"id":"1","todo":"Do something","who":"Me","is_done":"0"},{"id":"2","todo":"Learn JSON","who":"Me","is_done":"0"}]}
I tried in my PHP API to add instead of echo json_encode($todo)
echo '{todos: ' . json_encode($todo) . '}';
But it doesn't work. Any ideas ?
Your "todos" property name must be quoted with double-quote characters.
echo '{"todos": ' . json_encode($todo) . '}';
Though JavaScript syntax allows for property names without quotes, strict JSON insists on them.
While Pointy's answer is correct (might want to read about JSON), alternatively you could do this:
echo json_encode(array('todos' => $todo));
PHP associative arrays will be serialized to JSON as objects (json_encode() example in Manual).
Try with :
echo '{ "todos" : ' . json_encode($todo) . '}';
Try this:
echo json_encode(array( 'todos' => $todo ));
Instead of making the JSON yourself, make the structure you want, then have PHP make the JSON for you.

Categories