Auto Submit form just once - javascript

I have configured the javascript code to do auto submit but what I want is that if the authentication fails, I do not do the autosubmit again.
My code is the following:
Form:
<?php echo form_open($this->uri->uri_string(), array('class' => 'login-form')); ?>
<div class="form-group">
<label for="email"><?php echo _l('clients_login_email'); ?></label>
<input type="text" autofocus="true" class="form-control" name="email" id="email">
<?php echo form_error('email'); ?>
</div>
<div class="form-group">
<label for="password"><?php echo _l('clients_login_password'); ?></label>
<input type="password" class="form-control" name="password" id="password">
<?php echo form_error('password'); ?>
</div>
<?php echo form_close(); ?>
Javascript
<script type="text/javascript">
window.onload=function(){
var auto = setTimeout(function(){ autoRefresh(); }, 100);
function submitform(){
document.forms["login-form"].submit();
}
function autoRefresh(){
clearTimeout(auto);
auto = setTimeout(function(){ submitform(); autoRefresh(); }, 10000);
}
}
</script>
How can I do it?

I believe your problem lies in array('class' => 'login-form').
Looking at the documentation for document.forms, you access the forms with ID.
I am not familiar with code-igniter; however, your code tells me that you are probably setting the class for a form. You would need to set the id for a form.
For preventing the auto-submit from running twice. From what I see, I suspect that you are getting a normal HTML form at the end. When you submit a HTML form it would make a trip to the server and when it comes back it should reload the page (unless you make it an asynchronous form).
Since the page is reloading, the window.onload would be run every time. To prevent this you would have to use a true-false flag some wheres.
Here are some potential solutions:
You could try looking into accessing url parameters from JavaScript. Some quick searching shows that this is a lot more complex than I'd expect though...
Alternatively, you could move the JavaScript code into a <script> block and echo out a script block from PHP. If you are going with this option you should look into using addEventListener method instead of accessing onload directly. PHP would make it much easier to accessing URL parameters by using $_GET or $_POST.
A second alternative would be to echo out a <input type="hidden"> that holds the true/false value and then access the value using JavaScript.
Once you can use your flag, you just need to check the flag in order to decide whether or not to auto-submit or not.
if (myFlag){
//submit form
}else{
//don't submit form
}
This true-false value is not sensitive data so it should be safe to place it as a GET parameter.

Related

PHP link builder to avoid use of Java Script and hide the old URL

I'm creating a login page that accepts a username and then redirects the user to log in. This is currently done, and works with the following Java Script.
function process()
{
var url="https://example.com/users/profile" + document.getElementById("username").value;
location.href=url;
return false;
}
<p>Enter your username</p>
<form onsubmit="return process();">
<input type="text" name="username" id="username">
I'd prefer to do this without using Java Script to support users that disable it, older browsers and to hide this from the source code of the page. The subdirectories are protected anyway but I just want the added compatibility.
I'm attempting to do this with PHP instead;
<form action="/authenticate.php">
<input type="text" name="username" id="username">
I'm using the same form but have created a page called authenticate.php instead. All that authenticate.php contains is;
<p>Authenticating…</p>
<?php
$username = ["username"];
header("Location: https://example.com/users/profile/$username"); die();
?>
If steve was the input, I'd expect that to then redirect to https://example.com/users/profile/steve but it doesn't. I've set up redirects already to handle errors and the form translates text to lowercase anyway.
I'm just wondering why;
<?php
$username = ["username"];
header("Location: https://example.com/users/profile/$username"); die();
?>
won't work with the addition to the URL but does work without the $username so that's the only error. I also tried $username = $POST_["username"]; but that's not relevant and doesn't seem to work either. The current code takes me to https://example.com/users/profile/Array
If someone could advise on the correct way to do this I'd very much appreciate it.
By default form method is GET but the best practice is to mention it so you've to do:
<form action="/authenticate.php" method="get">
<input type="text" name="username" id="username">
</form>
And authenticate.php you need to get input value:
<p>Authenticating…</p>
<?php
$username = $_GET["username"];
header("Location: https://example.com/users/profile/$username");
die();
?>

Targetting button outside of a form in action.php?

