Execute PHP script if a JavaScript condition is true - javascript

I am running a javascript timer that can be activated by a start button and whenever the count is more than 30 minutes I want it to run an email script so that the email can be send to the intended recipient with the user having to actually send the email manually.Here is the php email code`
<?php
$to = "sa01#gmail.com";
$subject = "Vehicle Monitoring system ";
$message = "<b>Vehicle not logged out</b>";
$header = "From:vehicle001#gmail.com \r\n";
$header .= "Cc:sa001#gmail.com \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$retval = mail ($to,$subject,$message,$header);
if( $retval == true ) {
echo "Message sent successfully...";
}else {
echo "Message could not be sent...";
}
?>`
Here is my javascript code`
var status =0;
var time = 0;
function start() {
status = 1;
document.getElementById("startBtn").disabled = true;
timer();
}
function stop(numberPlate) {
status = 0;
var time = document.getElementById('timerLabel').innerHTML;
var car_no = numberPlate;
var stx = {no : time};
console.log(stx);
window.localStorage.setItem(car_no, time);
}
function reset() {
status = 0;
time = 0;
document.getElementById("startBtn").disabled = false;
document.getElementById("timerLabel").innerHTML = "00:00:00";
}
function timer() {
if (status == 1) {
setTimeout(function() {
time++;
var min = Math.floor(time/100/60);
var sec = Math.floor(time/100);
var mSec = time % 100;
if(min < 10) {
min = "0" + min;
}
if (sec >= 60) {
sec = sec % 60;
}
if (sec < 10) {
sec = "0" + sec;
}
document.getElementById("timerLabel").innerHTML = min + ":" + sec + ":"
+ mSec;
timer();
}, 10);
}
}
function output() {
document.getElementById('timerResult').innerHTML =
document.getElementById('timerLabel').innerHTML;
if(timer>=1){
var xhttp = new XMLHttpRequest();
var result;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("Success");
result = xhttp.responseText;
}
};
xhttp.open("GET", "sendmail.php", true);
xhttp.send();
}
`
This is how the table looks like.How do I do that?

You could use XMLHttpRequest() to have the PHP file be requested.
In this example, file.php is accessed if condition is true. The result is stored in the result variable.
if(condition){
var xhttp = new XMLHttpRequest();
var result;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("Success");
result = xhttp.responseText;
}
};
xhttp.open("GET", "file.php", true);
xhttp.send();
}

Related

Send php while loop variables to javascript file

My file.js is calling a php file to fetch from database and return an encoded JSON object so I can put it on a table. Here is the file.js -
url = "backend.php"
xmlhttp.open("GET", url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
myJSONObj = JSON.parse(this.responseText);
for ( i=0;i<myJSON.length;i++)
{
var x = document.getElementById("datatable").rows[i].cells;
x[6].innerHTML =obj[i].age;
}
}
}
And the backend.php file goes -
$sql_stmt= "SELECT * FROM TABLE ";
$result = odbc_exec($conn_id, $sql_stmt);
while ($row = odbc_fetch_array($result)) {
$age=$row['age'];
$ages[] = array('age'=> $age);
}
$myJSON = json_encode($ages);
echo $myJSON;
This works completely fine, but I have to wait for the PHP while loop to finish, which takes too long with large number of entries. I want to be able to return the JSON within the loop, not at the end.
Is there any way I can make the xmlhttp request and keep receiving JSON while the PHP while loop runs, not having to wait for it to finish and then send across all the rows together? Thanks
I think you should use mysql limit
JS:
var hasData = true;
var loop = 0;
while(hasData){
url = "backend.php?page="+loop;
xmlhttp.open("GET", url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
if(this.reponseText != ""){
myJSONObj = JSON.parse(this.responseText);
for ( i=0;i<myJSON.length;i++)
{
var x = document.getElementById("datatable").rows[i].cells;
x[6].innerHTML =obj[i].age;
}
}else{
hasData = false; //if no data retrieved
}//end if
}//end if
}
loop++; //increment loop
}//end while
PHP:
$loop = $_GET['loop'];
if($loop != ""){
$max_output = 10; //how many rows you want to display per query
$starting_row = $max_output * $loop;
// LIMIT 0, 10 = if loop is 0
// LIMIT 10, 10 = if loop is 1
// LIMIT 20, 10 = if loop is 2
$sql_stmt= "SELECT * FROM TABLE LIMIT {$starting_row}, {$max_output}";
$result = odbc_exec($conn_id, $sql_stmt);
if($result){
while ($row = odbc_fetch_array($result)) {
$age=$row['age'];
$ages[] = array('age'=> $age);
}
$myJSON = json_encode($ages);
echo $myJSON;
}else{
exit; //make sure nothing is echoed/print
}
}
{
myJSONObj = JSON.parse(this.responseText);
for ( i=0;i<myJSON.length;i++)
{
var x = document.getElementById("datatable").rows[i].cells;
x[6].innerHTML =obj[i].age;
}
}
}
Hope this helps

