PHP/JS - Accessing PHP variable from JS function Argument - javascript

.php
<?php
$timeArray = [355,400,609,1000];
$differentTimeArray = [1,45,622, 923];
?>
<script type="text/javascript">
var i=0;
var eventArray = [];
function generateArray(arrayName){
eventVideoArray = <?php echo json_encode(arrayName); ?>;
var vid = document.getElementById('my_video');
vid.currentTime = eventVideoArray[i];
}
</script>
<button onClick="javascript:generateArray(timeArray)"><button>
Currently I can get the function to generate the desired output by making generateArray have no arguments and replaing arrayName with $timeArray.
i.e. Working Code
<script type="text/javascript">
var i=0;
var eventArray = [];
function generateArray(){
eventVideoArray = <?php echo json_encode($timeArray); ?>;
var vid = document.getElementById('my_video');
vid.currentTime = eventVideoArray[i];
}
</script>
I want to use generate function to call on many different Time arrays, so getting JS to call directly from the php array would make coding much easier. Any help would be much appreciated.
Thanks!
[SOLVED]
Hi there,
Not sure about the comments regarding php not being able to run, I had a working example on my IIS just not quite flexible enough.
I solved the issue by rewriting the button in html. Now I can add new time arrays to video using the same function.
Thanks for the help.
<?php
$timeArray = array();
$timeArray[] = 345.1;
$timeArray[] = 789.1;
$timeArray[] = 1002.1;
$timeArray[] = 1200.12;
$differentArray = array();
$differentArray[] = 1500;
$differentArray[] = 1700;
?>
<script type="text/javascript">
var i = 0;
var eventVideoArray = [];
function generateArray(arrayName){
eventVideoArray = arrayName;
var vid = document.getElementById('my_video');
vid.currentTime = eventVideoArray[i];
}
</script>
<button id="goToTime" onClick="javascript:generateArray(<?php echo json_encode($timeArray); ?>)">timeArray</button>
<button id="goToTime" onClick="javascript:generateArray(<?php echo json_encode($$differentArray); ?>)">differentTimeArray</button>

PHP runs on the server and JS runs on the client. You want the client to call the server for the values for the array you will need an Ajax call or print the values directly to the JS (as already done on your code).
Depending on the project making an Ajax call would be a bit too much to be done.

A webserver will not parse PHP in a .html file...
Either, generate your Javascript variable in your PHP file and declare it global..
Or, change your .html file extension to .php so that the PHP in it gets parsed by the webserver.

Related

Passing Javascript variable to php on the same page

I'm trying to pass a javascript variable to php on the same page. I tried some code but nothing worked.
The current code looks like this:
function init(e){
$('#DeleteDaily').click(function() {
d = document.getElementById("DailyRequestsList");
selected = d.selectedIndex;
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "index.php?i=" + selected, true);
xhttp.send();
});
}
$(document).ready(init);
$(document).ready(function() {
$('#myForm').ajaxForm(function() {
<?php
if(isset($_POST['DeleteDaily'])) {
$Index = $_GET['i'];
}
?>
});
});
If I try to use Index as an argument for a python script it should delete an entry in a textfile and an element from a select object should be deleted on the website which doesn't happen. The python script itself works fine.
But I don't know why the variable isn't passed to php.
You can't just "mix" javascript and PHP like you're doing.
If that is inside a web page, the PHP code will be rendered (in your case, it will return nothing), and the page will just interpret an empty javascript function.
You need that PHP to be on the server, or turn it into javascript...
you can done it by
PHP Code
<?php
if(isset($_POST['DeleteDaily'])) {
$Index = $_GET['i'];
}else{
$Index='';
}
?>
Javascript code
$(document).ready(function() {
$('#myForm').ajaxForm(function() {
var index = '<?php echo $Index;?>';
if(index == ''){
//put your code
}else{
//put your code
}
});
});

Javascript var change when reload page