I currently have 2 forms, which adds data to my database. They both work, but they each have their own submit button - and I only want one submit button to collect the data from all the forms.
I found some javascript that should set the deal;
$("#submitbutton").click(function(){
$("#form1").submit();
$("#form2").submit();
});
The button I'm targetting is outside of both forms and looks like this:
<input id="submitbutton" type="button" value="add">
I'm pretty sure the reason why it doesn't work, is because of the way my php is written. I'm targetting the submit button in each form to excecute the php.
You can see the forms and php below.
One of the forms allows you to upload a picture;
<form id="form1" action="addimage.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<br/><br/>
<input type="submit" name="sumit" value="Upload" />
</form>
The action file contains this php;
<?php
if(isset($_POST['sumit']))
{
if(getimagesize($_FILES['image']['tmp_name'])== FALSE)
{
echo "Please select an image.";
}
else
{
$image= addslashes($_FILES['image']['tmp_name']);
$name= addslashes($_FILES['image']['name']);
$image= file_get_contents($image);
$image= base64_encode($image);
saveimage($name,$image);
}
}
displayimage();
function saveimage($name,$image)
{
$con=mysql_connect("localhost","root","");
mysql_select_db("ssdb",$con);
$qry="insert into pictures (name,image) values ('$name','$image')";
$result=mysql_query($qry,$con);
if($result)
{
//echo "<br/>Image uploaded.";
}
else
{
//echo "<br/>Image not uploaded.";
}
}
function displayimage()
{
$con=mysql_connect("localhost","root","");
mysql_select_db("ssdb",$con);
$qry="select * from pictures";
$result=mysql_query($qry,$con);
while($row = mysql_fetch_array($result))
{
echo '<img height="300" width="300" src="data:image;base64,'.$row[2].' "> ';
}
mysql_close($con);
}
?>
The other form lets you choose between multiple categories collected from my database;
<form id="form2" action="checkbox.php" method="post">
<label for="Category">Category</label>
<br />
<!-- iterate through the WHILE LOOP -->
<?php while($row = mysqli_fetch_array($result_category)): ?>
<!-- Echo out values {id} and {name} -->
<input type="checkbox" name="category[]" value=" <?php echo $row['id']; ?> "><?php echo $row['name'] . '<br />'; ?>
<?php endwhile; ?>
<input type="submit" name="Submit" value="Submit" class="btn btn-default"/>
</form>
And has the following php;
<?php
include("config.php");
$checkbox = $_POST['category'];
if($_POST["Submit"]=="Submit")
{
for ($i=0; $i<sizeof($checkbox);$i++) {
$query = "INSERT INTO placecategory (category_id) VALUES ('".$checkbox[$i]."')";
mysql_query($query) or die(mysql_error());
}
echo "Category is inserted";
}
?>
I've tried targetting the new button I made that should excecute the javascript, but it doesn't seem to work because that button is out of the form.
Is there a way to target the button outside of the form so the php excecutes when that is clicked? Or how can I rewrite this?
Any help is appreciated!
Not sure I understand completely what you're trying to do but try this with HTML5 add form="form1" and form="form2" for your second one and let me know if this works.
<form id="form1" action="addimage.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<br/><br/>
<input type="submit" name="sumit" value="Upload" />
</form>
<input type="submit" name="sumit" value="Upload" form="form1" />
Taking in account your complementary comment, then your proposed javascript sequence would work, assumed you have:
suppressed buttons such as <input type="submit"... /> from both forms
added the new button <button name="submitbutton">...</button> outside of the forms
modified the PHP parts accordingly, referencing $_POST['submitbutton'] instead of sumit and Submit respectively
You didn't report how it currently don't work, so the above steps target only the changes precisely related to the fact you replace two in-form buttons by a unique out-form one.
But something may turn wrong elsewhere. I notably noticed the non-usual way (at least for me) you get and process the image. Also you must ensure that your javascript part have really been executed.
Let me know if it doesn't work yet, than adding precise description of what turns wrong.
Edit, based on your provided comments and live preview.
Fully testing is not really possible because the server PHP part is out of reach, bue we can use Firebug to debug JS part.
So adding a breakpoint we can observe that, as soon as $("#form1").submit(); has been executed, the server returns a new page with the "Place has been added!" message.
In the other hand, without any breakpoint set, the server returns returns a new page with the "Categorie inserted!" message.
Though the OP didn't show the addingplace.php part of the current live preview, and comparing with the checkbox.php part, we can guess that:
In the reduced execution part, the first step addingplace.php did work as expected.
What we observe while whole execution merely means that all three parts have worked as expected, but each one having its returned message overwritten by the next one, but for the last one.
In other terms, when you comment "it only seems to submit the last form", this is a false impression based on what you only can see.
To ensure this is true or not you should control what is really updated or not in your database.
Let me know.
That said, it must be noted that this illustrates how the couple server-browser works in those circumstances: as already pointed by #David in a comment under the OP, to submit a form causes the browser to immediately receive a new page which overwrites the current one.
In the current example, it works because there are only few forms, and all three are submitted in a very reduced time, almost instantly: so the 3rd submit() can get executed before the 1st one's returned page comes.
So the recommended way to achieve the whole work in your example is merely to use only one form, with its unique submit button. BTW I wonder why you wanted to have this more complicated structure with three forms: what is the expected benefit?
Last point, outside of the precise issue you reported: you should pay attention to how you're coding. There is a lot of inconstencies in the HTML part, e.g.: a <html><body> part inside the already existing <body>; an exotic <br></br>; also you kept a supplemental button in the 1st form.

