how do i manipulate a countdown timer using button in php? - javascript

I'm working on a bidding system. I have the timer to read from the database and display a message when it reaches 00:00. Now i want to manipulate the timer in such a way that when it is <= 10secs(00:00:00:10), and a button is clicked then it should reset back to 00:00:00:10 and continue. The timer display is in day, hour, minute, and seconds.
Here is the javascript code
function calcage(secs, num1, num2) {
s = ((Math.floor(secs/num1))%num2).toString();
if (LeadingZero && s.length < 2)
s = "0" + s;
return "<b>" + s + "</b>";
}
function CountBack(secs) {
if (secs < 0) {
document.getElementById("cntdwn").innerHTML = FinishMessage;
return;
}
DisplayStr = DisplayFormat.replace(/%%D%%/g, calcage(secs,86400,100000));
DisplayStr = DisplayStr.replace(/%%H%%/g, calcage(secs,3600,24));
DisplayStr = DisplayStr.replace(/%%M%%/g, calcage(secs,60,60));
DisplayStr = DisplayStr.replace(/%%S%%/g, calcage(secs,1,60));
document.getElementById("cntdwn").innerHTML = DisplayStr;
if (CountActive)
setTimeout("CountBack(" + (secs+CountStepper) + ")", SetTimeOutPeriod);
}
function putspan(backcolor, forecolor) {
document.write("<span id='cntdwn' style='background-color:" + backcolor +
"; color:" + forecolor + "'></span>");
}
if (typeof(BackColor)=="undefined")
BackColor = "white";
if (typeof(ForeColor)=="undefined")
ForeColor= "black";
if (typeof(TargetDate)=="undefined")
TargetDate = "12/31/2020 5:00 AM";
if (typeof(DisplayFormat)=="undefined")
DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds.";
if (typeof(CountActive)=="undefined")
CountActive = true;
if (typeof(FinishMessage)=="undefined")
FinishMessage = "";
if (typeof(CountStepper)!="number")
CountStepper = -1;
if (typeof(LeadingZero)=="undefined")
LeadingZero = true;
CountStepper = Math.ceil(CountStepper);
if (CountStepper == 0)
CountActive = false;
var SetTimeOutPeriod = (Math.abs(CountStepper)-1)*1000 + 990;
putspan(BackColor, ForeColor);
var dthen = new Date(TargetDate);
var dnow = new Date();
if(CountStepper>0)
ddiff = new Date(dnow-dthen);
else
ddiff = new Date(dthen-dnow);
gsecs = Math.floor(ddiff.valueOf()/1000);
CountBack(gsecs);
Here is the php code
<body>
<?php
$mysqli = new mysqli("localhost","root","", "auction");
if (!$mysqli)
{
die('Could not connect: ' . mysql_error());
}
else{
$sql = "INSERT INTO bids (id, description, closing_date) VALUES
(NULL, 'Acer Aspire 4736', '2011-10-22 18:50:26')";
}
$result = $mysqli->query("SELECT * FROM bids WHERE id = 1");
$row = mysqli_num_rows($result);
if ($row == 0)
{
die('No record found.');
}
$row = $result->fetch_array();
echo "Description: " . $row[1] . "<br />";
$closedate = date_format(date_create($row[2]), 'm/d/Y H:i:s');
echo "Closing Date: " . $closedate;
?>
<p>Time Left:
</p>
<script language="JavaScript">
TargetDate = "<?php echo $closedate ?>";
BackColor = "blue";
ForeColor = "navy";
CountActive = true;
CountStepper = -1;
LeadingZero = true;
DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds.";
FinishMessage = "Bidding closed!";
</script>
<script language="JavaScript" src="countdown.js"></script>
</body>
here is the code for the display in html
<?php
$A=0;
if ($A%4 ==0):;?>
<?php
while ($auction=$result->fetch_assoc()):;?>
<div class = "grid ">
<h4 class="c-head"><?=$auction['item_name']?></h4>
<img src='<?=$auction['item_image']?>' class="img-responsive">
<span class="timer">
<script language="JavaScript">
TargetDate = "<?php echo $closedate ?>";
BackColor = "";
ForeColor = "";
CountActive = true;
CountStepper = -1;
LeadingZero = true;
DisplayFormat = "%%D%%, %%H%%:%%M%%:%%S%%";
FinishMessage = "Bidding closed!";
</script>
<script language="JavaScript" src="countdown\countdown.js">
</script>
</span>
<div class="input-group">
<span class="input-group-addon">$</span>
<input type="digit" class="form-control"
name="duration">
<span class="input-group-btn "><button class="btn btn-
primary c-button" type="button" name="bid">Bid now!</button></span>
</div>
</div>
<?php endwhile; $A++; endif;?>
I'm novice in php...just started learning it a couple of weeks ago. Your time is greatly appreciated.

