I have a small chat application for internal usage, this is light version just for example. I need few things, sorry for asking full source code but I try understand and learn from this example (I need it for few things).
Please find my source code:
<?php
if(isset($_GET['opt']))
{
if($_GET['opt'] == 'write')
{
$entry = $_POST['chat_input'];
$data = fopen("dat.txt","a+");
fwrite($data,"$entry\n");
fclose($data);
}
}
// jQuery auto refresh start
$dat = file_get_contents ("dat.txt");
if($dat == ''){echo 'You do not chat.';}else
{
$number_of_post = substr_count($dat, "\n");
$post = explode ("\n",$dat);
for($i=0 ; $i <= $number_of_post-1 ; $i++)
{
echo 'User x wrote: '.$post[$i].'<br>';
}
}
// jQuery auto refresh end
// jQuery form without refresh start
echo '<form method="post" action="index.php?opt=write">
<p><textarea rows="5" name="chat_input" cols="46"></textarea></p>
<p><input type="submit" value="Submit" name="B1"></p>
</form>';
// jQuery form withour refresh end
?>
I need two things:
- first is auto refresh iframe, when user write new post code must show this
- second is post my form without refresh, just execute action
Thank you very much for help, appreciate this.
To send post without refreshing use AJAX or method POST.
To refresh iframe do as asked here: How to refresh an IFrame using Javascript?
You can refresh iframe every second
setTimeout(function(){/*yourcodehere*/ },1000);
Related
I got a code here that if I refreshed the page it automaticaly save the data....can anyone help me that it will only save if the submit button is clicked.
current code:
<?php
ob_start();
?>
<html>
<head>
<title>test</title>
</head>
<body>
<?php
include('include/connect.php');
$query = mysql_query("SELECT DISTINCT count(batchcode) as batchcode1 FROM batchcodes");
while( $rows = mysql_fetch_array($query)) {
$code=$rows['batchcode1'];
}
if(isset($_POST['save'])){
$var = $code+1;
$sql = mysql_query("INSERT INTO batchcodes(batchcode) VALUES (". $var .")");
}
?>
<form method="post" action="index.php" >
<input type="text" value="batch<?php echo $var; ?>" />
<input type="submit" name="save">
</form>
</body>
</html>
The code you show is from your "handling" page. That page handles the post, it checks if there was a parameter "save" and if so, it saves.
If the user refreshes that page, he visits the page again, sending again a "save" parameter, so the INSERT is done twice.
To avoid this, you should use the POST-REDIRECT-GET model, where your handling page gets the data, saves it, and then redirects the user to a "GET" page (no post, no insert) that just shows the data. If the user then hits refresh, he only refreshes the "GET" page.
Offcourse, a user can always keep using the BACK button to go to the actual insert page. His browser will warn him "you are resubmitting form data...", but if he chooses to, he can. If you really want to handle this, you can work with session keys: have an extra field "submitID" on your form, and on INSERT, first check if that ID was already "used". You'll need an extra table/column "submitID" somewhere to ensure a form can only be submitted once.
The problem is the form is getting submitted again, you can make header redirect to this same page,
header("location: index.php) after updating your database and this will solve your issue.
Create one button in html
<input type="submit" name="submit"/>
In php Code, you can write like
<?php
if(isset($_POST['submit']))
{
//place your total code here
}
?>
As soon as the form is submitted once it has got the $_POST-Array in the site request. When you reload the page after the first submit, it will always send the data again.
You got multiple possibilities to resolve this problem:
1)
Reload the page after the execution of the PHP code. To do so put the PHP code at the top of the page (before writing anything in HTML) and reload the page after the execution of the query:
if(isset($_POST["save"])) {
/* MySQL Query */
$back = $_SERVER['HTTP_REFERER'] ; // the site who called this site
header("Location: $back") ; // Link back to this site
}
2)
Personally I prefer to execute my PHP scripts with an Ajax call, which would look as follows in jQuery.
function ajaxCall()
{
$.ajax({
type: "POST",
url: "handler.php",
data: {save: 1, textfield: $("#textfield").val()}
}) ;
}
Don't forget, that the forms action isn't the redirect to another site anymore, it is the call to this function ajaxCall. If you want more fields to submit, have a look at the serialize-function. The handler.php-file contains only your php-Code:
<?php
ob_start();
include('include/connect.php');
$query = mysql_query("SELECT DISTINCT count(batchcode) as batchcode1 FROM batchcodes");
while( $rows = mysql_fetch_array($query)) {
$code=$rows['batchcode1'];
}
if(isset($_POST['save'])){
$var = $code+1;
$sql = mysql_query("INSERT INTO batchcodes(batchcode) VALUES (". $var .")");
}
exit(0) ;
?>
In the ajax function you could also handle what happens when the call is successful (e.g. redirect). Have a look at the $.ajax-reference of jQuery. If you want you could also use ajax without jQuery.
3)
You could also make your page in action similiar to the handler.php in the second possibility.
<form action="handler.php" method="POST"></form>
In this case you had to replace the exit-statement with the $back and header-call in possibility 1 (similar to the response of Konerak).
I have a PHP AJAX json login form that I built.
I already have function that if you have been over than 5 failed attempts, the login form will be blocked.
But how to deny fast login attemps that has not entered user or pass?
I mean here in stackoverflow's login system when you click fast on the login button, 70% of the posts to server are denied.
And I don't want to make delay between posts, just to deny posts before the other post has been finished.
So what is the best way to deny fast click login posts?
You can use the following (example) method which works server-side, along with sessions to prevent people from clicking too fast.
The present code is set to 3 seconds minimum.
You can put the code you are using for successful post inside the else condition.
Important: If you are using multiple pages, then session_start(); needs to be inside every page, for included files also.
Presently set to work inside ONE file, using action=""
<?php
session_start();
$_SESSION['start_time'] = time();
if (isset($_POST['submit'])) {
$current_time = time();
if (!empty($_POST['start_time'])) {
if (($current_time - $_POST['start_time']) < 3) { // 5 is number of seconds differential; change as you sit fit
// someone/something has submitted this form in under 5 seconds from reaching the page
// probably a bot
echo "Sorry, too fast";
exit;
}
else {
$fname = $_POST['fname'];
$fname = ucwords($fname);
echo "Thank you $fname";
}
}
}
?>
<form action="" method="post">
<input type="hidden" name="start_time" value="<?php echo $_SESSION['start_time']; ?>"/>
<!-- other form fields -->
<input type="text" name="fname">
<input type="submit" name="submit" value="Submit" />
</form>
If you want to deny posts before the previous one has been done
I would suggest storing a post status value in a session
so when a post is made this status will change to a value indicating it is busy
and if someone tries to post before it is done they will get a message from the server that that it is busy.
I am not sure how you are implementing this but this is more like pseudo code explaining this idea.
<?
if($_SESSION['busy'] == true){
$_SESSION['busy'] = true;
//PHP POST HANDLER CODE HERE
$_SESSION['busy'] = false;
//RETURN JSON FOR RESULT OF LOGIN ATTEMPT
}
else
{
//RETURN JSON FOR BUSY STATUS
}
?>
Is there any way to know if the page was refreshed or data was posted data on the same page?
To be little more specific:
I have to post data on the same page.
This affects the where condition of the query.
If the page was refreshed, then the where condition must be 1.
Otherwise, where condition contains some id to get specific data from
the table.
Your best bet is to use PHP sessions, along with your submitted data in $_POST. Let's presume for this example you have the following form:
<form action="this_page.php" method="post">
<input type="text" name="important-info" />
<input type="submit" value="Submit" />
</form>
Then elsewhere in the same page is the PHP code:
<?php
// example code
session_start();
if (!isset($_SESSION['previousVisitor']) && isset($_POST['important-info'])) {
// this is a new visitor who has submitted the form
$_SESSION['previousVisitor'] = true;
// where is based on $_POST['important-info']
} else () {
// where is 1
}
// close the session after you do what you need - this stops large pages causing hang
session_destroy();
Please note that they can clear this session variable by deleting their cookies.
on the top of the page just include
if(isset($_POST['name']) && $_POST['name']!=''){
//your code goes here
}
I suggest you to check request
//Here goes the code
session_start();
$counter = 0;
$counter = (isset($_SESSION['param'])) ? $counter++ : 0;
if($counter == 0)
echo "data GET or POST";
else
echo "refreshed";
** If you want only POST param, use $_POST instead of $_REQUEST
I'm working on a little project, basically I have some text on my PHP/HTML page that is being echo'ed from a variable ($brief_string).
There is also a back, and continue button which basically subtracts or adds to another variable ($brief_page - which is pulled from my DB). The brief_string changes depending on the brief_page by using if statements. First problem I encounter is that when I hit continue (submit button) it resubmits/refreshes the page, causing my brief_page to reset back to 0.
So I'm thinking maybe I could use JS to hold the info and page variables and control the dynamic text, but then, how would I update my DB with the current page value via JS? Isn't it really easy to manually change/hack these values? I would preferably like my DB to be updated with the page number each time the use presses the back/continue button.
I would just like some advice really as I am a student trying to develop an interactive book like site (that uses a DB to save your current page).
Code:
<?
$brief_info = "brief info goes here";
$brief_page = 0; //< will soon be pulled off DB
if (isset($_GET['brief1Go'])) {
$brief_page = $brief_page + 1;
}
else if (isset($_GET['brief1Back'])) {
$brief_page = $brief_page - 1;
}
$breifController = "
<form action=\"".$_SERVER['PHP_SELF']."\" method=\"POST\">
<input type=\"submit\" name=\"brief1Back\" id=\"brief1Back\" value=\"BACK\" />
</form>
<form action=\"".$_SERVER['PHP_SELF']."\" method=\"POST\">
<input type=\"submit\" name=\"brief1Go\" id=\"brief1Go\" value=\"CONTINUE\" />
</form>";
if($brief_page == 0){
$brief1_info = "<b>Welcome Commander,</b> you are currently viewing the Mission Control Brief page, here you can view all your missions that you need to complete in order to advance through your prestiges. You will need to follow your briefs carefully in order to succeed. <br /><br />
";
}
else if($brief_page == 1){
$brief_info = "Okay, let me show you around the place ...";
}
else if($brief_page == 2){
$brief_info = "brief is on 2";
}
?>
Why not just use get vars entirely?
yes, start at 0 unless $_GET['page'] is set...
$brief_page = 0;
if(isset($_GET['page']))
$brief_page = $_GET['page'];
then only use links to your next and previous pages instead of some weird post thing.
Previous Next
where obviously the page numbers in the previous and next are just echoed from php
$prev = $brief_page - 1;
$next = $brief_page + 1;
The user specific things to store can easily be handled with sesisons, cookies or even other get vars if you want to introduce a horrible security hole. Your choice really.
I would definitely not do this via $_POST though. totally annoying. Go with all full on ajax if you want to do that. At least you won't pester the user with "are you sure you want to resubmit the form data" messages if they choose to refresh the page.
ok, i'm trying to do a quiz...all good by now. but when i'm trying to send the collected data(radio buttons values) through pages i can't get the logic flow. I have the main idea but i can;t put it into practice.
i want to collect all radio values
create an array containing this values
serialize the array
put the serialized array into a hidden input
the problem is that i want to send data on the same page via $_SERVER['PHP_SELF'] and i don;t know when in time to do those things.(cause on "first" page of the quiz i have nothing to receive, then on the "next" page i receive the S_POST['radio_names'] and just after the second page i can get that hidden input). i hope i made myself understood (it's hard even for me to understand what my question is :D )
You could try to use the $_SESSION object instead... For each page of your quiz, store up the results in the $_SESSION array. On the summary page, use this to show your results.
To accomplish this, on the beginning of each page, you could put something like:
<?
session_start();
foreach ($_POST as $name => $resp) {
$_SESSION['responses'][name] = $resp;
}
?>
Then, on the last page, you can loop through all results:
<?
session_start();
foreach ($_SESSION['responses'] as $name => $resp) {
// validate response ($resp) for input ($name)
}
?>
Name your form fields like this:
<input type="radio" name="quiz[page1][question1]" value="something"/>
...
<input type="hidden" name="quizdata" value="<?PHP serialize($quizdata); ?>"/>
Then when you process:
<?PHP
//if hidden field was passed, grab it.
if (! empty($_POST['quizdata'])){
$quizdata = unserialize($_POST['quizdata']);
}
// if $quizdata isn't an array, initialize it.
if (! is_array($quizdata)){
$quizdata = array();
}
// if there's new question data in post, merge it into quizdata
if (! empty($_POST)){
$quizdata = array_merge($quizdata,$_POST['quiz']);
}
//then output your html fields (as seen above)
As another approach, you could add a field to each "page" and track where you are. Then, in the handler at the top of the page, you would know what input is valid:
<?
if (isset($_POST['page'])) {
$last_page = $_POST['page'];
$current_page = $last_page + 1;
process_page_data($last_page);
} else {
$current_page = 1;
}
?>
... later on the page ...
<? display_page_data($current_page); ?>
<input type="hidden" name="page" value="<?= $current_page ?>" />
In this example, process_page_data($page) would handle reading all the input data necessary for the given page number and display_page_data($page) would show the user the valid questions for the given page number.
You could expand this further and create classes to represent pages, but this might give you an idea of where to start. Using this approach allows you to keep all the data handling in the same PHP script, and makes the data available to other functions in the same script.
You want to use a flow such as
if (isset $_POST){
//do the data processing and such
}
else {
/show entry form
}
That's the most straight forward way I know of to stay on the same page and accept for data.