Getting data from MySql table with no refresh - javascript

I have a code that counts down and when the countdown reaches 0 I want it to grab data from a MySql table and present it on the page without reloading.
I know my countdown works, but it is when I add the code to get the data from the PHP page it stops working. I know my PHP page works and grabs the correct data and presents it.
Here is the code I am currently using.
Any ideas?
<div id="countmesg"></div>
<div id="checking"></div>
<div id="name-data"></div>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var delay = 10;
function countdown() {
setTimeout(countdown, 1000);
$('#countmesg').html("Auction ends in " + delay + " seconds.");
delay--;
if (delay < 0) {
$('#countmesg').html("Auction ended.");
delay = 0;
}
}
countdown();
});
</script>
<script type="text/javascript">
$(document).ready(function () {
var delay = 2;
function countdown() {
setTimeout(countdown, 100);
$('#checking').html("Checking in " + delay + " seconds.");
delay--;
if (delay < 0) {
$('#checking').html("Checking again....");
var name = 'tom';
$.post('cdown.php', {
name: name
}, function (data) {
$('div#name-data').text(data);
};
delay = 2;
}
}
countdown();
});
</script>
The 3 lines that are supposed to be grabbing the PHP file are:
var name = 'tom';
$.post('cdown.php', {name: name}, function(data) {
$('div#name-data').text(data);
PHP Code:
<?php
require 'connect.php';
$name = 'tom';
$query = mysql_query("
SELECT `users`.`age`
FROM `users`
WHERE `users`.`name` = '" . mysql_real_escape_string(trim($name)) . "'"
);
echo (mysql_num_rows($query) !== 0) ? mysql_result($query, 0, 'age') : 'Name not found';
?>

use $.ajax instead of $.post
$.ajax(//url to php//).done(
function (data) { //data is from the php
//do stuff
}
)

Code you provided (3 lines):
var name = 'tom';
$.post('cdown.php', {name: name}, function(data) {
$('div#name-data').text(data);
It seems like you have an incomplete $.post(...) statement. If you check your Console you should see some Exceptions. What are they?
Update your 3 lines to this:
var name = 'tom';
$.post('cdown.php', {name: name}, function(data) {
$('div#name-data').html(data);
});

Related

Alternative to AJAX setTimeout?

I have a script that uses ajax to retrieve PHP data for video files on my server (godaddy shared hosting), and then play the video file on my php page if it is the highest ranked video, like so:
<script id="source" language="javascript" type="text/javascript">
$(function refreshscreen ()
{
$.ajax({
url: 'screen.php',
data: "",
pass to api.php
dataType: 'json',
success: function(data)
{
var id = data[0];
var name = data[1];
var votes = data[2];
var video = data[3];
var image = data[4];
$('.screen').hide(); $("#video"+id+"").show();
var whichvideo = "thevideo" + id;
var videoplay = document.getElementById(whichvideo);
var killvideo = document.getElementsByClassName('videobg');
var allvideos = document.getElementsByClassName("videobg");
for(var x=0; x < allvideos.length; x++)
{
var allvideosid = document.getElementById(allvideos[x]);
if ($(allvideos[x]).attr("id") == whichvideo) {
allvideos[x].play();
} else {
allvideos[x].pause();
}
}
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(refreshscreen, 5000);
}
});
});
And then the screen.php referenced above:
<?php
$host = "localhost";
$user = "myuserhere";
$pass = "mypasshere";
$databaseName = "mydbnamehere";
$tableName = "mytablenamehere";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$result = mysql_query("SELECT * FROM $tableName ORDER BY votes DESC");
$array = mysql_fetch_row($result);
echo json_encode($array);
?>
This all works fine, and the video switches as it should when a new higher ranked video is voted in, however, periodically, the video will freeze when playing, completely at random. My guess is that we are overloading the server with the setTimeout function of the ajax script, so I am wondering if there is a way I can clean up this script to avoid the freezing, or an alternative method.
Thanks in advance.
I've cleaned up the code:
var currentID = -1;
function refreshscreen() {
$.getJSON('screen.php', data => {
var topID = data[0];
// Schedule the next request
setTimeout(refreshscreen, 5000);
if (topID === currentID) return; // top rated video hasn't changed
$('.screen').hide();
$("#video" + topID).show();
var pauseID = "thevideo" + currentID;
var playID = "thevideo" + topID;
$(".videobg").each(function() {
if (this.id === pauseID) this.pause();
if (this.id === playID) this.play();
});
currentID = topID;
});
}
$(document).ready(function () {
refreshscreen();
});
The biggest change is keeping track of the currently playing video and exiting right away if it hasn't changed. Other than that I got rid of all the unused variables and used jQuery throughout. This should be much easier to debug at the least and might fix the error to boot.

Wordpress Modification To A Five-Star Rating Script

I have added custom javascript code to the header.php file of my wordpress site. I have tested this code on a basic html file and it works fine, but I cannot seem to make the vote recording function work on a wordpress post. The other components of the script are working fine (hover, vote display from a .txt file), but I cannot get the function to record the vote working. All files have read/write access.
I would greatly appreciate it if anyone could assist me or point me in the right direction to solve this.
Here is the part of the script that records the vote, I am fairly new to php and was wondering if there is something I can add/replace to modify so the code so it will work properly on Wordpress.
$('.ratings_stars').bind('click', function() {
var star = this;
var widget = $(this).parent();
var clicked_data = {
clicked_on : $(star).attr('class'),
widget_id : $(star).parent().attr('id')
};
$.post(
'http://localhost/url/wordpress/wp-content/ratings.php',
clicked_data,
function(INFO) {
widget.data( 'fsr', INFO );
set_votes(widget);
},
'json'
);
});
});
function set_votes(widget) {
var avg = $(widget).data('fsr').whole_avg;
var votes = $(widget).data('fsr').number_votes;
var exact = $(widget).data('fsr').dec_avg;
window.console && console.log('and now in set_votes, it thinks the fsr is ' + $(widget).data('fsr').number_votes);
$(widget).find('.star_' + avg).prevAll().andSelf().addClass('ratings_vote');
$(widget).find('.star_' + avg).nextAll().removeClass('ratings_vote');
$(widget).find('.total_votes').text( votes + ' votes recorded (' + exact + ' rating)' );
}
Here is a visual example for reference
Thank you for taking time to look at this, if there is any additional information that I can provide please let me know.
Here is the ratings.php that was mentioned in the script that was placed in the header.php.
ratings.php:
<?php
$rating = new ratings($_POST['widget_id']);
isset($_POST['fetch']) ? $rating->get_ratings() : $rating->vote();
class ratings {
var $data_file = 'http://localhost/url/wordpress/wp-content/ratings.data.txt';
private $widget_id;
private $data = array();
function __construct($wid) {
$this->widget_id = $wid;
$all = file_get_contents($this->data_file);
if($all) {
$this->data = unserialize($all);
}
}
public function get_ratings() {
if($this->data[$this->widget_id]) {
echo json_encode($this->data[$this->widget_id]);
}
else {
$data['widget_id'] = $this->widget_id;
$data['number_votes'] = 0;
$data['total_points'] = 0;
$data['dec_avg'] = 0;
$data['whole_avg'] = 0;
echo json_encode($data);
}
}
public function vote() {
preg_match('/star_([1-5]{1})/', $_POST['clicked_on'], $match);
$vote = $match[1];
$ID = $this->widget_id;
if($this->data[$ID]) {
$this->data[$ID]['number_votes'] += 1;
$this->data[$ID]['total_points'] += $vote;
}
else {
$this->data[$ID]['number_votes'] = 1;
$this->data[$ID]['total_points'] = $vote;
}
$this->data[$ID]['dec_avg'] = round( $this->data[$ID]['total_points'] / $this->data[$ID]['number_votes'], 1 );
$this->data[$ID]['whole_avg'] = round( $this->data[$ID]['dec_avg'] );
file_put_contents($this->data_file, serialize($this->data));
$this->get_ratings();
}
}
?>
Here is the complete javascript code added to the header.php, the mouseover/mouseout seem to be working properly, so I think the javascript should be running.
Javascript added to header.php:
<?php wp_head(); ?>
<script type="text/javascript">
$(document).ready(function() {
$('.rate_widget').each(function(i) {
var widget = this;
var out_data = {
widget_id : $(widget).attr('id'),
fetch: 1
};
$.post(
'http://localhost/url/wordpress/wp-content/ratings.php',
out_data,
function(INFO) {
$(widget).data( 'fsr', INFO );
set_votes(widget);
},
'json'
);
});
$('.ratings_stars').hover(
function() {
$(this).prevAll().andSelf().addClass('ratings_over');
$(this).nextAll().removeClass('ratings_vote');
},
function() {
$(this).prevAll().andSelf().removeClass('ratings_over');
set_votes($(this).parent());
}
);
$('.ratings_stars').bind('click', function() {
var star = this;
var widget = $(this).parent();
var clicked_data = {
clicked_on : $(star).attr('class'),
widget_id : $(star).parent().attr('id')
};
$.post(
'http://localhost/url/wordpress/wp-content/ratings.php',
clicked_data,
function(INFO) {
widget.data( 'fsr', INFO );
set_votes(widget);
},
'json'
);
});
});
function set_votes(widget) {
var avg = $(widget).data('fsr').whole_avg;
var votes = $(widget).data('fsr').number_votes;
var exact = $(widget).data('fsr').dec_avg;
window.console && console.log('and now in set_votes, it thinks the fsr is ' + $(widget).data('fsr').number_votes);
$(widget).find('.star_' + avg).prevAll().andSelf().addClass('ratings_vote');
$(widget).find('.star_' + avg).nextAll().removeClass('ratings_vote');
$(widget).find('.total_votes').text( votes + ' votes recorded (' + exact + ' rating)' );
}
</script>
To solve this all I had to do was place my ratings.php file and ratings.data.txt within my wordpress theme folder and link the custom javascript to these files within my header.php file. The javascript now operates properly. This is not the proper way to do this though, ideally I should use the wp_enqueue_scripts hook in the header.php and have the custom css and js in the css/js folders. But for now this temporary fix works and I can continue experimenting.

Cannot get value from PHP variable

I am using JQuery Ajax (and I am sure that things have changed since the last time I used it) but I am having trouble pulling the information from the PHP variable. Basically I am getting the IP address and logging how long it took that IP to load the page fully and then display it.
Here is my code...
getIP.php
<?php
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip = $_SERVER['REMOTE_ADDR'];
}
echo json_encode(array('ip' => $ip));
?>
Event listener that calls it
var IPAddresses = [];
//Anonymous functions - used for quality control and logging
(function() { //Used to test how long it took for a user to connect - uses a php script with it
window.addEventListener("load", function() {
$.ajax({
url: '../php/getIP.php',
type: 'POST',
success: function(result)
{
setTimeout(function alertUser(){IPAddresses.push(result.ip);}, 40);
}
});
}, false);
})();
(function() {
window.addEventListener("load", function() {
setTimeout(function() {
for (var i = 0; i < IPAddresses.length; i++)
{
var timing = performance.timing;
console.log(IPAddresses[i] + " " + timing.loadEventEnd - timing.responseEnd);
}
}, 0);
}, false);
})();
EDIT
Now I don't get errors but it does not seem to print the IP address or push it into the array at all. I am basically trying to get it to [ip] [loadtime] It gives a NaN error
Your output is a string:
echo $ip; //Just to check if it worked - it shows the IP
^---e.g. 127.0.0.1
and then you try to treat it as an array:
setTimeout(function alertUser(){alert(result['ip']);}, 40);
^^^^^^
Since it's not an array, this won't work. try just alert(result).
try to use "json_encode"
echo json_encode(array('ip' => $ip));
and in ajax
success: function(result)
{
setTimeout(function alertUser(){alert(result.ip);}, 40);
}

AJAX - reload page if JSON has changed

I cannot find a suitable way to achieve this:
I have this script
<script type="text/javascript">
function updateSpots() {
$.ajax({
url : '/epark/api/spots/last',
dataType : 'text',
success : function(data) {
var json = $.parseJSON(data);
var currentMessage = json.dateTime;
var idPosto = json.idPosto;
console.log('current '+currentMessage);
console.log('old '+oldMessage);
if(currentMessage != oldMessage){
setTimeout(function(){location.reload();}, 5000);
$('#idPosto').toggle("higlight");
}
oldMessage = currentMessage;
}
});
}
var intervalId = 0;
intervalId = setInterval(updateSpots, 3000);
var oldMessage ="";
</script>
This should check every 3 seconds if the dateTimehas changed on the JSON.
The problem is that I cannot get to go further first step. I mean, when the page loads, oldMessageempty so the if condition is not satisfied. If I could "jump" this first iteration, then everything would go well...
var oldMessage = false;
//...
if (oldMessage && oldMessage !== currentMessage) {
//...

Javascript 'onbeforeunload()' not working with a function call

I have this script below which is used in a survey. The problem I have is, onbeforeunload() works when I don't call a function inside it. If I make any function call(save_survey() or fetch_demographics()) inside it, the browser or the tab closes without any prompt.
<script type="text/javascript">
$(document).ready(function() {
$('#select_message').hide();
startTime = new Date().getTime();
});
loc = 0;
block_size = {{ block_size }};
sid = {{ sid }};
survey = {{ survey|tojson }};
survey_choices = '';
startTime = 0;
demographics_content = {};
function save_survey(sf)
{
var timeSpentMilliseconds = new Date().getTime() - startTime;
var t = timeSpentMilliseconds / 1000 / 60;
var surveydat = '';
if(sf==1)
{ //Success
surveydat = 'sid='+sid+'&dem='+JSON.stringify(demographics_content)+'&loc='+loc+'&t='+t+'&survey_choice='+JSON.stringify(survey_choices);
}
if(sf==0)
{ //Fail
surveydat = 'sid='+sid+'&dem='+json_encode(demographics_content)+'&loc='+loc+'&t='+t+'&survey_choice='+json_encode(survey_choices);
}
//Survey Save Call
$.ajax({
type: 'POST',
url: '/save_surveyresponse/'+sf,
data: surveydat,
beforeSend:function(){
// this is where we append a loading image
$('#survey_holder').html('<div class="loading"><img src="/static/img/loading.gif" alt="Loading..." /></div>');
},
success:function(data){
// successful request; do something with the data
$('#ajax-panel').empty();
$('#survey_holder').html('Success');
alert("Dev Alert: All surveys are over! Saving data now...");
window.location.replace('http://localhost:5000/surveys/thankyou');
},
error:function(){
// failed request; give feedback to user
$('#survey_holder').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
}
function verify_captcha()
{
// alert($('#g-recaptcha-response').html());
}
function block_by_block()
{
var div_content ='<table border="0" cellspacing="10" class="table-condensed"><tr>';
var ii=0;
var block = survey[loc];
var temp_array = block.split("::");
if(loc>=1)
{
var radio_val = $('input[name=block_child'+(loc-1)+']:checked', '#listform').val();
//console.log(radio_val);
if(radio_val!=undefined)
survey_choices += radio_val +'\t';
else
{
alert("Please select one of the choices");
loc--;
return false;
}
}
for(ii=0;ii<block_size;ii++)
{
//Chop the strings and change the div content
div_content+="<td>" + temp_array[ii]+"</td>";
div_content+="<td>" + ' <label class="btn btn-default"><input type="radio" id = "block_child'+loc+'" name="block_child'+loc+'" value="'+temp_array[ii]+'"></label></td>';
div_content+="</tr><tr>";
}
div_content+='<tr><td><input type="button" class="btn" value="Next" onClick="survey_handle()"></td><td>';
div_content+='<input type="button" class="btn" value="Quit" onClick="quit_survey()"></td></tr>';
div_content+="</table></br>";
$("#survey_holder").html(div_content);
//return Success;
}
function updateProgress()
{
var progress = (loc/survey.length)*100;
$('.progress-bar').css('width', progress+'%').attr('aria-valuenow', progress);
$("#active-bar").html(Math.ceil(progress));
}
function survey_handle()
{
if(loc==0)
{
verify_captcha();
$("#message").hide();
//Save the participant data and start showing survey
fetch_demographics();
block_by_block();
updateProgress();
$('#select_message').show();
}
else if(loc<survey.length)
{
block_by_block();
updateProgress();
}
else if(loc == survey.length)
{
//Save your data and show final page
$('#select_message').hide();
survey_choices += $('input[name=block_child'+(loc-1)+']:checked', '#listform').val()+'\t';
//alert(survey_choices);
//Great way to call AJAX
save_survey(1);
}
loc++;
return false;
}
</script>
<script type="text/javascript">
window.onbeforeunload = function() {
var timeSpentMilliseconds = new Date().getTime() - startTime;
var t = timeSpentMilliseconds / 1000 / 60;
//fetch_demographics();
save_survey(0);
return "You have spent "+Math.ceil(t)+ " minute/s on the survey!";
//!!delete last inserted element if not quit
}
</script>
I have checked whether those functions have any problem but they work fine when I call them from different part of the code. Later, I thought it might be because of unreachable function scope but its not the case. I have tried moving the onbeforeunload() at the end of script and the problem still persists. Wondering why this is happening, can anyone enlighten me?
I identified where the problem was. I am using json_encode instead of JSON.stringify and hence it is crashing(which I found and changed already in sf=1 case). That tip with debugger is invaluable. Also, its working fine even without async: false.
Thank you again #AdrianoRepetti!

Categories

Resources