Cant submit form

Basically I've got a form with 5 radio buttons. No submit button. I want the form to run when the user clicks on any of the radio buttons, so this is what I did.
<input id="5" type="radio" name="star" onchange="this.form.submit();" <?php if ($row["star"] =="5") echo "checked";?> value="5"/>
a querystring is required for the form so I'm using a form action like this
<form name="submit" action="http://example.com/page.php?id=<?php echo $urlid;?>&title=<?php echo $title;?>" method="POST">
and my php is
if ($_POST["submit"]) {
$rating = $_POST['star'];
$title = $_GET['title'];
$verification = ($_GET['verification']);
} else {
//run the page like usual
}
After testing, I found that onclick, it runs the form action, but on the php side, it goes to "else" where is runs the page like usual instead. Any ideas?
Your PHP is checking if $_POST['submit'] contains a value. Your form does not contain a form element with the attribute name="submit", so therefore it fails and moves straight to the else statement.
If you want to check if the form was posted then you should instead check for:
if (!empty($_POST)) {}
or
if ($_SERVER['REQUEST_METHOD'] == 'POST') {}
The form element seems to have invalid attributes, missing a quote and space.
It's generally easier to write a little more code, and keep it clearer
<?php
$url = "http://example.com/page.php?id=". $urlid ."&title=". $title;
?>
<form name="submit" action="<?php echo $url; ?>" method="POST">
Since you are checking with -
if ($_POST["submit"]) { // this checks whether there is any item named 'submit' inside the POST or not
} else {
//run the page like usual
}
The easiest would be to put a hidden item with name submit so that the check validates to true-
<form .. >
....
<input type='hidden' name='submit' value='submit' />
</form>

Indirect Population of Textarea in HTML Form Using PHP

I am working on an "Update User Data" form, which should reflect the initially entered information stored in the database into the textarea, and can be changed if the user wishes to. While I'm doing so, I have a concern - is directly writing value = <?php //some code ?> the safest bet?
I was trying to invoke a function to place my PHP code in that instead, but apparently it's just displaying the function's name.
Here's my code snippet:
<div>Date of Birth: </div>
<input id="dob" type="date" onFocus="emptyElement('status')" value="reflect_data('dob');">
where the function reflect_data is defined as -
function reflect_data(elem) {
//query and some code to access the data and store into $member
if (elem == "dob") {
echo $member['DOB'];
exit();
}
NOTE : A newbie to PHP, any advice would be welcome. Thanks. :)
You use php code in a JS function. That won't work that way and is impractical. Simple:
<input id="dob" type="date" onFocus="emptyElement('status')" value="<?php echo htmlspecialchars($member['DOB']); ?>">
is the best solution.

reload form on submit with latest post data

I have a form to post content into a database. The existing database content for the form is posted into the form as the value. enalbeing the form to show the existing database content.
On submit the database is updated and to view the newly updated content in the form the page must be reloaded.
I have produced a reload script in javascript to reload the page on submit. The page reloads but the php content doesn't update. The page still need to be reloaded manually for the new content to show up.
This is the code for my form.
<form method="POST" action="">
<input type="text" name="title" <?php echo "value=\"" .$row['title']."\">"?>
<textarea id="editor" name="content"><?php echo $row['content']; ?></textarea>
<input type="submit" name="save" value="Save" class="submit" onclick="reload();">
</form>
Javascript
function reload(){
document.location.reload(true);
}
I have also tried
window.location = window.location.href;
Both are relaoding the page but the php isn't being refreshed.
you should first update the db with submitted value before selecting the records to display in the form value.
use <?php $_SERVER['PHP_SELF'] ?> in form action.
mysql_query("UPDATE xyz SET title=$_request['title'],... WHERE id = 1") .
2.Then select query mysql_query("SELECT * from xxx where id =1").
These may solve your problem of reloading to get new values.
java script excecute only on the client side. php is Server side. you need to reload the PHP.
<form method="POST" action="<<NAME OF YOUR PHP>>.php">
<input type="text" name="title" <?php echo "value=\"" .$row['title']."\">"?>
<textarea id="editor" name="content"><?php echo $row['content']; ?></textarea>
<input type="submit" name="save" value="Save" class="submit" onclick="reload();">
</form>
Is there a reason it needs to be done with ajax? If you don't need ajax it's better to handle it with php. ajax is more work and doesn't have the same rate of success as submitting a form via php, sometimes weird things happen. You can just do a redirect after saving the form:
header("Location: /routeToYourPage&id=".$ID,TRUE,303);

Categories