How to prevent a page to reload after on submitted? - javascript

I'm Writing a PHP Programming with the database, I submit the form data to be inserted into the database at the same page but when it is reload it gives the respected error. I want to block the reload of the page using javascript or jQuery but I did not get any idea for it.
<!DOCTYPE HTML>
<html lang="en">
<head><title>Title</title></head>
<body>
<form method=post>
<label for="name">Name </label>
<input type=text name=name size=30>
<br/>
<input type=submit value=Sent name=submit>
</form>
</body>
</html>
I has close the form tag before the here I could not do that.
the php script is
<?php
$conn=pg_connect("host=hostname dbname=databasename user=username password=password") or die("Error, Could not connect".pg_last_error($conn));
$rs=pg_query($conn,"insert into tablename(name) values($_POST['name']");
if($rs)
{
echo "Inserted";
}
else
{
echo "ERror is occured!";
}
?>
Consider name is a unique in database then the error is generate during resubmission of form...
It is the second step when I submit the page after fillup the form..
It occurs after the re-submission of the form
Please Help me to resolve the problem..
Thanks....

You can use javascript jquery to submit your form asynchronously. Instead of using input type submit, you can use button with attribute 'onclick' that will call your javascript function. Example of form post can be found here.
In PHP file, you need to return useful result i.e status. From that status, you can decide the behaviour of your form after received the result either to proceed to other page or show errors.

Related

Stop refreshing on submit button [duplicate]

This question already has answers here:
JavaScript code to stop form submission
(14 answers)
Closed 4 years ago.
Is there any way to stop refreshing the page on submit button if your if condition goes false and show all the input fields with values entered?
Since you mentioned PHP, then why not use it?
I assume your question has two parts like below.
Part one - you wrote:
show all the input fields with values entered
By above, you mean using $_SESSION to repopulate the fields with the submitted data?
Part two - you wrote:
Is there any way to stop refreshing the page on submit button if your if condition goes false
Note that submit and any on is an event within the client side processing scope. You can use jQuery or JS validations for that.
Here below are two files for your learning test.
The posting php:
<html>
<body>
<form action="action.php" method="POST">
<input type="text" name="feedback" value="" />
<input type="hidden" name="token" value="123456ABCDEF" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
<?
session_start();
$token = '123456ABCDEF';
if(isset($_SESSION)){
if($_SESSION['token'] == $token){
echo "Your feedback:<br />";
foreach($_SESSION as $field=>$value):
echo $field.": ".$value."<br />";
endforeach;
}else{
echo " Bad token! Cross-Site Request Forgery (CSRF)";
}
}else{
echo "Nothing!";
}
The posted to php:
<?php
session_start();
$_SESSION = $_POST;
$_SESSION['message'] = "Thank you for the feedback!";
header('Location: ' . $_SERVER['HTTP_REFERER']);
?>
Hope I got you right and above helps.
First off, this is a duplicate of JavaScript code to stop form submission
Now, when we got that out of the way, here is abrief explanation. You cannot prevent the browser itself from refreshing. But what you can do is prevent the form from being submitted (and in turn causing a refresh). And this is the usual solution when dealing with form validation in JS.
You can check the abode linked answer for more details.
You can use Post / Redirect / Get Pattern. If you have errors redirect to same page with form and show errors. You can't just "stop" the form during POST.
Other way if you don't want "showing" any redirect you can use ajax request. Form wont "blink".
You can also use javascript for checking field onchange event of input elements.

Getting "Invalid URL Exception" on submit due to multiple form tags in Lotus Domino

