To print Random no in Php each second - php

I want to generate random no in php per second and want to display that after clicking the generate button. Below is the code for same
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>Random no Generator</title>
<meta content="text/html; charset=utf-8" http-equiv="content-type" />
</head>
<?php
if(isset($_GET['action'])=='submitfunc') {
submitfunc();
}else
//show form
?>
<body>
<form action="?action=submitfunc" method="post"> <p>
<input type="submit" value="Generate" /></p>
<p>
</form>
</body>
<?php
function submitfunc() {
while(1){
echo rand (5,10)."\n";
sleep(1);
echo rand (25,50)."\n";
sleep(1);
}
}
?>
</html>
Edit:
I want to insert no in database perodicaly so need this to work via php

As said, PHP is a server-side scripting language. This Fiddle may help.
<button id="gen">Generate</button>
<br/>
<div id="content">
</div>
<script type="text/javascript">
var int1 = null;
var int2 = null;
var br = $('<br/>');
$("#gen").on('click', function(){
int1 = setInterval(function(){
var span = $('<span/>').text(~~(Math.random()*5+5));
$("#content").append(span).append($('<br/>'));
},2000);
setTimeout(function(){
int2 = setInterval(function(){
var span = $('<span/>').text(~~(Math.random()*25+25));
$("#content").append(span).append($('<br/>'));
},2000);
},1000);
});
</script>

Related

Using Jquery .each function in a PHP foreach loop

I am quite new to jquery, and i couldn't use .each function in a php foreach function.
I am trying to do a quantity, unit price, total price table.
I don't know how many table rows does user need, therefore used foreach function. Here is an example what i am trying to do:
my deneme2.php file :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width= <script type="text/javascript">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>deneme5.js</script>
</head>
<body>
<?php
$arr=[1,2];
foreach ($arr as $key=>$val){ ?>
<div>
<input id="tst1"; type="text"; >
<input id="tst2"; type="text"; >
<input id="tst3"; type="text"; > <br><br>
</div>
<?php } ?>
<input id="asd"; type="submit"; value="hesapla">
</body>
</html>
And my deneme5.js file:
$(function(){
$("#asd").click(function(){
$("div").each(function(index){
var a=$("#tst1").val();
var b=$("#tst2").val();
var c= parseInt(a)*parseInt(b);
$("#tst3").val(c);
});
});
});
Can you help me? what am i doing wrong?
You have many syntax errors in your code. I have revised it a bit. Please compare it with yours and see where you have your mistakes.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<!-- here i have added your javascript code directly. You can include it like that: <script src="deneme5.js"></script>-->
<script>
$(function(){
$("#asd").click(function() {
$(".row").each(function(index, element){
var a = $(element).find(".tst1").val();
var b = $(element).find(".tst2").val();
var c = parseInt(a) * parseInt(b);
$(element).find(".tst3").val(c);
});
});
});
</script>
</head>
<body>
<?php
$arr=[1,2];
foreach ($arr as $key=>$val){ ?>
<!-- in the following i have switched your ids into classes because ids have to be unique. Furthermore html attributes do not have to be separated by ';' -->
<div class="row">
<input class="tst1" type="text">
<input class="tst2" type="text">
<input class="tst3" type="text"><br><br>
</div>
<?php } ?>
<input id="asd" type="submit" value="hesapla">
</body>
</html>
One of the things done here was to convert the use of ID's to classes. ID's cannot be duplicated on a page because it will cause problems with JavaScript and CSS.

PHP: Fill combobox after choosing one option from another combobox using MySQL database

