Javascript var change when reload page - javascript

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

Related

AJAX request not getting updated values of $_SESSION variable

I'm currently developing a web application and I am using PHP 8.0.3.
For some reason, the Ajax request is not capable of getting the updated value of the SESSION variable unless I forcefully refresh the page. I am calling the ajax function first when the page finishes loading, and then every minute.
I am using AJAX to update the values on a CanvasJS graph.
Can someone help me identify what am I doing wrong?
First, I start the session on a global file that I require on the scripts.
session_name("mfm");
session_start();
Snippet of my current ajax request on index.php page:
$.ajax({
method: "POST",
url: "php_func/somefile.php",
success: function(data){
console.log(data);
var dbdata = JSON.parse(data);
var qtyNuts = [];
var time = [];
dbdata = dbdata.reverse();
for (i = 0; i < dbdata.length; i++) {
time[i] = dbdata[i][1];
qtyNuts[i] = dbdata[i][0];
}
...
And this is part of the php_func/some_file.php:
if(isset($_SESSION['bar']))
{
$processed = $_SESSION['bar'];
$max = count($processed);
if($max > 5)
{
$max = 5;
}
$recent_data = array_slice($processed, -$max);
foreach($recent_data as $data)
{
$kgs = $data[0] / 120.0;
array_push($kgdata, array($kgs, $data[1]));
}
echo json_encode(array_reverse($kgdata));
}
I typed /php_func/some_file.php on my localhost URL and it works, kgdata array is getting updated as the SESSION variable updates.
And this is a snipped of where the session variable is created (this script runs as soon as the page is loaded and then every minute). Update.php:
$bar = array()
if(isset($_SESSION['bar'])
{
$bar = $_SESSION['bar'];
}
$b = array(count($buffer), date("H:i:s"));
array_push($bar, $b);
$_SESSION['bar'] = $bar;
For some reason, the ajax request does not update the values in the index.php graph, unless I forcefully refresh the page. What am I doing wrong?
I tried
Checking session id. They are the same in all files.
Use $.post instead. I have the same issue.
Change the setInterval for the ajax function to be more than a minute in case there is clashing between update.php and somefile.php

run php function using ajax to update phpBB template variable

NOTE: There are a lot of details here, so if anyone needs a condensed version of this, I'm happy to summarize.
I am trying to run a function in my php file, that will in turn, update a template variable. As an example, here is one such function:
function get_vehicle_makes()
{
$sql = 'SELECT DISTINCT make FROM phpbb_vehicles
WHERE year = ' . $select_vehicle_year;
$result = $db->sql_query($sql);
while($row = $db->sql_fetchrow($result))
{
$template->assign_block_vars('vehicle_makes', array(
'MAKE' => $row['make'],
));
}
$db->sql_freeresult($result);
}
I know that this function works. I am trying to access this function in my Javascript with:
function updateMakes(pageLoaded) {
var yearSelect = document.getElementById("vehicle_year");
var makeSelect = document.getElementById("vehicle_make");
var modelSelect = document.getElementById("vehicle_model");
$('#vehicle_make').html('');
$.ajax({ url: '/posting.php',
data: {action: 'get_vehicle_makes'},
type: 'post',
success:function(result)//we got the response
{
alert(result);
},
error:function(exception){alert('Exception:'+exception);}
});
<!-- BEGIN vehicle_makes -->
var option = document.createElement("option");
option.text = ('{vehicle_makes.MAKE}');
makeSelect.add(option);
<!-- END vehicle_makes -->
if(pageLoaded){
makeSelect.value='{VEHICLE_MAKE}{DRAFT_VEHICLE_MAKE}';
updateModels(true);
}else{
makeSelect.selectedIndex = -1;
updateModels(false);
}
}
The section in my javascript...
<!-- BEGIN vehicle_makes -->
var option = document.createElement("option");
option.text = ('{vehicle_makes.MAKE}');
makeSelect.add(option);
<!-- END vehicle_makes -->
... is a block loop and will loop through the block variable, vehicle_makes, set in the PHP function. This works upon loading the page because the page that loads, is the new.php that I'm trying to do an Ajax call to, and all of the PHP runs in that file upon loading. However, I need the function to run again, to update that block variable, since it will change based on a selection change in the HTML. I don't know if this type of block loop is common. I'm learning about them since they are used with a forum I've installed on my site, phpBB. (I've looked in their support forums for help on this.). I think another possible solution would be to return an array, but I would like to stick to the block variable if possible for the sake of consistency.
This is the bit of code in the php that reads the $_POST, and call the php function:
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
//Get vehicle vars - $select_vehicle_model is used right now, but what the heck.
$select_vehicle_year = utf8_normalize_nfc(request_var('vehicle_year', '', true));
$select_vehicle_make = utf8_normalize_nfc(request_var('vehicle_make', '', true));
$select_vehicle_model = utf8_normalize_nfc(request_var('vehicle_model', '', true));
switch($action) {
case 'get_vehicle_makes' :
get_vehicle_makes();
break;
case 'get_vehicle_models' :
get_vehicle_models();
break;
// ...etc...
}
}
And this is the javascript to run the Ajax:
function updateMakes(pageLoaded) {
var yearSelect = document.getElementById("vehicle_year");
var makeSelect = document.getElementById("vehicle_make");
var modelSelect = document.getElementById("vehicle_model");
$('#vehicle_make').html('');
$.ajax({ url: '/posting.php',
data: {action: 'get_vehicle_makes'},
type: 'post',
success:function(result)//we got the response
{
alert(result);
},
error:function(exception){alert('Exception:'+exception);}
});
<!-- BEGIN vehicle_makes -->
var option = document.createElement("option");
option.text = ('{vehicle_makes.MAKE}');
makeSelect.add(option);
<!-- END vehicle_makes -->
if(pageLoaded){
makeSelect.value='{VEHICLE_MAKE}{DRAFT_VEHICLE_MAKE}';
updateModels(true);
}else{
makeSelect.selectedIndex = -1;
updateModels(false);
}
}
The javascript will run, and the ajax will be successful. I've checked the network tab and console tab, and have done multiple tests to confirm that. It appears that the block variable is not being set. Is what I'm trying to do even possible? I have a feeling that to get this answer, we'll need to know more about phpBB's template engine, and how it works with these template variable. Also, just to clarify, I think the term 'template variable' is specific to phpBB. It's the term they use for variables set in PHP, to be accessed by the HTML, and javascript files. This works through a phpBB class called 'template', and a function called 'assign_block_vars'. I don't know exactly how that work.
If anyone has done this for phpBB, or has any ideas, I would appreciate it.
Think I found the problem. At the beginning of my PHP, I have an include statement to include the PHP file containing the class for connecting to the database. In the statement $result = $db->sql_query($sql);, $db is set in this other PHP file. I don't entirely understand, but because of that, $db was outside of the scope of my function get_vehicle_makes(). I had to create a class inside my PHP file, and pass $db as a parameter to the function using:
class vehicle {
public function __construct($db)
{
$this->db = $db;
}
function get_vehicle_makes()
{
$sql = 'SELECT make FROM phpbb_vehicles
WHERE year = ' . $select_vehicle_year;
$result = $this->db->sql_query($sql);
Hope this helps.

AJAX not submitting from external directory

I have a star rating system on my application - the following code works correctly if it is in the PHP doc. But when I remove it and place it in a js file, it doesn't work.
Could someone please let me know why it's not working when i call the js file. Thanks.
<script>
$(document).ready(function(){
$('.rate-btn').hover(function(){
$('.rate-btn').removeClass('rate-btn-hover');
var rating = $(this).attr('id');
for (var i = rating; i >= 0; i--) {
$('.rate-btn-'+i).addClass('rate-btn-hover');
};
});
$('.rate-btn').click(function(){
var rating = $(this).attr('id');
var dataRate = 'act=rate&app_id=<?php echo $app_id; ?>&id=<?php echo $id; ?>&rate='+rating;
$('.rate-btn').removeClass('rate-btn-active');
for (var i = rating; i >= 0; i--) {
$('.rate-btn-'+i).addClass('rate-btn-active');
};
$.ajax({
type : "POST",
url : "submitRating.php", // I have tried changing this to reflect the directory
data: dataRate,
success:function(){}
});
});
});
</script>
What "TamilSelvan" said is right you can't inject php code in js file. Try keeping the app_id and id in webstorage (or cookies) if you are redirection from some other page to this page and then make use of them in js file else first make AJAX call to retrieve app_id and id then use them.

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