I'm getting the error, "Invalid URL Exception" on submit of a button. I am assuming that this issue is coming from three form tags I have in the web page.
In the body, the first form tag is for "post" of the fields and redirection. The second one, which is inside of the first form tag, is for the search bar as part of company header.
The third one is a form class for the input fields, which is also inside the first form tag.
I tried placing an end form tag in the first line of my code, it closes the form tag which now looks like this:
<form method = "post" action="/sample/sampleweb.nsf/myForm?OpenForm&Seq=1" enctype="multipart/form-data" name=_myForm">
<input type="hidden" name="__Click" value="0">
</form>
Then the search form tag comes in after as also part of body. Upon clicking the submit button, I'm getting such error. When I tried searching by clicking the search, search functionality working as expected.
When I tried removing the form tag and end form tag for the search, and I click on Submit, it's working as expected.
I notice that domino is still creating end form tag at the last part of the page, right before the end of body tag. Could it be because of this?
To give you a better idea, here is the structure of it:
<html>
<body>
<form method = "post" action="/sample/sampleweb.nsf/myForm?OpenForm&Seq=1" enctype="multipart/form-data" name=_myForm">
<input type="hidden" name="__Click" value="0">
</form> //This comes out when I add end form tag in the first line of code.
<form class="searchbox">
<input id="searchtxt" class="searchbox-submit">
<input type="submit" class="searchbox-submit">
</form>
<form class="form-horizontal">
//Rest of the code go here having the input fields.
<button type="submit" onclick="return validatefields(event)">Submit</button>
</form>
</form> //This part is the generated form tag.
</body>
</html>
Any help would be appreciated.
Domino creates the form tags for you because it assumes you are doing data entry if the form is in edit mode. To prevent this use the setting on the form properties second tab (propeller head) for "On Web Access" "HTML". With that you can do anything you want in HTML but as Richard suggested you need to define where to go when the form is submitted.
Once created this way you need to use the ?ReadFrom url parameter rather than the ?OpenForm parameter

Submit form and redirect not working

EDIT: I should mention the form submits fine manually but with the javascript nothing seems to happen
I'm trying to get a form to autosubmit on page load and then redirect the user. Reason for this is this is part of a PHP page and the data needs to go into my database but then also POST the variables to a 3rd party SMS platform then return to the users dashboard.
My form looks like this:
<html>
<form action="https://www.example.com" id="myForm" method ="POST">
<input type="hidden" name="apiKey" value="withheld">
<input type="hidden" name="message" value="<?php echo $club_name ?> have requested you to play for them this weekend. Please login to your account to see more information and accept.">
<input type="hidden" name="to" value="<?php echo $to ?>">
<input type="hidden" name="from" value="withheld">
<input type="submit" name="submit" id="submit" value="Submit">
</form>
</html>
This seems to work fine so I assume the Javascript is incorrect which is:
<script>
document.getElementById('myForm').submit();
window.location.replace("https://www.example.com");
</script>
You have to use a different name than
name="submit"
as all name attributes are set as properties on the form,
hence overriding the default "submit" property on the form,
and the default form method "submit()" is gone.
https://developer.mozilla.org/de/docs/Web/API/HTMLFormElement
"Named inputs are added to their owner form instance as properties, and can overwrite native properties if they share the same name (eg a form with an input named action will have its action property return that input instead of the form's action HTML attribute)."
In your code window.location.replace("https://www.example.com"); line won't make sense because submit() function will try to submit the form and will change the page and then replace function will prevent submitting the form and will redirect the page. The right way to do this via js can be, submit the form via ajax and in the success callback of Ajax run document.getElementById('myForm').submit()

How to submit two forms on 2 different .htm files to the same place

I'm trying to essentially have the submit button of search.htm be able to create a pop up with a text area which the users are required to enter a comment describing their actions and click the submit button in the pop up to effectively submit both forms to the same processing page. Both the forms in search.htm and frm_comment.htm will submit both sets of data back to search.htm which calls cfinclude on the server processing logic (server.htm).
In the below code I'm having the the "createPeriod" button submit everything that is in the "srch" form. It is also creating a pop up window which has a html textarea that allows the user to enter a comment. There is a reason that I need to split up the main form from the comment form (frm_comment.htm) but it's very specific to the task I'm trying to accomplish.
search.htm is structured roughly as such:
//include the template here to process the forms
<cfinclude template="../server.htm">
<cfform method = "post" action = "search.htm" name="srch" format="html">
<table>
//bunch of form fields here
.
.
.
.
//bunch of form fields here
<cfinput type="submit" name="createPeriod" value="Create"
onClick="ColdFusion.Window.create('comment', 'CommentBox',
'frm_comment.htm', {center:true,modal:true})">
</table>
</cfform>
I've tried to change the submit button in search.htm to just a cfinput type="button" because keeping it as a submit will make it so that the comment box will appear for a brief moment while the page reloads and disappear as soon as the page reloads. However, I was unable to preserve the form data from search.htm when changing the submit button to a regular button.
I've also tried to have my comment form's submit button's onClick function call a javascript function to submit both forms (to no avail) like so:
submitForms = function(){
document.forms["srch"].submit();
document.forms["srch1"].submit();
}
<cfinput type="button" name="submitComment" value="Submit" onClick="submitForms()"/>
Please advise on the best way to accomplish this task, sorry about the messy code.
This a very basic example, on how to have your 2 forms in one. The JavaScript will just show the comment form when the user clicks on "Search".
<!DOCTYPE html>
<html>
<head>
<style>
#hiddenStuff {
display: none;
}
</style>
</head>
<body>
<form action="...">
// search fields here
<input type="button" value="Search" onclick="document.getElementById('hiddenStuff').style.display='block';">
<div id="hiddenStuff">
// comment form stuff here
<input type="submit" value="Submit">
</div>
</form>
</body>
</html>
I also made a fiddle, if you want to see the result in action.
Sorry I'm not familiar with ColdFusion, but it shouldn't be too hard for you to translate :)

