I want to make an alert using JavaScript. This is an example I have made bls.hol.es.
When I click first name will display an alert containing the first name. But it displays an alert containing the second name.
This is my code:
<?php
$arrayname=array('iqbal', 'rezza');
$arrayaddress=array('teloyo', 'karang rejo');
for ($x = 0; $x <= 1; $x++)
{
$name=$arrayname[$x];
$address=$arrayaddress[$x]; // indent consistently!!
?>
<script>
function call()
{
var nik = "<?php echo $name ?>"; // semicolons not needed in the embedded PHP code
var addres = "<?php echo $address ?>"; // indent consistently!!
alert(nik+address);
}
</script>
<?php echo $name ?>
<?php
} ?>
Whether this can be done my way?
What is wrong in my code?
That happens because you're creating js function call() inside the loop, so technically you have two declarations of call() in resulting code. When you call the call() function, then both of them are processed.
I assume you want to use more logic in the call() in the future, so the solution would be to alter your js code to process the name as a parameter nad move it outside the loop like:
function call(name){
alert(name);
}
and alter the link:
<?php echo $name;?>
What's wrong with your code is the second pass through the loop redefines the call() function with the second name, so by the time it's been rendered in the browser window, only the second instance of the function is available to run.
Just loop the html with inline onclick using the php loop.
<a onclick="alert(this.innerHTML);">iqbal</a>
<a onclick="alert(this.innerHTML);">rezza</a>
Here's the php:
$arrayname=array('iqbal', 'rezza');
foreach($arrayname as $v){
echo "<a onclick='alert(this.innerHTML);'>$v</a>";
// or echo "<a onclick='alert($v);'>$v</a>";
}
The bottom line is, you don't want to write duplicate functions. Write one function, call it as many times as you wish, and pass $v as a parameter to it, then you can do what ever you wish with the parameter inside the function.
If you are making a function call and want to send three variables at time, you can set it up like this in php:
<script>
function call(one,two,three){
alert(one);
alert(two);
alert(three);
}
</script>
<?php
$array=[
['a','b','c'],
['d','e','f']
];
foreach($array as $a){
echo "{$a[0]} and {$a[1]} and {$a[2]}";
}
Related
I want to use javascript variable as php variable. I am echo php variable then its print. but when i am use for fetching data from database its show an error
Notice: Undefined index: document.write(i)
here my code
javascript
var i=0;
function inc()
{
i+=1;
}
<?php $foo="<script>document.write(i)</script>"; ?>
php
code work for
echo $foo
code not work for
$i=$foo;
$query="select * from TABLE where id = $i";
$result=mysqli_query($conn,$query);
while($row=mysqli_fetch_row($result))
{
echo $row[0];
}
Then It show This Error Notice: Undefined index: document.write(i)
PHP is server-side code that is run to generate a page. Javascript is client-side code that is run after the page is sent to the visitor's browser. Javascript can't affect the server-side code because the server code is done running by the time the Javascript runs. If you want to have a user's selection change the behavior of the PHP code the next time the form is loaded, pass a variable through a $_POST variable when the form is submitted.
If you want your PHP and Javascript code to be using the same value, have the PHP code write a Javascript variable initialization into the page's <head> section before any Javascript would run that would need to use it.
<script>
var i=0;
function inc()
{
i+=1;
return i;
}
</script>
<?php
$foo = '<script type="text/javascript">document.write(inc());</script>'; //Script function call which return the var i value to php variable
echo $foo;
?>
Whenever I write echo $_GET['sec']; then it shows the value of sec
but when I try the following code:
$(document).ready(function() {
setInterval(function () {
$('#div_id').load('../data.php?id_to=<?php $_GET['sec'];?>')
}, 100);
});
The value of "sec", which is coming from another page does not transfer to
data.php with id_to variable.
What's wrong with my code?
I can see the value of $_GET['sec']; in current page but the value is not available on the data.php file.
Code is okay so variable if available should be passed
So what can you try is:
You have simple mistake you don't echo
change <?php $_GET['sec'];?> to <?php echo $_GET['sec'];?> or <?= $_GET['sec'] ?>
also:
what's the output of this php code is it ile '../data.php?id_to=VALUE' If output is okay then variable will be passed via GET method
In your data.php try doing echo $_GET['id_to'] maybe you try to output sec and this causes problem?
You can always try print_r($_GET); on data.php
You're not outputting the GET variable into your JS string.
Replace:
$('#div_id').load('../data.php?id_to=<?php $_GET['sec'];?>')
With:
$('#div_id').load('../data.php?id_to=<?php echo $_GET['sec'];?>')
// That was missing ^
Alternatively, there's a shorthand available for a php echo:
$('#div_id').load('../data.php?id_to=<?= $_GET['sec'];?>')
While the syntax highlighter on here may make it seem like the nested single quotes will interfere, they won't. <?= $_GET['sec'];?> will literally be replaced by the value in sec, resulting in a valid JS string.
I'm having a little trouble calling a PHP variable into a jQuery script. Basically, I run a few functions to determine if a user is logged in and, if so, store that as $loggedin=1. If a person that is on a page is NOT logged in, when a button is clicked I want them to be prompted to sign in (I'll obviously still ensure the user is ACTUALLY logged in on the server side before any processing of data). I searched around, and found the easiest way to get that information over to jQuery is to create the script as a PHP file so I can echo it into the script. Here is the high level code I'm using:
Call up the script:
<?php
$loggedIn = 1;
<script src="../buttonScript.php"></script>
?>
Script:
<?php header("Content-type: application/javascript"); ?>
var buttonScript = function(){
var loggedIn = <?php if($loggedIn===1){echo "1";}else{echo "0";} ?>;
$("#button").click(function(){
alert(loggedIn);
});
};
$(document).ready(buttonScript);
When I click the button in a situation where $loggedIn is equal to 1, the alert gives me 0. In fact, if I simply echo $loggedIn in the script itself, the value is completely empty and the script errors out and won't pop up an alert at all. I'm confident that the PHP variable $loggedIn actually has a variable, since if I echo the variable right before the script is called, I successfully see the number 1. What am I missing here?
Note: added a couple lines in the script calling just for clarity.
Try this
<?php
$loggedIn = 1;
require("/path/buttonScript.php");
?>
buttonScript.php
<script type="text/javascript">
var buttonScript = function(){
var loggedIn = <?php echo $loggedIn; ?>;
$("#button").click(function(){
alert(loggedIn);
});
};
$(document).ready(buttonScript);
</script>
I have a javascript method in separate js file that I want to call from a HTML page with a php argument.
<?php
include "connection.php";
$selectedpatient = $_POST['patient_dropdown'];
$myquery = "SELECT * FROM `patient_info` patient_info.Name = '$selectedpatient' ";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
$tempdata = json_encode($data);
?>
<script> data_arrival($_tempdata); </script>
And I defined the source for the javascript file in the HTML header. It displays two errors:
1) Parse error in the javascript file - that's understandable as I included the javascript file in header and the file gets executed before the php actually retrieves any data.
2) data_arrival method is undefined
How can I fix this ?? I want to pass the $tempdata (after its populated by php) to data_arrival method as an argument.
Thanks in advance !
First of all: it's PHP that's executed first, not JavaScript. It can't be the other way round in your example.
data_arrival is undefined... because either you haven't defined it at all, or because it is defined after it's called.
To pass the value from PHP to JavaScript in your case, you can use:
data_arrival(<?php echo $_tempdata; ?>);
It will generate something like:
data_arrival([a, b, c, d, ...]);
Of course, data_arrival function need to be defined prior to its execution.
Edit
And maybe it's good to use the same variable name: $_tempdata vs $tempdata.
For example i declare some variable like test in server side of my PHP
echo('var test = ' . json_encode($abc));
Now i want to use this test variable in Jquery ..how can i use it?
What function do i need to use it?
For Example i have:
I have back end PHP code something like this
$abc = no
echo "var test= ".json_encode($abc);
I want jquery to do the following action(client side)
$(document).ready(function(){
function(json) {
if($abc == no )//this i what i want to be achieved
}
}
I think, you dont understand the diference between frontend (JavaScript) and backend (PHP). You can not directly access php variables from javascript. You need to make Ajax-request to some php file, that will return some data that you need in format that you specify.
for example:
<?php
$result = array('abc' => 'no');
echo json_encode($result);
?>
This is serverside script called data.php. In Javascript you can make so:
$(document).ready(function(){
$.getJSON('data.php', function (data) {
if(data.abc === 'no') {
your code...
}
});
}
You're comparing the wrong variable:
<?php
echo <<<JS
<script type="text/javascript">
var test = {json_encode($abc)};
$(document).ready(function(){
if(test == 'no' )
// here you go
}
});
</script>
JS;
If you really wanted to (though I don't think this is a very good practice), you could echo the PHP variable's value into a javascript variable like this:
<script type="text/javascript">
var phpValue = <?php echo $abc; ?>;
alert(phpValue);
</script>
I can see this being dangerous in many cases, but what this effectively does is echo the value of $abc onto the page (inside of your script tags of course). Then, when the javascript it run by the browser, the browser sees it like this:
<script type="text/javascript">
var phpValue = no;
alert(phpValue);
</script>
This is very basic, but you get an idea of what you could do by using that kind of code.