This question already has answers here:
JavaScript post request like a form submit
(32 answers)
How can I submit a form using JavaScript?
(10 answers)
Closed 4 years ago.
I used the Javascript below.
If the time is finished it must redirect to the next page "result.php" by submitting a form. But unfortunately the page displayed is empty.
below my form which must send to the next page "result.php".
I want to have how to send this form and redirect to the next page.
how to send the form with this Javascript to make my page work?
var hoursleft = 3;
var minutesleft = 0;
var secondsleft = 0;
var end1;
var progressBar = document.getElementById('progressBar');
if (localStorage.getItem("end1")) {
end1 = new Date(localStorage.getItem("end1"));
} else {
end1 = new Date();
end1.setMinutes(end1.getMinutes() + minutesleft);
end1.setSeconds(end1.getSeconds() + secondsleft);
end1.setHours(end1.getHours() + hoursleft);
}
progressBar.max = end1 - new Date();
var counter = function() {
var now = new Date();
var diff = end1 - now;
diff = new Date(diff);
var sec = parseInt((diff / 1000) % 60)
var mins = parseInt((diff / (1000 * 60)) % 60)
var hours = parseInt((diff / (1000 * 60 * 60)) % 24);
if (hours < 10) {
hours = "0" + hours;
}
if (mins < 10) {
mins = "0" + mins;
}
if (sec < 10) {
sec = "0" + sec;
}
if (now >= end1) {
clearTimeout(interval);
localStorage.setItem("end", null);
localStorage.removeItem("end1");
localStorage.clear();
if (confirm("TIME UP!"))
window.location.href = "result.php";
//alert("Time finished!");
} else {
progressBar.value = progressBar.max - (end1 - now);
localStorage.setItem("end1", end1);
document.getElementById('hours').innerHTML = "<b>" + hours + "</b> " + ":";
document.getElementById('mins').innerHTML = "<b>" + mins + "</b> " + ":";
document.getElementById('sec').innerHTML = "<b>" + sec + "</b>";
}
}
var interval = setInterval(counter, 1000);
<form class="form-horizontal" role="form" id='question' name="question" method="post" action="result.php">
<?php
$number_question=1;
$limit=10;
$row = mysqli_query( $conn, "select id,question_name,image from testquestion where email = '".$email."' ");
$total = mysqli_num_rows( $row );
$remainder = $total/$number_question;
$i = 0;
$j = 1; $k = 1;
?>
<?php while ( $result = mysqli_fetch_assoc($row) ) {
if ( $i != 0)
echo "<div id='question_splitter_$j'>";
if ( $i == 0)
echo "<div class='cont' id='question_splitter_$j'>";?>
<div id='question<?php echo $k;?>' >
<p class='questions' id="qname<?php echo $j;?>"> <?php echo $k?>.<?php echo $result['question_name'];?>
<input type="checkbox" id="review" name="review" />
<label style="color:#0080ff">Review</label></p>
</br>
<?php echo '<img src="data:image/png;base64,'.($result['image']).'" />'; ?></br><br/><br/>
<input type="text" id="answer<?php echo $result['id'];?>" name="<?php echo $result['id'];?>" placeholder="Enter your answer" />
<br/>
<br/>
</div>
<?php
$i++;
if ( ( $remainder < 1 ) || ( $i == $number_question && $remainder == 1 ) ) {
echo "<button id='".$j."' class='next btn btn-primary' type='submit'>Finish</button>";
echo "</div>";
} elseif ( $total > $number_question ) {
if ( $j == 1 && $i == $number_question ) {
echo "<button id='".$j."' class='next btn btn-primary' type='button'>Next</button>";
echo "</div>";
$i = 0;
$j++;
} elseif ( $k == $total ) {
echo " <button id='".$j."' class='previous btn btn-primary' type='button'>Previous</button>
<a href='review.php'><button id='review.php' class='previous btn btn-primary' type='button'>Review</button></a>
<button id='".$j."' class='next btn btn-primary' type='submit'>Finish</button>";
echo "</div>";
$i = 0;
$j++;
} elseif ( $j > 1 && $i == $number_question ) {
echo "<button id='".$j."' class='previous btn btn-primary' type='button'>Previous</button>
<button id='".$j."' class='next btn btn-primary' type='button' >Next</button>";
echo "</div>";
$i = 0;
$j++;
}
}
$k++;
}
?>
<br/>
<br/>
<br/>
</form>
You have to use document.getElementById('question').submit(); with window.location.href = "result.php"; the POST data isnt posted
I have this code which works very well. But I wanted use mysql.
Here is the code that works:
<?php if (date('w') == 2) { { ?>
<script> $(function() {
var times = [
// mysql import start
{'id': '1', 'name': 'Mardi 5H55', 'end': new Date('2017-01-31 05:55:00'),},
{'id': '2', 'name': 'Mardi 8H40', 'end': new Date('2017-01-31 08:40:00'),},
{'id': '3', 'name': 'Mardi 11H30', 'end': new Date('2017-01-31 11:30:00'),},
{'id': '4', 'name': 'Mardi 14H05', 'end': new Date('2017-01-31 14:05:00'),}
// mysql import end
];
// Initialize the table values
$.each(times, function( key, value ) {
$('#mau-mpl').append('<tr><td>'+value.name+'</td><td>Hérault Transports (Ruban Bleu)</td><td>Montpellier</td><td><span id="player-'+value.id+'-expiration" class="label label-primary">Chargement encours...</span></td></tr>');
});
function countdown()
{
var now = new Date();
console.log('updating time');
$.each(times, function( key, value ) {
var left = value.end - now;
var days = Math.floor( left / (1000 * 60 * 60 * 24) );
var hours = Math.floor( (left % (1000 * 60 * 60 * 24) ) / (1000 * 60 * 60) );
var minutes = Math.floor( (left % (1000 * 60 * 60)) / (1000 * 60) );
var seconds = Math.floor( (left % (1000 * 60)) / 1000 );
displayTime = '';
if (days > 0) {
displayTime = + days + " jr ";
}
if (minutes > 0) {
displayTime = displayTime + hours + " H " + minutes + " Mn " + seconds + " Sec ";
}
echo = "Deja parti";
$('#player-'+value.id+'-expiration').text(displayTime)
});
}
timer = setInterval(countdown, 1000);
});</script><?php } } ?>
As you see my data that I want to put is after mysql import start.
I made a php file that fetches data from mysql and I have this result:
{'id': '1', 'name': 'Mardi 5H', 'end': new Date('2017-01-31 05:00:00'),},
{'id': '2', 'name': 'Mardi 6H', 'end': new Date('2017-01-31 06:00:00'),},
{'id': '3', 'name': 'Mardi 7H', 'end': new Date('2017-01-31 07:00:00'),},
The php file is:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "horaires";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
$sql = "SELECT id, jourheure, name, depart, arrivee FROM 2_mardi";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// {'id': '1', 'name': '5H', 'end': new Date('2017-01-31, 05:55:00'),},";
echo "{'id': '" . $row["id"]. "', 'name': '" . $row['name'] ."', 'end': new Date('" . $row["jourheure"]. "" . $row["depart"]. "'),},<br>"; }
} $conn->close();
?>
+---+----------+---------------------+
| 1 | Mardi 5H | 2017-01-31 05:00:00 |
+---+----------+---------------------+
| 2 | Mardi 6H | 2017-01-31 06:00:00 |
+---+----------+---------------------+
| 3 | Mardi 7H | 2017-01-31 07:00:00 |
+---+----------+---------------------+
How do I put the result in javascript variable between "mysql import start" and "mysql import end" ?
You can do this :
var js = <?php echo "{'id': '" . $row["id"]. "', 'name': '" . $row['name'] ."', 'end': new Date('" . $row["jourheure"]. "" . $row["depart"]. "')}"; ?>
But warning, I remove bad characters on your object at the last :
echo "{'id': '" . $row["id"]. "', 'name': '" . $row['name'] ."', 'end': new Date('" . $row["jourheure"]. "" . $row["depart"]. "'),},<br>"; }
---------------------------------------------------------------------------------------------------------------------------------^-^^^^^
You can set var with a lot diferent ways ,ajax,embebed javascript code inside php code...
When you want get a PHP object or var to javascript you need serialized the object to JSON in your php code, then you need set your JSON string and convert this string to a valid javascript object.
JSON is a string like this
"{'propertyname':'stringvalue','property2':true,'property3':null,'property':[...]}"
If now you can parse JSON on javascript code block
index.php
<?php
$result = getData() // your data like you want =>[ multiple objects ]
$resultJSON = json_encode($result); // "[{..},{...}]"
?>
<script>
var jsondata = parse.JSON('<?php echo $resultJSON ?>') ;
</script>
But i think is better slice the html/javascript code from php code, and get vars from ajax for example.
You can use AJAX call to a PHP script to store the data into Javascript variables.
In the following file the AJAX call using JQuery is demonstrated to store the data into Javascript
<?php if (date('w') == 2) { { ?>
<script>
$(function() {
var times = $.ajax({
url: 'api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
return data;
}
});
$.each(times, function(key, value) {
$('#mau-mpl').append('<tr><td>' + value.name + '</td><td>Hérault Transports (Ruban Bleu)</td><td>Montpellier</td><td><span id="player-' + value.id + '-expiration" class="label label-primary">Chargement encours...</span></td></tr>');
});
function countdown() {
var now = new Date();
console.log('updating time');
$.each(times, function(key, value) {
var left = value.end - now;
var days = Math.floor(left / (1000 * 60 * 60 * 24));
var hours = Math.floor((left % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((left % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((left % (1000 * 60)) / 1000);
displayTime = '';
if (days > 0) {
displayTime = +days + " jr ";
}
if (minutes > 0) {
displayTime = displayTime + hours + " H " + minutes + " Mn " + seconds + " Sec ";
}
echo = "Deja parti";
$('#player-' + value.id + '-expiration').text(displayTime)
});
}
timer = setInterval(countdown, 1000);
});
});</script><?php } } ?>
Following is the code which fetches the data from the database.
Let's call this file api.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "horaires";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, jourheure, name, depart, arrivee FROM 2_mardi";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
//storing result into an array
$array = mysql_fetch_row($result);
}
$conn->close();
//encoding the array into JSON
echo json_encode($array);
?>
my salary month start in previous month 26th and ends in this month 25
ie February month is 2016-01-26 to 2016-02-25.
i need the out put as below
$date = '2014-02-27';
echo date('F', strtotime($date)); = "March" //if date > 25 print next month
I believe what you have to do is get the day:
$date = '2014-02-27';
$day = date('d', strtotime($date));
Then see if bigger than 26, increase one month
$month = date('F', strtotime($date));
if($day > 26)
{
$ts = mktime(0, 0, 0, date("n", strtotime($date)) + 1, 1);
$tmpNewDate = date("Y-m-d H:i:s", $ts);
$month = date('F', strtotime($date));
}
echo $month;
Try this one, I have prepared several date inputs :
<?php
$input_date = '2014-2-2';
// $input_date = '2014-2-27';
// $input_date = '2014-12-27';
$date = DateTime::createFromFormat('Y-m-d', $input_date);
$next_month = null;
$year = $date->format('Y');
$next_month = $date->format('m');
if ($date->format('d') >= 26)
$next_month = intval($date->format('m')) + 1;
if ($next_month == 13){
$next_month = 1;
$year = intval($year) + 1;
}
echo "next month = " . $next_month . ", year = " . $year;
?>
Well, I'm making a game, and in my game I have a countdown script in javascript that receives the date when the building upgrade is over, and makes a countdown, and when the countdown ends, executes a script that upgrades the building to the next level.
But just works in google chrome, and in the other browsers appears like that:
Firefox:
Google Chrome
Just the Javascript:
date_default_timezone_set('europe/lisbon');
$datephp = date('Y-m-d H:i:s');
echo'
<script type="text/javascript">
function cdtd() {
var xmas = new Date("' . $factory_date . '");
var now = new Date();
var timeDiff = xmas.getTime() - now.getTime();
if (timeDiff <= 0) {
clearTimeout(timer);
$("#factory_upgrade").load("/include/factory_upgraded.php");
$("#quantidade_fabricas").load("/include/factory_stats.php");
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;' .
"var tempo=('0' + hours).slice(-2)+':'+('0' + minutes).slice(-2)+':'+('0' + seconds).slice(-2);"
.
'
document.getElementById("secsBox").innerHTML = tempo;
var timer = setTimeout("cdtd()",1000);
}
</script>
';
Complete function:
function factory_update($get){
$userid = $_SESSION['userid'];
$query00 = "SELECT * FROM factory_upgrading WHERE userid = '$userid'";
$result00 = mysql_query($query00) or die(mysql_error());
while($row00 = mysql_fetch_array($result00)){
$factory_upgrade = $row00['userid'];
}
if(!isset($factory_upgrade)){
echo "Sem melhoramentos.";
return 0;
}
$query01 = "SELECT * FROM factory_upgrading WHERE userid = '$userid'";
$result01 = mysql_query($query01) or die(mysql_error());
while($row01 = mysql_fetch_array($result01)){
$factory_level = $row01['new_level'];
$factory_date = $row01['upgraded'];
}
if ($get == "load")
{
echo '<div class="message_upgrades" ">';
echo '<div class="loading"><img src="/images/loading.gif"></img></div>';
echo '</div>';}
else
{
date_default_timezone_set('europe/lisbon');
$datephp = date('Y-m-d H:i:s');
echo'
<script type="text/javascript">
function cdtd() {
var xmas = new Date("' . $factory_date . '");
var now = new Date();
var timeDiff = xmas.getTime() - now.getTime();
if (timeDiff <= 0) {
clearTimeout(timer);
$("#factory_upgrade").load("/include/factory_upgraded.php");
$("#quantidade_fabricas").load("/include/factory_stats.php");
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;' .
"var tempo=('0' + hours).slice(-2)+':'+('0' + minutes).slice(-2)+':'+('0' + seconds).slice(-2);"
.
'
document.getElementById("secsBox").innerHTML = tempo;
var timer = setTimeout("cdtd()",1000);
}
</script>
';
echo '<div class="success_upgrades">';
echo '<div class="upgrade_text"><b>Nivel: </b>' . $factory_level . '</div><div class="div_separator"></div><div class="upgrade_text"><b>Duração:</b>
<div class="secsBox" id="secsBox"></div>
<script type="text/javascript">cdtd();</script></div><div class="div_separator"></div>
';
echo '<div id="close" class="stop_upgrade" ></img></div>';
echo '</div>';
echo '<script>
$(".stop_upgrade").click(function (e) {
e.preventDefault();
$(factory_upgrade2).empty();
setTimeout(function(){
$("#factory_upgrade2").load("/include/upgrade_cancel.php");
$("#factory_upgrade").load("/include/factory_update.php");
$("#load").load("/include/cabecalho_content.php");
$("#industrial").fadeIn();
$(loader1).delay(1000).hide(0);
}, 100);
});
</script>
';
}
}
The format of $factory_date is invalid according to standard JavaScript and Chrome happens to be able to parse it.
For better results, stick to these Date constructors:
new Date();
new Date(value);
new Date(dateString);
new Date(year, month [, day, hour, minute, second, millisecond]);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
I have this code for a countdown timer. its basically a combination of PHP/Javascript countdown timer which will gets the $end_date from a Mysql table/field.
The problem is that it will stop automatically (which is unwanted) at a certain time.
For example: I set the $end_date to September 19 2013 11:30:00 AM GMT in mysql database.
the countdown starts and works fine and starts counting down as it should. However, when the countdown timer reaches September 19 2013 13:00:00 PM GMT it will stop and it will show the Times Up message! Basically it will stop working or counting down once the $end_date has been changed to 13:00:00 PM.
I cannot see anything in my code that will cause this issue. apart from this line:
if ($now < $exp_date ) {
?>
but again, this line only tells the script when to start counting and as far i can see it shouldn't stop the countdown timer to stop as long as the timer has not reached the $end_date. or am I missing something?
here is my code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>
<?php date_default_timezone_set('GMT'); ?>
<?php
session_start();
// Run a select query to get my letest 6 items
// Connect to the MySQL database
include "config/connect.php";
$dynamicList = "";
$sql = "SELECT * FROM item ORDER BY id";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query); // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$id = $row["id"];
$product_name = $row["product_name"];
$date_added = date("Y-m-d", strtotime($row["date_added"]));
$end_date = date("F d Y H:i:s A T", strtotime($row["end_date"]));
$price = $row["price"];
$dynamicList .= '<div>' . $end_date . '
</div>';
}
} else {
$dynamicList = "No Records";
}
?>
<?php
$date = $end_date;
$exp_date = strtotime($date);
$now = time();
if ($now < $exp_date ) {
?>
<script>
// Count down milliseconds = server_end - server_now = client_end - client_now
var server_end = <?php echo $exp_date; ?> * 1000;
var server_now = <?php echo time(); ?> * 1000;
var client_now = new Date().getTime();
var end = server_end - server_now + client_now; // this is the real end time
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour *24
var timer;
function showRemaining()
{
var now = new Date();
var distance = end - now;
if (distance < 0 ) {
clearInterval( timer );
document.getElementById('countdown').innerHTML = 'EXPIRED!';
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor( (distance % _day ) / _hour );
var minutes = Math.floor( (distance % _hour) / _minute );
var seconds = Math.floor( (distance % _minute) / _second );
var countdown = document.getElementById('countdown');
countdown.innerHTML = '';
if (days) {
countdown.innerHTML += 'Days: ' + days + '<br />';
}
countdown.innerHTML += 'Hours: ' + hours+ '<br />';
countdown.innerHTML += 'Minutes: ' + minutes+ '<br />';
countdown.innerHTML += 'Seconds: ' + seconds+ '<br />';
}
timer = setInterval(showRemaining, 1000);
</script>
<?php
} else {
echo "Times Up";
}
?>
<div id="countdown"></div>
any help would be greatly appreciated.
13:00:00 PM is not a valid time. AM and PM are used to indicate which side of the 12-hour cycle the time is. You cannot logically say you're on the 13th hour of the 12 hour side of the clock.
EDIT: For clarity: 13:00 == 1 PM, 13:00 PM == nothing.