I have a string array in javascript. But when I use href='mypage.php?id=var', I lost this array. I need keep it out for use it in the $_GET. This is the code:
<script>
var element_selected=[];
var i = 0;
function hrefPage()
{
var pagina = "index.php?id=renew";
location.href = pagina;
}
function loadArray(value)
{
element_selected[i] = value;
i++;
}
</script>
<?php
if(isset($_GET['id']))
{
if ($_GET['id'] == "renew")
{
$selected_elements = array();
$j = 0;
for($j = 0; $j < "<script> document.write(i) </script>"; $j++)
{
$selected_elements[j] = "<script> document.write(elements_selected[j]) </script>";
echo $selected_elements[j];
}
}
}
?>
You need to use local storage to use retain javascript variables value across page reloads
var varName = "sachin";
localStorage.setItem("varName", VarName);
alert(localStorage.getItem("varName"));
Another example how to store array in localstorage
var arrayName= [];
arrayName[0] = prompt("Enter your value");
localStorage.setItem("arrayName", JSON.stringify(arrayName));
//...
var storedValues = JSON.parse(localStorage.getItem("arrayName"));
I have added a simple example here how to set javascript value in localstorage and how to access it
I have provided it as an information for you to retain value across page reloads
but first thing about http is that it is a stateless protocol .Each request fetches data from server and renders it in browser the value here is set in local storage of browser .So if you want to reload some value to script after page reload you need to set some flags and on page load check that flag if flag condition for the required situation arises get data from localstorage else proceed as normal
Check out this tutorial for more information