I have one combobox where I choose one option filled it up with the table 'distrito' where the columns it's 'ID' and 'nome'.
So far, so good. The problem is when I want to fill it up the other combobox depending on the option select in the first combobox. The table 'localidade' that fills this combobox uses the columns 'id', 'nome' and 'id_distrito'.
This is the code to fill the first combobox called 'distrito':
<?php
// Connects to your Database
include "config.php";
$QUERY_LISTAR_DISTRITO = "SELECT id, nome FROM distrito";
$DISTRITO = mysql_query($QUERY_LISTAR_DISTRITO) or die(mysql_error());
$nr_distrito = mysql_num_rows($DISTRITO);
while ($nr_distrito > 0) {
$row = mysql_fetch_row($DISTRITO);
echo '<option value="'.$row[0].'">'.$row[1].'</option>';
$nr_distrito--;
}
?>
This is the code to fill the second combobox called 'localidade':
<?php
// Connects to your Database
include "config.php";
$id_distrito = $_GET['distrito'];
$QUERY_LISTAR_LOCALIDADE = "SELECT * FROM localidade WHERE localidade.id_distrito = $id_distrito";
$LOCALIDADE = mysql_query($QUERY_LISTAR_LOCALIDADE) or die(mysql_error());
$nr_localidade = mysql_num_rows($LOCALIDADE);
while ($nr_localidade > 0) {
$row = mysql_fetch_row($LOCALIDADE);
echo '<option value="'.$row[0].'">'.$row[1].'</option>';
$nr_localidade--;
}
?>
This is the HTML code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Test</title>
</head>
<body>
<form action="registarGestorBD.php" method="post" enctype="multipart/form-data">
Distrito: <select name="distrito" id="distrito">
<?php include 'listarDistritos.php'; ?>
</select> <br> <br>
Localidade: <select name="localidade" id="localidade">
<?php include 'listarLocalidades.php'; ?>
</select> <br> <br>
<input type="submit" name="button1" id="button1" value="Guardar">
</form>
</body>
</html>
Thanks in advance. :)
This will solve your problem. Change your HTML file to this
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Test</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<form action="registarGestorBD.php" method="post" enctype="multipart/form-data">
Distrito: <select name="distrito" id="distrito">
<?php include 'listarDistritos.php'; ?>
</select> <br> <br>
Localidade: <select name="localidade" id="localidade">
</select> <br> <br>
<input type="submit" name="button1" id="button1" value="Guardar">
</form>
<script type="text/javascript">
$(document).on('change','#distrito',function(){
var val = $(this).val();
$.ajax({
url: 'listarLocalidades.php',
data: {distrito:val},
type: 'GET',
dataType: 'html',
success: function(result){
$('#localidade').html();
$('#localidade').html(result);
}
});
});
</script>
</body>
</html>
What you need is basically an ajax call which will fire on the selection of first combo box. The ajax call will sends the value of the first combo box and will query the other table based on id.
this might help you
Combobox items based on selected item in another combobox
You need to be looking at ajax. Consider this example (modified from Wikipedia):
function sendToServer(){
// Initialize the Ajax request
var xhr = new XMLHttpRequest();
xhr.open('post', 'send-ajax-data.php');
// Track the state changes of the request
xhr.onreadystatechange = function(){
// Ready state 4 means the request is done
if(xhr.readyState === 4){
// 200 is a successful return
if(xhr.status === 200){
var options = xhr.responseText.split(",");
populateComboBox(options)
}
}
}
// Send the request to send-ajax-data.php
xhr.send(distrito_id);
}
function populateComboBox(options){
var combo = document.getElementById("localidade");
$(options).each(function(i){
var opt = options[i];
var el = document.createElement("option");
el.textContext = opt;
el.value = opt;
combo.appendChild(el);
})
}
Then of course in your php, get the post variable distrito_id, do your query and return the results in a comma separated list!

Auto submit form using timer

I wrote the following code. With this code pushing Submit button submits the form manually. I have also a timer which I want to auto submit the form after 10 seconds. But it does not work. It counts until 0 and then it does not do anything. Can you please tell me what I am missing or how to change my timer (if there, is the problem)? But I want the user to watch the timer as my example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript">
function countDown(secs,elem)
{
var element = document.getElementById(elem);
element.innerHTML = "<h2>You have <b>"+secs+"</b> seconds to answer the questions</h2>";
if(secs < 1){
clearTimeout(timer);
document.getElementById('myquiz').submit();
}
secs--;
var timer = setTimeout ('countDown('+secs+',"'+elem+'")',1500);
}
</script>
<div id="status"></div>
<script type="text/javascript">countDown(5,"status");</script>
<title>Questionnaire</title>
<style type="text/css">
span {color: #FF00CC}
</style>
</head>
<body>
<h1>Please complete the following Survey</h1>
<form name="quiz" id ="myquiz" method="post" action="includes/process.php">
First Name: <input type="text" name="firstname" id="fname"/>
<p></p>
Last Name: <input type="text" name="lastname" id="lname"/>
<p></p>
<input type="submit" name="submit" value="Go"></input>
<input type="reset" value="clear all"></input>
</form>
</body>
</html>
There are three errors producing this bug.
You have a typo in form attributes. there is a space after id. It should be id="myquiz".
Your form has a button named "submit", which is wrong. It overrides the function. Name it "submitbutton" or something other.
The "validate" method is not defined. It should return true.
By the way, the timeout has wrong time, it should be 1000.
Working example: plunk
Don't do this:
var timer = setTimeout ('countDown('+secs+',"'+elem+'")',1500);
in countDown. Every 1500 you're calling countDown again.
Put this at the bottom of the page (before closing body tag)
<script type="text/javascript">
secs = 10;
timer = setInterval(function () {
var element = document.getElementById("status");
element.innerHTML = "<h2>You have <b>"+secs+"</b> seconds to answer the questions</h2>";
if(secs < 1){
clearInterval(timer);
document.getElementById('myquiz').submit();
}
secs--;
}, 1000)
Btw: where is validate() declared ?
Didn't test it, but it should do the trick.
You have to submit a form, not an element so try this:
document.forms["quiz"].submit();
OR if its the only form you can use
document.forms[0].submit();
This Code will work:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript">
function countDown(secs, elem)
{
var element = document.getElementById(elem);
element.innerHTML = "<h2>You have <b>"+secs+"</b> seconds to answer the questions</h2>";
if(secs < 1) {
document.quiz.submit();
}
else
{
secs--;
setTimeout('countDown('+secs+',"'+elem+'")',1500);
}
}
function validate() {
return true;
}
</script>
<div id="status"></div>
<script type="text/javascript">countDown(5,"status");</script>
<title>Questionnaire</title>
<style type="text/css">
span {
color: #FF00CC;
}
</style>
</head>
<body>
<h1>Please complete the following Survey</h1>
<form name="quiz" id="myquiz" onsubmit="return validate()" method="post" action="includes/process.php">
First Name: <input type="text" name="firstname" id="fname"/>
<p></p>
Last Name: <input type="text" name="lastname" id="lname"/>
<p></p>
<input type="submit" name="submitbutton" value="Go"></input>
<input type="reset" value="clear all"></input>
</form>
</body>
</html>
define function wait as
function caller()
{
setInterval(submit_now, 10000);
}
function submit_now()
{
document.forms["quiz"].submit();
}
Explaination:
1). Function wait() will set a time interval of 10 seconds (10000) ms before it calls submit_now() function.
2). On other hand submit_now() function do submit your form data when calling of this function is performed.