I wroted that to help your start. I haven't currently a dev environment under hands so I didn't run this code,.
All the php files have to be put in the same directory to communicate
This file when required should allow you to communicate with your database. Moreover I used PDO that is good practice when requesting database to avoid SQL injections.
Please check the php documentation http://php.net/manual/fr/class.pdo.php
// database_connection.php
$host = 'localhost';
$user = 'root'; // Bad idea to user root user ^^'
$password = 'yourpassword';
$dbname = 'auction';
try {
$dsn = sprintf('mysql:host=%s;dbname=%s', $host, $dbname);
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION; // I active errors, if you are a beginner that'll help you, comment this in prod env
// I use PDO to avoid SQL injections, this line open a mysql connection, check the documentation
$connection = new PDO($dsn, $user, $password, $pdo_options);
} catch (PDOException $e) {
echo 'Connexion failed : ' . $e->getMessage();
exit;
}
You have to implement a HTML POST form with a description input which will submit to this PHP file
This file handle the creation of a bid
// addBid.php
// You have to implement a HTLM POST form with the needed fields which will submit to this PHP file
// The url yourdomain.fr/addBid.php
require 'database_connection.php';
function redirectTo($url, $statusCode = 301) {
if(!is_int($statusCode)) {
// The error code isnt an integer
throw new \Exception('error code isn\'nt an integer!');
}
if(!in_array($statusCode, [301, 302, 307, 308])) { // 301, 302, 307, 308 are the valid http code for client redirect response
throw new \Exception('invalid error code !');
}
header('Location: ' . $url, true, $statusCode);
exit;
}
$description = isset($_POST['description']) ? $_POST['description'] : null;
$urlListing = 'yourdomain.fr/yourlistingurl';
// The sended description isn't valid
if(empty($description) || !is_string($description)) {
redirectTo($urlListing);
}
// You should do some verification on the string that send the user, it can be malicious html/javascript code, XSS attack
// Start logic update
$inTenMinutes = new \DateTime('+10 minutes'); // I create a datetime object that represent the future in ten minutes
$stringDate = $inTenMinutes->format('Y-m-d H:i:s');
$sql = 'INSERT INTO bids(description, closing_date) VALUES(":description", ":closing_date")';
$statement = $connection->prepare($sql);
$success = $statement->execute([
':closing_date' => $stringDate,
':description' => $description
]);
if(!$success) {
echo 'The sql query didnt work as excepted';
exit;
}
$numberModifiedLines = $statement->rowCount(); // will return 0 or 1, it should return 1 if the bid is created
$urlListing .= '?created=' . $numberModifiedLines;
redirectTo($urlListing); // All its ok, we redirect the browser to the listing page
This third file handle the update of bid that is in the database
// updateBid.php
// The url yourdomain.fr/updateBid.php?bidId=6 will update the bid with id 6 into database
require 'database_connection.php';
function redirectTo($url, $statusCode = 301) {
if(!is_int($statusCode)) {
// The error code isnt an integer
throw new \Exception('error code isn\'nt an integer!');
}
if(!in_array($statusCode, [301, 302, 307, 308])) { // 301, 302, 307, 308 are the valid http code for client redirect response
throw new \Exception('invalid error code !');
}
header('Location: ' . $url, true, $statusCode);
exit;
}
$bidId = isset($_GET['bidId']) ? $_GET['bidId'] : null;
$urlListing = 'yourdomain.fr/yourlistingurl';
// The sended bidId isn't valid
if(empty($bidId) || !is_numeric($bidId)) {
redirectTo($urlListing);
}
// Start logic update
$inTenMinutes = new \DateTime('+10 minutes'); // I create a datetime object that represent the future in ten minutes
$stringDate = $inTenMinutes->format('Y-m-d H:i:s');
$sql = 'UPDATE bids SET closing_date = ":dateToModify" WHERE id = :id';
$statement = $connection->prepare($sql);
$success = $statement->execute([
':closing_date' => $stringDate,
':id' => $bidId
]);
if(!$success) {
echo 'The sql query didnt work as excepted';
exit;
}
$numberModifiedLines = $statement->rowCount(); // will return 0 or 1, it should return 1 if the $bidId is present in database
$urlListing .= '?updated=' . $numberModifiedLines;
redirectTo($urlListing); // All its ok, we redirect the browser to the listing page
You should do some tutorials learn PHP and MYSQL, that'll help you a lot :)
Moreover when you use a PHP framework it is more difficult at the start but after that you'll learn a lot reading code. And the framework help you to stay in the "good practices", it very easy in php to do some shit code.
I hope I didn't so many syntax or logic error but I know that the stackoverflow community will correct me if needed
Sorry for my english !!
An up vote would be greatly appreciated :)