how to send javascript variable to php mysql [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
I am trying to insert javascript varaible to php mysql, but it is not inserting. it is inserting as <javascript>document.write(window.outerWidth); </javascript> x <javascript>document.write(window.outerHeight); </javascript>. but the result is 1366 x 728
What should I do?
<?php
$width = " <script>document.write(window.outerWidth); </script>";
$height = " <script>document.write(window.outerHeight); </script>";
$xex = " x ";
$resulteee = "$width $xex $height";
echo $resulteee;
?>
AJAX is a good solution to your problem :
<script type="text/javascript">
function call_ajax () {
var width = window.outerWidth;
var height = window.outerHeight;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("abc").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "a.php?height="+height+"width="+width, true);
xmlhttp.send();
}
</script>
and on the page a.php, you can echo your variables to get the output like this :
<?php
echo $_POST['height'];
echo $_POST['width'];
die;
The best way is AJAX, which is a way for Javascript to send data to a PHP script. You should do some research on your own, but your solution will end up looking something like this. I'm using jQuery syntax, which is a really helpful Javascript library that I recommend looking into.
// get values we want
var width = window.outerWidth;
var height = window.outerHeight;
var payload = {"width" : width, "height" : height}; // just a normal object
// send them to server
$.get('/path/to/script.php', payload, function(response) {
alert('Sent the values!');
});
And in your PHP:
<?php
$width = $_GET['width'];
$height = $_GET['height];
/*
* DEFINITELY sanitize these things before they're anywhere NEAR the database!
* research "prepared statements" and "mysqli escape" or you are going to have a very bad time with a hacked server
*/
// do some database stuff!
Hopefully this gives you a good starting point. You really need to make sure you sanitize data before you blindly let it touch a database query or attackers can easily perform a SQL Injection attack, deleting your database or dumping all your data. These are very bad things.
You'll have to send it to a separate php file to insert it into MySQL... You'll also have to use Ajax. Include the jquery plugin in your page for that.
So this would include this in your main page. Call the submitstuff() function when the button is pushed instead of submitting a form like normal:
<script>
function submitstuff(){
var wheight = window.outerHeight;
var wwidth = window.outerWidth;
var results = wwidth+" x "+wheight;
$.ajax({
url : "submit.php",
type: "POST",
data : "result="+results,
});
}
</script>
Then, make a file called submit.php and put it in the same folder as your main file.
submit.php
/* include all your database connection stuff */
mysql_query("insert into `yourtable` (`size`) values ('".$_POST['result']."');");
I didn't test this, but I think it might work... :)
Try jQuery's $.post
var width = x;
var height = y;
$.post( "page.php", // name of the page you want to send the variables
{width:width,height:height}, // variables
function( data ) { // returned values from the page
alert(data);
}
);
You can get the variables using $_POST['width'] and $_POST['height'].

How do you use a php variable for directory path?

I am getting userid from the url.
This is what I have at the moment. I want to replace the one with $userid but I don't know how. It doesn't work and I can't seem to find the right syntax, please can someone help?
function returnimages($dirname = "Photos/1")
Basically I am trying to create a photo slideshow using html, php and javascript. I had something working before I started adding php into my code. I had html and an external javascript that changes the photos and they fade in and out in a loop. I have a photo array in javascript. Right now I am trying to add php to my html. I want to be able to get userid via url and then from that get the photos from a specific path to the userid in the directory. Then I am hoping to create an array of these photos and use them in my javascript. Here is my php code embedded in my html:
<?php
$user_id = $_GET['userid'];
print " Hi, $user_id ";
function returnimages($dirname = "Photos/1") { //will replace 1 with userid once something starts working
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo 'galleryarray['.$curimage.']="'.$file .'";';
$curimage++;
}
}
closedir($handle);
}
return($files);
}
echo 'var galleryarray=new Array();'; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names
?>
And my javascript:
$ (document).ready(function(){
var photodisplay =
[
$("#photo1"),
$("#photo2"),
$("#photo3"),
$("#photo4"),
$("#photo5"),
];
//photodisplay[0].hide().fadeIn(3000);
var user = new Array();
[1, 2, 3, 4, 5];
// List of images for user one
/*var userphoto = new Array();
userphoto[0] = "Photos/1/1.jpg";
userphoto[1] = "Photos/1/2.jpg";
userphoto[2] = "Photos/1/1.jpg";
userphoto[3] = "Photos/1/1.jpg";
userphoto[4] = "Photos/1/1.jpg";*/
//preloading photos
var userphoto = <? echo json_encode($galleryarray); ?>;
function preloadingPhotos() {
for (var x=0; x<5; x++)
{
photodisplay[x].attr("src", "Photos/1" + userphoto[x]);
photodisplay[x].hide();
console.log("preloaded photos");
}
displayPhoto();
}
function displayPhoto(){
photodisplay[0].fadeIn(3000);
photodisplay[0].delay(3000).fadeOut(3000, function() { //first callback func
photodisplay[1].fadeIn(3000);
photodisplay[1].delay(3000).fadeOut(3000, function() { //second callback func
photodisplay[2].fadeIn(3000);
photodisplay[2].delay(3000).fadeOut(3000, function() { //third callback func
photodisplay[3].fadeIn(3000);
photodisplay[3].delay(3000).fadeOut(3000, function() { // fourth callback func
photodisplay[4].fadeIn(3000);
photodisplay[4].delay(3000).fadeOut(3000, function() {
setTimeout(displayPhoto(), 3000);
});
});
});
});
});
}// end of function displayPhoto
window.onload = preloadingPhotos;
}); //end ready
My url to get userid:
http://example.com/code.php?user_id=1
Thank you for your time!
The problem is that you are always setting the dirname instead of letting calling the function set it. You could change:
function returnimages($dirname = "Photos/1") {
to
function returnimages($dirname) {
because otherwise the $dirname is always Photo/1. Then, when you call the function, use:
returnimages('Photos/'.$user_id);
You can concatenate in PHP by using the dot '.'. This will concatenate two string and then assign them to the variable $dirname. For example:
$dirname = "Photos/" . $_GET['ID'];
The variable $dirname can then be placed in the function returnimages, like:
returnimages($dirname);

defined path from php to javascript

I have a little problem with the syntax in Javascript. I want to work with a defined variable for a path in Javascript.
function checkusername(){
var u = _("username").value;
if(u != ""){
_("unamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "http://localhost:8888/.../file.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("unamestatus").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+u);
}
}
Now I want to set for
http://localhost:8888/.../file.php
a defined variable from php
define('Name','http://localhost:8888/.../file.php');
You'd either have to retrieve that constant via an AJAX call, or embed it into the Javascript at the time PHP is building the page.
e.g.
<?php
define('your_url', 'http://.....');
?>
<script type="text/javascript">
var url = <?php echo json_encode(your_url) ?>;
...
var ajax = ajaxOBJ('POST', url);
Note that if the sole purpose of this constant is to hold a url that's passed to javascript and is otherwise never used in PHP, you might as well just use a variable - Javascript could not alter the PHP/server-side value anyways, so it's effectively a constant.

Categories