Value not found in php

For login i'm passing mail id and password from javascript file and i've checked through console.log that the values are printed. But when i echo both values in php only password is showed not the mail. But i can't find any error.Here i'm pasting the php file.
<?php
require_once('DBconnection.php');
ini_set('display_errors', 1);
ini_set('log_errors', 1);
$datamail = $_GET["mailID"];
$datapass = $_GET["psw"];
//$datamail = isset($_GET["mailID"]) ? $_GET["mailID"] : '';
echo $datamail;
echo $datapass;
$login_query = "SELECT * FROM student_table where mail_id = '$datamail' AND password='$datapass'";
//echo $login_query;
$login_res = $db->query($login_query);
if( $login_res->num_rows == 1 ){
//if( $login_res == true ){
echo "success";
}
else {
//echo $login_res;
echo mysqli_error($db);
exit;
}
$db->close();
?>
Javascrit file Here
function globalLogin() {
checkLogInMail();
//pageEntry();
}
function checkLogInMail() {
var mailET = document.getElementById("mailID");
var mailIdError = document.getElementById("mailIdErr");
mailID = mailET.value;
var regex = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
if (!regex.test(mailID)) {
mailIdError.innerHTML = "Enter a valid Email id";
//loginFlag = 1;
}
else{
checkmailPass();
}
}
function checkmailPass() {
var passET = document.getElementById("psw");
var passError = document.getElementById("pswErr");
psw = passET.value;
console.log(mailID);
console.log(psw);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
console.log(this.readyState);
if(this.readyState == 4 && this.status == 200)
{
console.log(this.status);
var response = xhttp.responseText;
alert(response);
if(!response.localeCompare( "success" )){
document.getElementById("loginErr").innerHTML = "Mail or Password is correct";
//alert("Successfully logged in :)");
//window.location.href = "index.html";
}
else{
document.getElementById("loginErr").innerHTML = response;
}
}
}
xhttp.open("GET", "passwordChecker.php?psw="+psw+"&mailID"+mailID, true);
xhttp.send();
}
you miss = in your get request in mailID
xhttp.open("GET", "passwordChecker.php?psw="+psw+"&mailID="+mailID, true);
You missed an equal sign '=' in your javascript at your mailid parameter.

Count down timer not working with AJAX