Can server script detect if a form is posted with submit button or with javascript:Submit()

This problem is keeping me busy all week and I find little to nothing on the net ...
What I want to do is simple ... on my own website, create a server side PHP script that makes a login to another website with valid credentials and downloads a file that I want to process.
I use curl_init(), curl_setopt() and curl_exec() in trying to achieve that. It doesn't work.
So I stripped down that webpage to figure out what's wrong.
As you can see in the html code, the form's action event is the url to retrieve the file, when correct credentials are submitted.
<!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" >
<body>
<form name="form1" method="post" action="http://otherwebsite/login.aspx?ReturnUrl=/export_file.aspx?id=xxxxxxx" >
<script type="text/javascript" language="JavaScript">
function Submit_Form()
{
document.form1.Login$UserName.value="myname";
document.form1.Login$Password.value="mypassword";
//document.form1.Login$LoginButton.click();
document.form1.submit();
}
</script>
<input type="hidden" name="Login$UserName" value="myname" />
<input type="hidden" name="Login$Password" value="mypassword" />
<input name="Login$LoginButton" type="submit" />
<br />Login
</form>
</body>
</html>
Now here is where it gets weird.
If I press the button, it works and I receive the download file.
If I click the hyperlink, i get a page saying to login properly.
When I uncomment the javascript line : click() it works too.
So it comes down to this :
Why does the button submit work and javascript submit doesn't work ?
Is there a way that the other website's server check how the form was posted ?
Thank you for your thoughts !
When you click the button, its name is included in the POST request because it's a named submit button. When you use the link, the button's name doesn't get passed in the POST data.
You could probably spoof the button when you use the link by having a hidden field with the name the button should have:
<input type="hidden" name="Login$UserName" value="myname" />
<input type="hidden" name="Login$Password" value="mypassword" />
<input type="hidden" name="Login$LoginButton" />
Note it doesn't need a value because the button it replaces doesn't have a value setting its text. Just including it should be sufficient.
Why not have another hidden field called js_submitted with a value of false, and in your Submit_Form() function, set it to true before firing the submit() method? Then, in PHP (for example), you could look for $_GET/$_POST['js_submitted'] to determine which submission method was used.
It's possible to check that the button was posted with the submit. Maybe they are checking for this.
Yes, it is very easy to find out when a button submits a form, and that is exactly what the site might be doing.
A button is a form control and so, when a form is submitted, the button state is submitted as well. What this means is, when you check the form object on the server that receives the post, you will see it contains a key with the same name as the button and it's value is set to the value attribute of your button.
Consider you have a form:
<form id="form1" action="abc.asp" method="post">
<input type="submit" name="btn" value="Opt123" />
<input type="submit" name="btn" value="Opt456" />
Send
</form>
I am not a PHP person, so code might not be the best:
$item = $_POST['btn'];
In this case, value of $item will be either Opt123 or Opt456 depending on the button pressed, whereas if the link is pressed, then it would be a null or PHP equivalent.
Even though the submit button is part of the form, the browser only sends its name=value pair as part of the post data if the button was actually clicked. When you call the .submit() method from Javascript, your browser sends the data Login$Username=myname&Login$Password=mypassword to the server. But when you actually click the button, it sends Login$Username=myname&Login$Password=mypassword&Login$LoginButton=. As you can see, it would then be very easy for the server to differentiate between the two.
So, you can trick the form into always sending that element by making it hidden. In Submit_Form, just before you say document.form1.submit();, add this:
var sbtn_hid = document.createElement('input');
sbtn_hid.type = 'hidden';
sbtn_hid.name = 'Login$LoginButton';
sbtn_hid.value = '';
document.form1.appendChild(sbtn_hid);
That adds a hidden form element with the same name as the submit button, so the server won't be able to tell the difference.

Categories