Related

The browser cannot connect to the server in SSE

I am setting up a Server Sent Event connection between my instant messaging page and my sse page in php. But firefox tells me that it could not connect to the server. I followed an article telling me to put in php.ini : output_buffering = Off and zlib.output_compression = Off.
Then I arrived at this result by adding my personal code so that the code does what I want:
client code:
<script type="text/javascript">
var eventSource = new EventSource("includes/load_chat.php");
eventSource.onmessage = function(event) {
document.getElementById("message").innerHTML += event.data;
console.log('messsssage!!!!')
};
</script>
server code :
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
include 'database_message.php';
global $msg_bdd;
$from = '2';
$to = '1';
$id_discution = "ezdhnijkezd&ézuoijde_hjé_àe'dzunbfezd";
// test values
$dmd_last_id_msg = $msg_bdd->prepare('SELECT * FROM message WHERE discution_id = :id ORDER BY creation_date DESC');
$dmd_last_id_msg->execute([
'id' => $id_discution
]);
while($message = $dmd_last_id_msg->fetch()){
$last_msg_date = $message['creation_date'];
$last_msg_id = array($message['id']);
break;
}
while (true) {
if(connection_aborted()) exit();
$dmd_if_new_msg = $msg_bdd->prepare('SELECT * FROM message WHERE discution_id = :id AND creation_date >= :last_creation ORDER BY creation_date');
$dmd_if_new_msg->execute([
'id' => $id_discution,
'last_creation' => $last_msg_date
]);
$data = 'data: ';
echo $data;
while($message = $dmd_if_new_msg->fetch()){
if(in_array($message['id'],$last_msg_id)){}
else{
if($message['user'] == $from){$id_div = "from";}
elseif($message['user'] == $to){$id_div = "to";}
$data = '<div class="message" id="' .$id_div. '"><p>' .$message['message']. '</p></div><br><br><br>';
$data = htmlspecialchars($data);
echo $data;
if ($message['creation_date'] > $last_msg_date) {
$last_msg_date = $message['creation_date'];
$last_msg_id = array($message['id']);
}
elseif($message['creation_date'] = $last_msg_date){
array_push($last_msg_id, $message['id']);
}
}
}
flush();
sleep(1);
}
?>
Where can the problem come from ? client ? server ? What is the problem? Thanks for reading

Creating a PHP session variable after successful AJAX call