I am trying to make a counter with JS. So far I've managed to pull that off, however I now encounter a problem. While using AJAX to retreive the time to count down I can't make it work. It's weird because it works on my original file but not with a php file called by AJAX.
This works fine :
https://jsfiddle.net/6kvp25vv/
I have no idea what the problem is. This is the HTML page :
<button onclick="upgrade('meat_max')" id="up_meat_max">+</button>
When I click on the button, it runs the function inside this js file which creates a GET request on upgrade.php :
function upgrade(building) {
var file = 'upgrade.php?building=' + building;
ajax(file, function(response) {
document.getElementById('construction').innerHTML += response;
})
}
function ajax(file, fn) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
fn(xmlhttp.responseText);
}
};
xmlhttp.open('GET', file, true);
xmlhttp.send();
}
And this is the code from upgrade.php (variables sent to this file with AJAX are not used for the purpose of testing the code) :
<div class="time">Time: <span id="timer">?</span></div>
var hour = 2;
var minute = 46;
var second = 45;
// function to make a counter
function clockIt() {
function clockO(digit) {
if(digit<10) {
return '0';
} else {
return '';
}
}
document.getElementById('timer').textContent = hour + ':' + clockO(minute) + minute + ':' + clockO(second) + second;
if(second>0) {
second -= 1;
} else if(minute>0) {
minute -= 1;
second += 59;
} else if(hour>0) {
hour -= 1;
minute += 59;
}
}
// runs the function every seconds
clockIt();
setInterval(function (){clockIt()}, 1000);
innerHTML does not execute ajax loaded scripts, what I would do in your case is to return a JSON encoded string with the variables that you need and have a function on your main script (the one thats already loaded) with this provided script, that way you already have the function ready and only pass parameters with the ajax response.
You can decode a json string with:
obj = JSON.parse(jsonString);
For example:
Ajax JSON response string:
{"time": {"hour":2, "minute":46, "second": 45}, "html": "<div class=\"time\">Time: <span id=\"timer\"></span></div>"}
Modified upgrade function:
function upgrade(building) {
var file = 'upgrade.php?building=' + building;
ajax(file, function(response) {
obj = JSON.parse(response);
time = obj.time;
document.getElementById('construction').innerHTML += obj.html;
startCountdown(time.hour, time.minute, time.second);
})
}
New function
function startCountdown(hour, minute, second) {
// function to make a counter
function clockIt() {
function clockO(digit) {
if(digit<10) {
return '0';
} else {
return '';
}
}
document.getElementById('timer').textContent = hour + ':' + clockO(minute) + minute + ':' + clockO(second) + second;
if(second>0) {
second -= 1;
} else if(minute>0) {
minute -= 1;
second += 59;
} else if(hour>0) {
hour -= 1;
minute += 59;
}
}
// runs the function every seconds
clockIt();
setInterval(function (){clockIt()}, 1000);
}
My problem was with the method for the countdown timer. When you specify an interval of 1000 milliseconds, you can't count on it being 1000 milliseconds. It's actually as soon as the timer loop gets to it after 1000 milliseconds have passed. Over a period of time, there are going to be some delays. What you want to do, if you want accurate timing, is to store the initial settings and then measure the time from when the countdown was started to the current time. See the code below which bases the timer on the internal clock rather than the interval counter. Once you have the number of seconds, you can easily it convert it to hours, minutes, and seconds by dividing by 3600 for the hours and using division and modulo arithmetic for the minute and second.
See https://www.sitepoint.com/creating-accurate-timers-in-javascript/
How to create an accurate timer in javascript?
<!DOCTYPE html />
<html>
<head>
<meta encoding="UTF-8" />
<title>Testing XMLHttpRequest</title>
<script>
var request;
var button1;
var display1;
var display2;
var display3;
var start;
var counter;
function second() {
display2.value = display2.value + "\r\nreadyState=" + request.readyState + " status=" + request.status + "\r\n";;
if (request.readyState == 4 && request.status == 200) {
display1.value = display1.value + request.responseText + "\r\n";
}
}
function first() {
display2.value = display2.value + "\r\n" +
"Starting page \r\n";
request = new XMLHttpRequest();
request.onreadystatechange = second;
var file = "http://localhost:80/";
request.open('GET', file, true);
request.send();
setInterval(timed, 1000);
}
function starter() {
display1 = document.getElementById("display1");
display2 = document.getElementById("display2");
display3 = document.getElementById("display3");
button1 = document.getElementById("button1");
button1.onclick = first;
start = new Date();
counter = 60;
}
function timed() {
var duration = (start.getTime() - new Date().getTime()) / 1000.0;
display3.value = (duration + counter).toFixed(0);
}
window.onload = starter;
</script>
</head>
<body>
<form>
<p>
<input type="button" id="button1" value="Start" />Timer:
<input type="text" readonly="readonly" id="display3" />
</p>
<p>Status:
<textarea rows="5" cols="30" id="display2"></textarea>
</p>
<p>Response:
<textarea rows="60" cols="80" id="display1"></textarea>
</p>
</form>
</body>
</html>
Found a way to compensate the delays, using the original version :
function upgrade(building) {
var file = 'upgrade.php?building=' + building;
ajax(file, function(response) {
var obj = JSON.parse(response);
var time = obj.time;
document.getElementById('construction').innerHTML += obj.html;
run_clockIt(time.hour, time.minute, time.second);
})
}
// general AJAX launcher
function ajax(file, fn) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
fn(xmlhttp.responseText);
}
};
xmlhttp.open('GET', file, true);
xmlhttp.send();
}
// count down timer with adjustments to compensate delay
function clockIt(hour, minute, second, finished, nbOfLoop) {
// every 5 seconds, run a delay correction
if(nbOfLoop%5 == 0) {
var actualTimeLeft = adjustClock(finished);
minute = actualTimeLeft[0];
second = actualTimeLeft[1];
}
nbOfLoop += 1;
// add a string "0" if necessary
function clockO(digit) {
if(digit<10) {
return '0';
} else {
return '';
}
}
document.getElementById('timer').textContent = hour + ':' + clockO(minute) + minute + ':' + clockO(second) + second;
// update displayed timer
if(second>0) {
second -= 1;
} else if(minute>0) {
minute -= 1;
second += 59;
} else if(hour>0) {
hour -= 1;
minute += 59;
}
// waits 1 sec before launching the next one
setTimeout(function() {
clockIt(hour, minute, second, finished, nbOfLoop);
}, 1000);
}
// runs the function for the first time
function run_clockIt(hour, minute, second) {
var finished = new Date();
finished.setUTCHours(finished.getUTCHours() + hour);
finished.setUTCMinutes(finished.getUTCMinutes() + minute);
finished.setUTCSeconds(finished.getUTCSeconds() + second);
clockIt(hour, minute, second, finished, 1);
}
function adjustClock(finished) {
var now = new Date();
var diff = new Date(Math.abs(now - finished));
return [diff.getUTCMinutes(), diff.getUTCSeconds()];
}
This way, the count down timer is smooth, no lagging and most of all you can define the interval on which the adjust function will run and correct the timer.
This is the php file, preparing the JSON object (thanks #Miguel) :
<?php
header('Content-Type: application/json');
// retreive variables from AJAX call
$building = $_REQUEST['building'];
// processing variable with database...
// prepare JSON object
$jsonData = '
{
"time":{"hour":2, "minute":46, "second": 45},
"html": "<div class=\"time\">Time: <span id=\"timer\"></span></div>"
}
';
echo $jsonData;

How to update jQuery-UI progress bar with AJAXcall (files scan)

I want to hash all the files in a specific folder with AJAX and update the progress, meaning I don't want the AJAX to stop at the first reply. I searched online and I thing I found the right answer but it doesn't work.
My jQuery( mixed js):
jQuery(document).ready(function($) {
$('#progress').progressbar();
document.getElementById('save').onclick = function() {
var div = document.getElementById('save_log');
var security = $('#save_security').val();
div.innerHTML = '';
xhr = new XMLHttpRequest();
xhr.open("POST", checkit.admin_ajax, false);
xhr.onprogress = function(evt) {
//var json = JSON.parse(e.currentTarget.responseText);
//var percentComplete = ( json.currentFile * 100 ) / json.filesCount;
var progress = evt.currentTarget.responseText;
$('#progress').progressbar("value", progress);
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
console.log(xhr);
}
}
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send("action=checkit_scan_files&security=" + security);
};
});
and my php AJAX
$iterator = new RecursiveDirectoryIterator($dir);
$iterator->setFlags(RecursiveDirectoryIterator::SKIP_DOTS);
$fi = new RecursiveIteratorIterator( $iterator );
$files = array();
$i = 1;
$size = $this->get_files_count();
foreach ($fi as $file) {
if ( !$file->isDir() ) {
$files[$i]['md5'] = md5_file( $file->getPathname() );
$files[$i]['path'] = $file->getPathname();
$progress = ($i * 100) / $size;
$i++;
echo intval( $progress );
}
}

