This question already has answers here:
Convert php array to Javascript
(21 answers)
Closed 9 years ago.
I would like to concatenate a php array into javascript array.
And use all of this to create jquery function.
Help me...
Instructions for in the loop are => descriptif[i] = .$description[i].;
<?php echo '<script> var descriptif = new Array ();
for(i=0 ; i<16 ; i++)
{
descriptif[i] = "'.$description["'"+ i +"'"].'";
}
</script>';
?>
You cannot access PHP arrays using client-side Javascript.
PHP is a server-side language. Everything happens on the server.
Javascript is a client-side language. Everything happens in the browser.
I guess you're thinking about:
<script> var descriptif = new Array ();
<?php for(i=0 ; i<16 ; i++) {
echo "descriptif[$i] = '$description[$i]';"
} ?>
</script>
It will print:
<script> var descriptif = new Array ();
descriptif[0] = value1;
descriptif[1] = value2;
descriptif[2] = value3;
...
</script>
PS if you want to dynamize something (javascript, css ,etc.) with a scripting language (php, jsp), use , <% %> only in the parts that differ (the loop part). The rest is the same so it doesn't have to be echoed - it makes your code less clear.
Related
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
I have that code:
function saveData(position, map) {
var latlng = marker.getPosition();
var late = latlng.lat();
var longe = latlng.lng();
<?php
require("sql.php");
session_start();
$name = 'prova';
$address = 'temare';
$type = 'bar';
$late = "<script>document.getElementByID('late').value</script>";
$longe ="<script>document.getElementByID('longe').value</script>";
I need to get late and longe variables in PHP but this doesn't work, anyone knows how I can do it?
You can't access javascript variables using PHP as JavaScript is executed on client side ( browser ) and PHP on server side.
The best what you can do is send data from those variables as request to server and read them, for example using jQuery ajax request:
Good example you can find here:
jQuery Ajax POST example with PHP
Or you can use this:
javascript
function sendData(variable1, variable2) {
$.ajax({
type: 'post',
url: 'myphpscript.php'
data: 'var1='+variable1+'&var2='+variable2
});
myphpscript.php
<?php
$variable1 = $_POST['var1'];
$variable2 = $_POST['var2'];
<script type="text/javascript">
<?php $abc = "<script>document.write(late)</script>"?>
<?php $def = "<script>document.write(longe)</script>"?>
</script>
This question already has answers here:
how to convert javascript variable to PHP variable? [closed]
(2 answers)
How to get JavaScript function data into a PHP variable
(5 answers)
Closed 9 years ago.
i am trying to get the javascript variable value to php.
here is my javascript code:
function getResults()
{
var radios = document.getElementsByName("address");
for (var i = 0; i < radios.length; i++)
{
if (radios[i].checked) {
var a = radios[i].value
alert(a);
break;
}
}
}
from this javascript i want to get variable a's value inside php code onclick on submit button.
how can i do this?
i tried this
$var1 = $_GET["a"];
Do this..
$var1 = <?=$_GET["a"]?>;
to communicate a value from JavaScript to PHP do following
$var1 = <?=$_POST["a"]?>;
What you tried is almost correct:
var a = <?=$_GET["a"]?>;
Since javascript code runs on client-side, but PHP is server-side code, you need to send your JS variables to the server. You can do this using AJAX.
Hint: AJAX calls usually use POST instead of GET.
Replace:
$var1 = $_GET["a"];
on:
$var1 = <?=$_POST["a"]?>;
This question already has answers here:
Pass a PHP string to a JavaScript variable (and escape newlines) [duplicate]
(14 answers)
Closed 9 years ago.
Yes I know this question gets asked a lot, but I'm fairly new to JS and I need to use a php variable in some JS. I'm more then aware that PHP is executed server side and JS is client side however other people claim that this works.
I've got a PHP variable called "test1" that I want to log to the JS console (for instance):
<?php
$test1 = '1';
print '
<script type="text/javascript">
var carnr;
carnr = "<?php print($test1); ?>"
console.log(carnr);
</script>';
?>
What this does is print " " to the JS console. Not exactly what I was hoping for.
Now this may not even be doable and I may have to pass the variable off the page and back in again with AJAX, but I'd rather have a quick and easy solution if there is one available!
Any help is appreciated.
You could do this.
<script>
var JSvar = "<?= $phpVar ?>";
</script>
The PHP will be parsed and the value of $phpVar will become the value of JSvar whatever.
Make sure you encode phpVar properly. For example, if phpVar contains a double quote, you'll end up with a broken JS
Use this no need to give "" => change to '.$test1.'..
<?php
$test1 = '1';
print '
<script type="text/javascript">
var carnr;
carnr = "'.$test1.'"
console.log(carnr);
</script>';
?>
try
<?php $test1 = '1'; ?>
<script type="text/javascript">
var carnr;
carnr = "<?php print($test1); ?>"
console.log(carnr);
</script>
Generally, it is better to not print static stuff with php, but to have static (that is unchanging) stuff directly in HTML and only use PHP on the parts that really need it.
You made a mistake do it so:
<?php
$test1 = '1';
echo '<script type="text/javascript"> var carnr; carnr = "'.$test1.'" console.log(carnr)</script>';
?>
Since you're writing your JS with your PHP, you can simply do:
$test1 = "blah";
echo "<script type=\"text/javascript\">console.log($test1);</script>";
You are already in open php tag. When printing the line just append the variable to the output by using a dot.
Example:
print 'variable1 '.$variable1.' is now printed';
I have a sql query that pulls an array that contains file paths to my images.
It is store in the variable $rows and I can access individual paths by indexing throught...
IE.
$rows[0]...$rows[n]
How can I utilize java script to step through this.
Final goal is for the picture to appear with a "Next" "Previous" button under it.
Hitting next would show the next image (without a refresh)
echo $rows[0];
would print
images/a.png
Maybe using PHP's json functions you can convert your PHP array to a js array... and then use javascript functions to control which picture to show
<script type="text/javascript">
var images = <?php echo json_encode($rows) ?>, counter = 0;
function prevImage() {
counter = (counter<=0)?images.length-1:counter-1;
var i = document.getElementById('myImage');
i.src = images[counter];
}
function nextImage() {
counter = (counter==images.length-1)?0:counter+1;
var i = document.getElementById('myImage');
i.src = images[counter];
}
</script>
and
<img src="img/0.jpg" id="myImage" />
Previous - Next​
Here is a little example to move your php array to a javascript array:
<?php
$row = array("image/image1","image/image2","image/image3");
?>
<html>
<head>
<title>Sample Array</title>
<script>
var jsArray = new Array();
<?php
for ($i=0; $i<3; $i++)
{
echo "jsArray[$i] = '$row[$i]';";
}
?>
for(i = 0; i < jsArray.length;i++)
{
alert(jsArray[i]);
}
</script>
</head>
<body>
<span>Sample Array</span>
</body>
</html>
Good luck!
Get your PHP array (server-side) to Javascript (clientside)
There are quite a few ways to go about doing this, but I'd recommend JSON. It has numerous advantages, but the most obvious one is you can store arrays and javascript objects as a string. If you're not familiar with it, this would be an excellent time to start including it in your workflow, considering you have to deal with Javascript.
PHP
Turn Array to JSON:
$jsonResults = json_encode($arrayOfResults);
Get JSON from PHP to Javascript:
<script>
var myAppsData = {};
myAppsData.slideshowJSON = JSON.parse($jsonResults);
</script>
Now your JSON object is accessible to Javascript at myAppsData.slideshowJSON.
The rest of the work is as simple as iterating through the object with a for loop (just like you would in PHP), grabbing the content and doing what you want with it.
Cheers!
This question already has answers here:
Call php function from JavaScript
(5 answers)
Closed 7 years ago.
I'm trying to use my PHP function in JavaScript like this:
PHP code:
function checkevents($date){
$ev = new CalendarModelEventss();
$wh = "`event_date` = '".$date."'";
$all = $ev->getAllEvents('event_date', $wh);
if($all == $date){
//echo 'event is available'.$all;
return true;
} else {
return false;
//echo 'event is NOT available' .'--'. $all;
}
}
and JavaScript code:
var yyyy = date.getLocalFullYear(true, this.dateType);
var mm = date.getLocalMonth(true,this.dateType);
var dd = iday;
var ddddd = yyyy+'/'+mm+'/'+dd;
if(<?php checkevents( ?>ddddd<?php ) ?>){
cell.className += " eventsss ";
}
but it doesn't work, and I have PHP error (syntax error, unexpected ';', expecting ')' in ...).
As the previous speaker said, it's impossible to directly call php functions from javascript. PHP could be used to output javascript though.
In your case you would need to send an ajax-request from the client side (with javascript) that executes the php code (on the server side), fetches the output and puts it into your if-statement.
If you do not know alot about javascript/AJAX you could take a look at jQuery or another similar framework.
Javascript is parsed on client side and PHP on Server side.
Without AJAX this is impossible.
Example with JQuery:
PHP:
...
echo "true";//or something else that indicates the success
} else {
echo "false";//or something else that indicates the failure
}
...
Javascript:
$.ajax({
url: "URL TO YOU PHP SCRIPT",
cache: false
}).done(function( html ) {
if(html.match(/true/g)){
cell.className += " eventsss ";
}
});
You cannot directly call php function using javascript directly as both of them are on different sides.So what you do is make an AJAX call with certain parameters and after that call that php function directly from that php file with the parameters to be validated.
And Send back the output back to javascript by echoing the output and do whatever with it on javascript.