I am having problems creating a PHP session following a successful AJAX call. Here is the AJAX code:
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
var id = profile.getId();
var em = profile.getEmail();
var name = profile.getName();
var pic = profile.getImageUrl();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('confirm-login').style.display = 'block';
}
};
xhttp.open("GET", "./assets/inc/profile.php?id="+id+"&e="+em+"&n="+name+"&p="+pic, true);
xhttp.send();
}
This part works perfectly. I only include it for completeness sake.
Here's the contents of profile.php
<?php
$id = $_GET["id"];
$email = $_GET["e"];
$name = $_GET["n"];
$pic = $_GET["p"];
require_once("db.php");
$result = $mysqli->query("SELECT googleid FROM user_tbl WHERE googleid = '$id' LIMIT 1");
if($result->num_rows == 0) {
$sql = "INSERT INTO user_tbl (googleid, email, fullname, pic, loc) VALUES ('$id', '$email', '$name', '$pic', '')";
if (mysqli_query($mysqli, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "" . mysqli_error($mysqli);
}
} else {
echo "already exists";
}
$mysqli->close();
session_start();
$_SESSION['gid'] = $id;
?>
All of this code works except for session_start(); and $_SESSION['gid'] = $id; when I return to another PHP page (which correctly has session_start(); at the very top of the page) the variable has not been created in profile.php
Any help as to what I'm doing wrong would be much appreicated.
You can't start a session after the script has sent output. (There should have been output to that effect; if there wasn't, try changing PHP's warnings.) The session_start() call must come before any echo call that is actually executed.
On an unrelated topic, you will want to learn how to escape your database parameters.

Unable to send data from JavaScript to PHP file using ajax

I'm unable to retrieve the q parameter sent from the PHP.
When I run my code, null values get inserted in my database.
Here are the concerning parts of my code:
My JavaScript function:
function load_now(str){
//alert(str);
var id = str.split("+")[0];
var r = confirm("Start load process for scooter " + str + "?");
if (r == true) {
var xmlhttp = new XMLHttpRequest();
//console.log(str);
xmlhttp.open("GET", "load_scooter_action.php?q=" + str, true);
xmlhttp.send();
}
}
and my load_scooter_action.php file:
<?php
require "checkUserModel.php";
require "databaseController.php";
$databaseController = new DatabaseController();
$databaseController->startConnexionToDatabase();
$conn = $databaseController->getConn();
$dateObject = new DateTime();
$startTime = $dateObject->format('Y-m-d H:i:s');
$user = $_SESSION['user-id'];
// get the q parameter from URL
$q = $_REQUEST["q"];
//forme:(scooter, lat, lng, chg);
$val = explode("+",$q);
$scooter = val[0];
$lat = val[1];
$lng = val[2];
$chg = val[3];
echo "<script type='text/javascript'> console.log(".$q.")</script>";
$sql = "UPDATE `scooters` SET `disponible` = '0' WHERE `scooters`.`numero` = '$scooter';";
if ($conn->query($sql) === TRUE) {
$add = "\nScooter Taken";
} else {
$add = "Error Taking scooter" . $conn->error;
}
$sql = "
INSERT
INTO Reloads(scooter, user, initialLoad, finalLoad, sourceX, sourceY,destinationX, destinationY, startTime,endTime)
VALUES ('$scooter','$user','$chg',null,'$lat','$lng',null ,null, '$startTime', null)";
if ($conn->query($sql) === TRUE) {
//echo "\nNew record created successfully";
//echo '<script>window.location.href = "../php/scooterMapIndex.php";</script>';
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Could you help me have a clear understanding of my mistake?
Thanks in advance.
EDIT
str is has the following form 599+50.8037+4.32782+4
Two mistakes:
The first one is a quick fix. Replace val with $val
The second one is that, although str is of the form 599+50.8037+4.32782+4 in the .js file, $q gets retrieved without the + characters in the .php file. Therefore it has to be split appropriately.
Can you show me that what is passed in str or which value is passed in str load_now function. Do you get value when you alert(str)?
If yes then try below function
$.ajax({
type: 'GET',
url: 'follow_user.php?user_id='.urlencode($user_id),
success: function(data) {
alert('done');
}
});
Thanks

how to check whether request is made or not

i am using contenteditable property in p tag .. the code is
<p contenteditable="true" id="Option1_<?php echo $i ?>" style="width:98%;border:4px thin black; background-color:#D6D6D6;font-size:18px;color:black;padding:3px "><?php echo ' '.'A.'.' &nbsp'.$question1['Option1'];?></p>
<p contenteditable="true" id="Option2_<?php echo $i ?>" style="width:98%;border:4px thin black; background-color:#D6D6D6;font-size:18px;color:black;padding:3px "><?php echo ' '.'B.'.' &nbsp'.$question1['Option2'];?></P>
and jquery to make a request to make request
document).ready(function(){
$("p[contenteditable=true]").blur(function(){
var msg = $(".alert");
var newvalue = $(this).text();
var field = $(this).attr("id");
$.post("ajax.php",field+"="+newvalue,function(d){
var data = JSON.parse(d);
msg.removeClass("hide");
if(data.status == '200'){
msg.addClass("alert-success").removeClass("alert-danger");
}else{
msg.addClass("alert-danger").removeClass("alert-success");
}
msg.text(data.response);
setTimeout(function(){msg.addClass("hide");},3000);//It will add hide class after 3 seconds
});
});
});
and then php to update my mysql database on receiving the request
<?php
$response = NULL;
$status = http_response_code(406);
if(!empty($_POST)){
session_start();
$mock_test_name=$_SESSION['mock_test_name'];
$num_of_sections = $_SESSION['num_of_sections'];
$school_name = $_SESSION['school_name'];
$class_name = $_SESSION['class_name'];
$section_name = $_SESSION['section_name'];
$con = mysqli_connect("localhost","root","","onlinetest");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
$table_space = "$school_name $class_name $section_name $mock_test_name";
$table = str_replace(" ", "_", $table_space);
$table_space1 = "$school_name $class_name $section_name";
$table1 = str_replace(" ", "_", $table_space1);
$table_space2 = "$table1 $table";
$table2 = str_replace(" ", "_", $table_space2);
$table2 = strtolower($table2);
foreach($_POST as $key=>$value){
$key = strip_tags(trim($key));
$value = strip_tags(trim($value));
$explode = explode("_",$key);
$user_id = $explode[1];
$field_name = $explode[0];
if(isset($user_id)){
$update = false;
$selectData = mysqli_query($con,"SELECT " + $field_name + " FROM " + $table2 + " WHERE question_id='" + $user_id + "'"); //Selecting data from MySql
$result = mysqli_fetch_assoc($selectData); //Fetching Data
if($result[$field_name]!==$value){ //Checking if the Value is modified
$update = mysqli_query($con,"UPDATE" + $table2+ "SET" + $field_name+"="+$value+ "WHERE question_id='"+$user_id+"'"); //Updating MySQL if value is Modifie
}
//Update the users Table
if($update){
$response = "User Details Updated";
http_response_code(200); //Setting HTTP Code to 200 i.e OK
}else{
$response = "Not Modified";
http_response_code(304); //Setting HTTP Code to 304 i.e Not Modified
}
}else{
$response = "Not Acceptable";
}
}
}
echo json_encode(array(
"status"=>$status,
"response"=>$response
));
?>
But i think the request is not made properly as the database is not getting updated.. Please tell me how to check if a request has been made... or am i making error somewhere in writing code ??
Your mysqli_query function is formed incorrectly. You have to escape out of the parentheses in order to drop in variables.
You need to do something like
mysqli_connect($con, "SELECT " + var1 + " FROM " + var2);
or you'll end up making a query for
EDIT:
For a more apt example, the line
$selectData = mysqli_query($con,"SELECT $field_name FROM $table2 WHERE question_id='$user_id'");
should be
$selectData = mysqli_query($con,"SELECT " + $field_name + " FROM " + $table2 + " WHERE question_id='" + $user_id + "'");
You'll notice the main difference, especially in coloring between the two, signifying that in the first one, the variables $field_name, $table2, and $user_id are all being interpreted as part of the query. You don't want the NAME of the variable, you want the VALUE of it instead, so you need to concatenate the strings together.
This is just one of the multiple similar fixes you'll need to do for your multiple queries. Every place the editor is marking the thing you're trying to use as a variable as part of the string, take the same steps to concat the strings.
You need to change your code like this,
ajax code
$.ajax({
type:"post",
url:"ajax.php",
data: "your data",
success:function(d){
console.log(d);
}
});
php code:
$table_space = $school_name." ".$class_name." ".$section_name." ".$mock_test_name;
$table = str_replace(" ", "_", $table_space);
$table_space1 = $school_name." ".$class_name." ".$section_name;
$table1 = str_replace(" ", "_", $table_space1);
$table_space2 = $table1." ".$table;
$table2 = str_replace(" ", "_", $table_space2);
$table2 = strtolower($table2);

Getting javascript response from a PHP login function

public function login($username,$password) {
$linkingcon = $this->getConnection();
$sqlquery = "SELECT ac.userID,ac.name,us.usertype FROM users us JOIN accounts ac ON us.userID = ac.userID WHERE us.username='$username' AND us.password='$password';";
$result = mysql_query($sqlquery , $linkingcon);
$this->throwMySQLExceptionOnError($linkingcon);
$row = mysql_fetch_array($result);
$survey = new stdClass();
if($row) {
$res->userID = (int)$row['userID'];
$res->name = $row['name'];
$res->usertype = (int)$row['usertype'];
$string = rand() . 'SurveyLand' . rand() . $username. $password;
$_SESSION['SURVEYLAND_KEY'] = md5($string);
} else {
$res = false;
}
return $res;
}
Hi everyone,
im in a spot of bother regarding a conversion, I need to get a Javascript response from the above php function by calling that php function from another script(HTML)...
P.S
i saw an example in the internet like the below, cant i use method like below get the call
client.sendRequest('hello', null, { 'async': false }, function(rtn) {
if (rtn.isError())
document.write('<li>Request hello error: ' + rtn.getErrorMessage() + "</li>");
else
document.write('<li>Request hello result: ' + rtn.getResult() + "</li>");
});
If you are using ajax return response in json format
return json_encode($res);
Or just print response in script tag
<script>
var res = <?php echo json_encode(login('username','password')); ?>
</script>

Categories