Submit the form when on browser reload/add new tab

Just got some codes from worldofwebcraft.com for my project examination system.I only know PHP,and I actually have no idea on javascripts because our teacher hasnt taught us yet. Please help me on how do I submit the form automatically when the user reloads the page or when he/she opens a new tab.
heres the codes:
<?php if(isset($_GET['question'])){
$question = preg_replace('/[^0-9]/', "", $_GET['question']);
$next = $question + 1;
$prev = $question - 1; ?>
<script type="text/javascript">
function countDown(secs,elem) {
var element = document.getElementById(elem);
element.innerHTML = "You have "+secs+" seconds remaining.";
if(secs < 1) {
var xhr = new XMLHttpRequest();
var url = "userAnswers.php";
var vars = "radio=0"+"&qid="+<?php echo $question; ?>;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert("You did not answer the question in the allotted time. It will be marked as incorrect.");
clearTimeout(timer);
}
}
xhr.send(vars);
document.getElementById('counter_status').innerHTML = "";
document.getElementById('btnSpan').innerHTML = '<h2>Times Up!</h2>';
document.getElementById('btnSpan').innerHTML += 'Click here now';
}
secs--;
var timer = setTimeout('countDown('+secs+',"'+elem+'")',1000);
}
</script>
<script>
function getQuestion(){
var hr = new XMLHttpRequest();
hr.onreadystatechange = function(){
if (hr.readyState==4 && hr.status==200){
var response = hr.responseText.split("|");
if(response[0] == "finished"){
document.getElementById('status').innerHTML = response[1];
}
var nums = hr.responseText.split(",");
document.getElementById('question').innerHTML = nums[0];
document.getElementById('answers').innerHTML = nums[1];
document.getElementById('answers').innerHTML += nums[2];
}
}
hr.open("GET", "questions.php?question=" + <?php echo $question; ?>, true);
hr.send();
}
function x() {
var rads = document.getElementsByName("rads");
for ( var i = 0; i < rads.length; i++ ) {
if ( rads[i].checked ){
var val = rads[i].value;
return val;
}
}
}
function post_answer(){
var p = new XMLHttpRequest();
var id = document.getElementById('qid').value;
var url = "userAnswers.php";
var vars = "qid="+id+"&radio="+x();
p.open("POST", url, true);
p.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
p.onreadystatechange = function() {
if(p.readyState == 4 && p.status == 200) {
document.getElementById("status").innerHTML = '';
alert("Your answer was submitted.");
var url = 'exam.php?question=<?php echo $next; ?>';
window.location = url;
}
}
p.send(vars);
document.getElementById("status").innerHTML = "processing...";
}
</script>
<script>
window.oncontextmenu = function(){
return false;
}
document.onkeydown = function() {
if(event.keyCode == 116) {
event.returnValue = false;
event.keyCode = 0;
return false;
}
}
</script>
I would do something like :
window.onbeforeunload = function() {
post_answer();
}
If post_answer() is your "submit the form"-handler. Cannot tell exactly from the code.

Categories

Resources