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
Related
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.
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
I have a web page that allows users to complete quizzes. These quizzes use JavaScript to populate original questions each time it is run.
Disclaimer: JS Noob alert.
After the questions are completed, the user is given a final score via this function:
function CheckFinished(){
var FB = '';
var AllDone = true;
for (var QNum=0; QNum<State.length; QNum++){
if (State[QNum] != null){
if (State[QNum][0] < 0){
AllDone = false;
}
}
}
if (AllDone == true){
//Report final score and submit if necessary
NewScore();
CalculateOverallScore();
CalculateGrade();
FB = YourScoreIs + ' ' + RealScore + '%. (' + Grade + ')';
if (ShowCorrectFirstTime == true){
var CFT = 0;
for (QNum=0; QNum<State.length; QNum++){
if (State[QNum] != null){
if (State[QNum][0] >= 1){
CFT++;
}
}
}
FB += '<br />' + CorrectFirstTime + ' ' + CFT + '/' + QsToShow;
}
All the Javascript here is pre-coded so I am trying my best to hack it. I am however struggling to work out how to pass the variable RealScore to a MySql database via PHP.
There are similar questions here on stackoverflow but none seem to help me.
By the looks of it AJAX seems to hold the answer, but how do I implement this into my JS code?
RealScore is only given a value after the quiz is complete, so my question is how do I go about posting this value to php, and beyond to update a field for a particular user in my database on completion of the quiz?
Thank you in advance for any help, and if you require any more info just let me know!
Storing data using AJAX (without JQuery)
What you are trying to do can pose a series of security vulnerabilities, it is important that you research ways to control and catch these if you care about your web application's security. These security flaws are outside the scope of this tutorial.
Requirements:
You will need your MySQL database table to have the fields "username" and "score"
What we are doing is writing two scripts, one in PHP and one in JavaScript (JS). The JS script will define a function that you can use to call the PHP script dynamically, and then react according to it's response.
The PHP script simply attempts to insert data into the database via $_POST.
To send the data to the database via AJAX, you need to call the Ajax() function, and the following is the usage of the funciton:
// JavaScript variable declarations
myUsername = "ReeceComo123";
myScriptLocation = "scripts/ajax.php";
myOutputLocation = getElementById("htmlObject");
// Call the function
Ajax(myOutputLocation, myScriptLocation, myUsername, RealScore);
So, without further ado...
JavaScript file:
/**
* outputLocation - any HTML object that can hold innerHTML (span, div, p)
* PHPScript - the URL of the PHP Ajax script
* username & score - the respective variables
*/
function Ajax(outputLocation, PHPScript, username, score) {
// Define AJAX Request
var ajaxReq = new XMLHttpRequest();
// Define how AJAX handles the response
ajaxReq.onreadystatechange=function(){
if (ajaxReq.readyState==4 && xml.status==200) {
// Send the response to the object outputLocation
document.getElementById(outputLocation).innerHTML = ajaxReq.responseText;
}
};
// Send Data to PHP script
ajaxReq.open("POST",PHPScript,true);
ajaxReq.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajaxReq.send("username="username);
ajaxReq.send("score="score);
}
PHP file (you will need to fill in the MYSQL login data):
<?php
// MYSQL login data
DEFINE(MYSQL_host, 'localhost');
DEFINE(MYSQL_db, 'myDatabase');
DEFINE(MYSQL_user, 'mySQLuser');
DEFINE(MYSQL_pass, 'password123');
// If data in ajax request exists
if(isset($_POST["username"]) && isset($_POST["score"])) {
// Set data
$myUsername = $_POST["username"];
$myScore = intval($_POST["score"]);
} else
// Or else kill the script
die('Invalid AJAX request.');
// Set up the MySQL connection
$con = mysqli_connect(MYSQL_host,MYSQL_user,MYSQL_pass,MYSQL_db);
// Kill the page if no connection could be made
if (!$con) die('Could not connect: ' . mysqli_error($con));
// Prepare the SQL Query
$sql_query="INSERT INTO ".TABLE_NAME." (username, score)";
$sql_query.="VALUES ($myUsername, $myScore);";
// Run the Query
if(mysqli_query($con,$sql))
echo "Score Saved!"; // Return 0 if true
else
echo "Error Saving Score!"; // Return 1 if false
mysqli_close($con);
?>
I use these function for ajax without JQuery its just a javascript function doesnt work in IE6 or below. call this function with the right parameters and it should work.
//div = the div id where feedback will be displayed via echo.
//url = the location of your php script
//score = your score.
function Ajax(div, URL, score){
var xml = new XMLHttpRequest(); //sets xmlrequest
xml.onreadystatechange=function(){
if (xml.readyState==4 && xml.status==200){
document.getElementById(div).innerHTML=xml.responseText;//sets div
}
};
xml.open("POST",URL,true); //sets php url
xml.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xml.send("score="score); //sends data via post
}
//Your PHP-script needs this.
$score = $_POST["score"]; //obtains score from POST.
//save your score here
echo "score saved"; //this will be displayed in the div set for feedback.
so call the javascript function with the right inputs, a div id, the url to your php script and the score. Then it will send the data to the back end, and you can send back some feedback to the user via echo.
Call simple a Script with the parameter score.
"savescore.php?score=" + RealScore
in PHP Side you save it
$score = isset ($_GET['score']) ? (int)$_GET['score'] : 0;
$db->Query('INSERT INTO ... ' . $score . ' ...');
You could call the URL via Ajax or hidden Iframe.
Example for Ajax
var request = $.ajax({
url: "/savescore.php?score=" + RealScore,
type: "GET"
});
request.done(function(msg) {
alert("Save successfull");
});
request.fail(function(jqXHR, textStatus) {
alert("Error on Saving");
});
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.
I'm using some jQuery to display tweets but once the Twitter API limit is reached, the request is sent but just keeps loading and loading. This doesn't look good. I want to be able to determine if the request is taking too long and then obviously do stuff, like cancel the request, change the styling, etc.
So this is the code that sends the request:
var fileref = document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", "http://search.twitter.com/search.json?q="+buildString+"&callback=TweetTick&rpp=50");
document.getElementsByTagName("head")[0].appendChild(fileref);
And this is the TweetTick function:
function TweetTick(ob)
{
var container=$('#tweet-container');
container.html('');
$(ob.results).each(function(el){
/* in here, a div is built for each tweet and then appended to container */
});
container.jScrollPane(); /* just adds the scrollbar */
}
You need to cache twitter api response on your server side.
How do I keep from running into the rate limit?
I had a very similar problem lately. I use this script by Remy Sharp for most of my twitter requests: http://remysharp.com/2007/05/18/add-twitter-to-your-blog-step-by-step/
What you need to realise is that the api timeout is per IP address. So if the api has timed out for you based on your testing, it won't have timed out for someone else on a different IP address. Now, if someone accessing the site is doing so within a corporation or business, and others in the same place are doing the same, that timeout will occur almost instantaneously.
To get around this you need to cache your results. The way I did this was as follows.
I created a twitter caching system using the following code:
$twitter_username = "tadywankenobi"; //
$number_of_tweets = "10";
$options[CURLOPT_URL] = 'http://api.twitter.com/1/statuses/user_timeline.xml?screen_name='.$twitter_username.'&count='.$number_of_tweets.'&include_rts=1';
$options[CURLOPT_PORT] = 80;
$options[CURLOPT_FOLLOWLOCATION] = true;
$options[CURLOPT_RETURNTRANSFER] = true;
$options[CURLOPT_TIMEOUT] = 60;
$tweets = cache($options);
$twxml = new SimpleXMLElement($tweets);
echo "<ul>";
for($i=0;$i<=($number_of_tweets-1);$i++){
$text = $twxml->status[$i]->text;
echo "<li>".auto_link_twitter($text)."</li>";
}
echo "</ul>";
function cache($options) {
$cache_filename = "/var/cache/tweets.xml";
if(!file_exists($cache_filename)){
$handle = fopen($cache_filename, 'w') or die('Cannot open file: '.$my_file);
fclose($handle);
}// Check if cache file exists and if not, create it
$time_expire = filectime($cache_filename) + 60*60; // Expire Time (1 hour) // Comment for first run
// Set time to check file against
if(filectime($cache_filename) >= $time_expire || filesize($cache_filename) == 0) {
// File is too old or empty, refresh cache
$curl = curl_init();
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
curl_close($curl);
if($response){
file_put_contents($cache_filename, $response);
}
else{
unlink($cache_filename);
}
}else{
$response = file_get_contents($cache_filename);
}
return $response;
}
What the cache function at the end does is create a file on the server and stores the twitter xml feedback in there. The system then checks to see the age of that file and if it's younger than an hour old, it takes its results from there. Otherwise, it re-accesses twitter. You need to have the file writable in the /var/cache folder (create it if it's not there).
I've kinda hacked this code together a bit, so let me know if you run into any issues with it. It also uses an auto_link_twitter() function, which creates the links required within the twitter text. I didn't write that, so I'll try and find you a link to it now.
Hope that all helps,
T
UPDATE: I can't remember where I got the auto_link_twitter() function, so here it is. If the person who wrote it reads this post, my apologies, I couldn't find the source again.
function auto_link_twitter($text) {
// properly formatted URLs
$urls = "/(((http[s]?:\/\/)|(www\.))?(([a-z][-a-z0-9]+\.)?[a-z][-a-z0-9]+\.[a-z]+(\.[a-z]{2,2})?)\/?[a-z0-9._\/~#&=;%+?-]+[a-z0-9\/#=?]{1,1})/is";
$text = preg_replace($urls, " <a href='$1'>$1</a>", $text);
// URLs without protocols
$text = preg_replace("/href=\"www/", "href=\"http://www", $text);
// Twitter usernames
$twitter = "/#([A-Za-z0-9_]+)/is";
$text = preg_replace ($twitter, " <a href='http://twitter.com/$1'>#$1</a>", $text);
// Twitter hashtags
$hashtag = "/#([A-Aa-z0-9_-]+)/is";
$text = preg_replace ($hashtag, " <a href='http://twitter.com/#!/search?q=%23$1'>#$1</a>", $text);
return $text;
}
You can use specific jQuery methods to make a JSONP request. There is basic $.ajax method and shorthand method $.getJSON which fits better for you. To control timeout of the request you can use timeout parameter. Request exceeded timeout can be processed using the error callback.
$.ajax(
dataType: 'jsonp',
url: 'http://search.twitter.com/search.json',
data: {
q: buildString,
rpp: 50
},
jsonpCallback: 'TweetTick',
timeout: 30000,
error: function(jqXHR, textStatus, errorThrown) {
if (textStatus == 'timeout') {
alert('timeout exceeded');
}
}
);