google custom search can't work

Here is the test.html file code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-hans" xml:lang="zh-hans">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test</title>
</head>
<body>
<div class="fr_search">
<form action="cse.php" accept-charset="UTF-8" method="post"
id="search-theme-form">
<input type="text" maxlength="128" name="search_theme_form"
id="edit-search-theme-form-1" size="15" value="" class="form-text" />
<input type="image" name="submit" id="edit-submit"
class="form-submit" src="images/search_btn_top.gif" /></div>
</form>
</div>
</body>
</html>
I put the code which generated by the http://www.google.com/cse/manage/create?hl=en. The
"Sites to search" I entered that was http://stackoverflow.com. When I put the generated code into the cse.php. Then put the cse.php and test.html into my local php enviroment. When I entered the text "php" into the search textbox and click the search button. But there is no any result on my search result page. What's wrong with my steps and code? thank you.
Here is the cse.php file code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>test search</title>
</head>
<body>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load('search', '1', {language : 'en'});
google.setOnLoadCallback(function()
{
var customSearchControl = new google.search.CustomSearchControl ('011247711644571852159:xe2ytn1hwsa');
customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
customSearchControl.draw('cse');
}, true);
</script>
<link rel="stylesheet" href="http://www.google.com/cse/style/look/default.css"
type="text/css" />
<?php echo 'test'; ?>
</body>
</html>
I'm not sure where to start with your code, but with a fresh code snippet from the Custom Search code generator, you can pass a query string to the CustomSearchControl. With code borrowed from here, something like this should work:
<div id="cse">Loading…</div>
<script src="http://www.google.com/jsapi"></script>
<script>
// Extract user's query from the URL
function getQuery() {
var url = '' + window.location;
var queryStart = url.indexOf('?') + 1;
if (queryStart > 0) {
var parts = url.substr(queryStart).split('&');
for (var i = 0; i < parts.length; i++) {
if (parts[i].length > 2 && parts[i].substr(0, 2) == 'q=') {
return decodeURIComponent(parts[i].split('=')[1].replace(/\+/g, ' '));
}
}
}
return '';
}
google.load('search', '1', {language:'en' });
google.setOnLoadCallback(function() {
var cseControl = new google.search.CustomSearchControl('ID_GOES_HERE');
cseControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
cseControl.draw('cse');
// Execute a query based on the query string
cseControl.execute(getQuery());
}, true);
</script>
So, for example that would go in your cse.php page (although there's no PHP in there at this stage) and your initial page's form something like:
<form action="cse.php" method="get">
<input name="q"> <input type="submit">
</form>
Get rid of the http:// in the sites to search bit.

Use one submit button to enter various pages in Javascript

I want to enter different rooms with on button. How is this possible in Javascript. For example, there are three rooms, "Kitchen, toilet and bedroom". How can I use JS to enter any of these rooms depending on my choice. so if i enter "kitchen" in the input box its gonna take me to kitchen.php, if I enter toilet...the same button is going to take me to toilet.php etc.
This is the HTML input,
<form method="post">
<input style=""name="Text1" type="text"><br>
<input name="move" style="height: 23px" type="submit" value="Move">
</form>
Just use a select field jsfiddle demo:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
<script type="text/javascript">
function submitForm() {
var myform = document.getElementById('myform');
var mytext = document.getElementById('room');
myroom = mytext.value.toLowerCase();
if (myroom == 'kitchen') {
myform.action = 'kitchen.php';
myform.submit();
} else if (myroom == 'toilet') {
myform.action = 'toilet.php';
myform.submit();
} else if (myroom == 'bedroom') {
myform.action = 'bedroom.php';
myform.submit();
} else return false;
}
window.onload = function(){
document.getElementById('move').onclick = submitForm;
}
</script>
</head>
<body>
<form id="myform" name="myform" method="post">
<input type="text" id="room" name="room" />
<button id="move" name="move" style="height: 23px">Move</button>
</form>
</body>
</html>
On the php side create three files to test to see if this works, toilet.php, kitchen.php, and bedroom.php with the following code in all three files. make sure the file names are lower cased:
<?php
echo $_POST['room'];
?>
Basically, based on the option that is selected, the JavaScript would change the form's action url and submit. If none is selected it'll return false and not submit. The submitForm function is attached to the move button with an onclick event.

Categories