HTML page is refreshing after clicking on submit button with onclick function - javascript

I have a form in this index.html page with an Ajax script, on clicking the submit button it should just display "Authentification succeeded" or not, if the user is in the database, it works but when I hit submit it displays the message for only one second. How can I keep the message displayed?
Here's the index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Accueil</title>
<style type="text/css" media="screen">
h1 {
color:red;
}
</style>
<script language="javascript">
function chargement()
{
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
var x = new XMLHttpRequest();
x.open('GET','verif.php?email='+email+'&password='+password,true);
x.onreadystatechange = function()
{
if ((x.readyState == 4 ) && (x.status == 200))
{
document.getElementById('res').innerHTML= x.responseText;
}
}
x.send();
}
</script>
</head>
<body>
<h1>Bienvenu(e) à Affariyet.tn </h1>
<table>
<form action="index.html" method="GET">
<tr>
<td>Email :</td>
<td> <input type="text" id ="email" name="email" value="" placeholder="Votre Email"><br></td>
</tr>
<tr>
<td>Mot De Passe : </td>
<td><input type="password" id="password" name="password" value="" placeholder="Votre Mot De Passe"><br></td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" name="auth" value="S'authentifier" onclick="chargement()">
<input type="reset" name="reset" value="Annuler">
</td>
</tr>
<tr>
<td></td>
<td><div id="res"> </div></td>
</tr>
</form>
</table>
</body>
</html>
And this is the PHP file that has the verification function :
<?php
include 'config.php';
class main
{
public $conn;
function __construct()
{
$c=new config();
$this->conn=$c->connexion();
}
function verif($conn,$email,$password)
{
$req="SELECT `Email`,`Password` FROM utilisateur WHERE `Email`='$email' AND `Password`='$password' ";
$res=$conn->query($req);
return $res->RowCount();
}
}
$m=new main();
$email=$_GET['email'];
$password=$_GET['password'];
$resultat=$m->verif($m->conn,$email,$password);
if($resultat==0)
{
echo '<h4 style="color:red;"> Email ou mot de passe erroné</h4>';
}
else
{
echo '<h4 style="color:green;">Authentification réussie. Accéder à la <a href=produit.php>Liste des produits</a></h4>';
}
?>

Your issue comes from that, when you submit:
you execute the chargement() function as stated by the onclick attribute, and it works
but since your button has type="submit" its default behaviour is to submit the form: then the action="index.php" is executed, so reloading the page, which obviously doesn't not include what you'd just put into the res div
To avoid this (i.e work without reloading the page) you can use two ways:
one is to prevent default action, either as already proposed by #anhkzet (
but in your case it can't work "as is"; look at it's answer's edit), or by adding event as argument to your chargement() function, then including event.preventDefault; before it ends
more simply you can change your <input type="submit"...> into <button type=button"...>: this way the form is not submitted at all.
EDIT in response to the supplemental question added by the OP in its comment below.
In order to use POST rather than GET you can merely substitute the desired method in your XMLHttpRequest.open() function.
I guess that you ask it because you're incertain about how to pass POST data in this case.
In fact there is no place in the method for an argument that would contain such data, but it doesn't matter: like with the <form> tag you can at once use POST method and keep query parameters attached to the url.

Inputs with type submit are meant to send data in form to server. To prevent default behaviour of submit button add return false; at the end of chargement() handler.
Ok, apparantly, I forgot 'bout return statement inside attribute...
Either:
<input type="submit" onclick="return chargement()" />
... and add return false to the end of chargement method.
...or just
<input type="submit" onclick="chargement(); return false;" />
Both should work.

Related

I want to display a confirmation dialog before displaying output

I want to display a confirmation dialog box like "Do you want to continue?" If "yes", I want to popup a message displaying form output, if "No" I want to stay on the same page.
In the code shown below I am navigating to facto.html for displying the output, but I want to show a popup with its contents instead. How can I do that?
My index.html:
<!DOCTYPE html>
<html>
<head>
<title>Lift From Scratch</title>
<script type="text/javascript">
<!--
function getConfirmation(){
var retVal = confirm("Do you want to continue ?");
if( retVal == true ){
<!--document.write("continue")-->
<!--window.location.href = '/facto.html';-->
return true;
}
else{
alert("Don't continue")
<!--window.location.href = 'index.html';-->
return false;
}
}
//-->
</script>
</head>
<body>
<h1>Finding Factorial</h1>
<div id="main" class="lift:surround?with=default&at=content">
<form method="post">
<table>
<tr><td> Enter a Number:</td> <td><input name="num" type="number"></td></tr>
<tr><td><input type="submit" value="Submit" onclick="getConfirmation();" formaction="facto"></td>
<td><input type="reset" value="Reset"></td>
</tr>
</table>
</form>
</div>
</div>
</body>
</html>
facto.html:
<div data-lift="factorial">
<p>Factorial is: <span name="paramname"></span></p>
</div>
Try something like this:
function validateMyForm()
{
if( confirm('Are you sure?') )
return true; // will submit the form
else
return false; // do not submit the form
}
<form name="myForm" onsubmit="return validateMyForm();">
<input type="submit" value="Submit" />
</form>
You're going to probably want to fall back to JavaScript for this one, to be honest. You can make the form an AJAX form using Lift's SHtml.makeFormsAjax helper, then you can bind your submit button using SHtml.ajaxSubmit. The callback you pass to ajaxSubmit should return a JsCmd. That JsCmd can trigger the display of the popup. You can even render the popup's contents by using SHtml.idMemoize.
If you describe this question in a little more detail on the Lift group, you will probably find folks willing to help you with some of the more specific aspects of it.

Several submit buttons in a single HTML form

I'll cut to the chase. I wish to have two separate buttons that does two unique functions. However, acquiring data from the same form. The current problem that I'm facing is onSubmit() will always be executed with whatever buttons I attach to the form instead of its own function.
checkUser.js: Acquires username from the input field and tries to match it with the database (Oracle)
Update 1:
I have changed them accordingly. However, pressing Check still forwards me to StaffRegAuth.jsp instead of executing checkUser and then opening a new window.
<form action="StaffRegAuth.jsp" name="form" method="post">
...
<button onClick="return validStaffReg();">Register</button>
<button onclick="return checkUser()">Check</button>
</form>
Update 2:
Updated my checkUser.js as it seems to be the problem
StaffReg.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Staff Registration</title>
<%-- Javascript --%>
<script type="text/javascript" src="JS/validStaffReg.js"></script>
<script type="text/javascript" src="JS/preventSpace.js"></script>
<script type="text/javascript" src="JS/checkUser.js"></script>
</head>
<body>
<%response.addHeader( "Cache-Control", "no-cache"); response.addHeader( "Pragma", "no-cache"); response.addHeader( "Expires", "0"); %>
<h1 align="center"> Account Registration: </h1>
<form action="StaffRegAuth.jsp" name="form" method="post">
<div align="center">
<table style="width = 30%">
<tr>
<td>User Name:</td>
<td>
<input type="text" name="username" onKeyDown="preventSpace(this)">
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type="password" name="password" onKeyDown="preventSpace(this)">
</td>
</tr>
<tr>
<td>User Group:</td>
<td>
<select name="userGroup">
<option value="1">Administrator
</optin>
<option value="2">Clerk
</optin>
<option value="3">Operations
</optin>
<option value="4">Sales
</optin>
</select>
</td>
</tr>
<tr>
<td>
<button onClick="return validStaffReg(form)">Register</button>
</td>
<td>
<button onClick="return checkUser(form)">Check</button>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
validStaffReg.js
// JavaScript Document
function validStaffReg(form) {
if (document.form.password.value == "" && document.form.username.value == "") {
alert("Please enter a Password and Login ID.");
document.form.password.focus();
return false;
}
if (document.form.username.value == "") {
alert("Please enter a Login ID.");
document.form.username.focus();
return false;
}
if (document.form.password.value == "") {
alert("Please enter a Password.");
document.form.password.focus();
return false;
}
return true;
}
checkUser.js
function checkUser(form) {
if (document.form.username.value != "" || document.form.username.value != null) {
var myWindow = window.open("checkUser.jsp", "MsgWindow", "width=200, height=100");
myWindow.document.write("<p>This is 'MsgWindow'. I am 200px wide and 100px tall!</p>");
document.form.username.focus();
return false;
}
return true;
}
Don’t use submit.
I.e., don’t use <input type="submit">.
Instead, make two separate buttons and call different functions onclick. Mind you that you can still get the form values.
I.e.,
<button onclick="return reqfunc()">
Use return, and now you can use the function. If you want to return to the form back without going to the next page then just return false in the JavaScript code.
Use <button onclick='YourFunction()'>Button Text</button>.
One of the tricks I use regularly is something like the following.
<form action="submit.jsp">
<button type="submit" name="submit_form" value="1" class="hiddenSubmit">Submit</button>
...
<button type="submit" name="clear_form" value="1">Clear</button>
<button type="submit" name="submit_form" value="1">Submit</button>
</form>
By giving the buttons different names, you can have the form do whatever processing is consistent and let the server manage any button-specific processing. Of course, you can also attach event handlers to the separate buttons.
Why does it have two [name="submit_form"] buttons? The first one has a class that you would style to make it active yet invisible (e.g., position: absolute; top: -1000px; left: -1000px) so that a keyboard <Enter> will fire that button instead of the other button[name="clear_form"].

jQuery $('#id').submit() not working

I am creating a form such that when the user click the "submit" button, it prevents the default action, serializes a subset of the fields, and then proceeds to submit all of the information via the POST array (PHP).
I am encountering a problem where the form is basically not submitting when I use the .submit() method. When I disable my javascript, the form submits fine (just with the wrong information, as the array is not serialized). But as soon as I re-enable my js, clicking the submit button does nothing except show my test console.log(var) in console. Here is some of my code, hopefully you can see what I am doing wrong. All of the online documentation says to use .submit(), but it doesn't seem to work, no matter what I try.
HTML:
<form id="entryForm" action="add_entry.php" method="post">
<div class="leftDiv">
<input type="text" class="inputFormTitle" name="entryName" placeholder="Name your entry..." />
<span class="regText">
<b>Entry Properties</b>
Specify entry properties, permissions, etc.</span>
<table class="formTable">
<tr>
<th>Parameter</th>
<th>Value</th>
<tr>
<td>Group</td>
<td><select name="group"><option></option><option>Graham Test</option></select>
</tr>
<tr>
<td>Project</td>
<td><select name="project"><option></option><option>Project 1</option><option>Project 2</option></select>
</tr>
<tr>
<td>Protocol</td>
<td>
<select id="protocolloader" name="protocol">
<option></option>
<option>PCR & Gel</option>
<option>Item Storage</option>
<tr>
<td>Permissions</td>
<td><input type="radio" name="permission" value="0">Only I can access this entry</input>
<input type="radio" name="permission" value="1">Only group members can access this entry</input>
<input type="radio" name="permission" value="2">Everyone can access this entry</input>
</select>
</tr>
</table>
<input type="submit" id="submitEntry" style="font-family:Raleway;" class="inputButton" type="button" name="submit" value="Submit Entry" /
<br/>
</div>
<div class="rightDiv">
<input type="text" class="inputFormTitle" id="ppt" placeholder="Please select a protocol" disabled/>
<div class="formHolder" id="protocolForm">
</div>
</div>
<input type="hidden" id="serialInput" name="protocolValues" value="nuttin" />
</form>
And the accompanying javascript:
var entrySubmit = $('#submitEntry');
entrySubmit.on('click', initEntrySubmission);
function initEntrySubmission(e) {
e.preventDefault();
var serializedProtocol = $("#protocolForm :input").serialize();
console.log(serializedProtocol);
$('#serialInput').val(serializedProtocol);
$('#entryForm').submit();
}
PHP Form (which I don't think is the issue but figured I would include it anyways)
<?php // add_entry.php
session_start();
include_once 'creds.php';
$con=mysqli_connect("$db_hostname","$db_username","$db_password","$db_database");
if (isset($_POST['group'])){
$lab = $_SESSION['labname'];
$author = $_SESSION['username'];
$name = $_POST['entryName'];
$group = $_POST['group'];
$protocol = $_POST['protocol'];
$permission = $_POST['permission'];
$array = $_POST['serialInput'];
$filearray = $_POST['fileArray'];
$project = $_POST['project'];
$query = "INSERT INTO data (protocol, name, lab, author, uniquearray, filearray, group, project, permissionflag)
VALUES ('$protocol', '$name', '$lab', '$author', '$array', '$filearray', '$group', 'project', '$permission')";
mysqli_query($con, $query);
mysqli_close($con);
}
?>
I wouldn't normally include so much HTML but I thought maybe I messed something up in there that may be the issue, and I just don't realize it. I tried to take out most of the break and header tags to clean up the code a bit.
Thanks for any help!
Regards.
The documentation of .submit() states, that
Forms and their child elements should not use input names or ids that conflict with properties of a form, such as submit, length, or method. Name conflicts can cause confusing failures.
You have an input that has the name submit.
<input type="submit" id="submitEntry" style="font-family:Raleway;" class="inputButton" type="button" name="submit" value="Submit Entry" />
I tried it with and without that name. It works without!
I found the following to work:
<script>
function initEntrySubmission() {
var serializedProtocol = $("#protocolForm :input").serialize();
alert(serializedProtocol);
$('#serialInput').val(serializedProtocol);
return true;
}
</script>
<form id="entryForm" action="" method="post" onSubmit="return initEntrySubmission();">
...
<input type="submit" id="submitEntry" style="font-family:Raleway;" class="inputButton" value="Submit Entry"/>
</form>
The main things to do are to add an onSubmit to your form tag. The function must return either true or false. Return true will submit the form.
Also, you do need to clean up your HTML, there are select statements in there, without closing tags and your submit button
<input type="submit" id="submitEntry" style="font-family:Raleway;" class="inputButton" type="button" name="submit" value="Submit Entry" /
has no ending >, it also has 2 type attributes type="button" and type="submit"(its both a button and a submit?) and has a name=submit, which is also unnecessary .
You don't have to preventDefault(), the Code will still be run before the Form is submitted.
function initEntrySubmission() {
var serializedProtocol = $("#protocolForm :input").serialize();
console.log(serializedProtocol);
$('#serialInput').val(serializedProtocol);
}
You can try something like below
In HTML just add
<form id="entryForm" action="add_entry.php" method="post" onsubmit="return false;">
And in JS function
function initEntrySubmission(e) {
var serializedProtocol = $("#protocolForm :input").serialize();
$('#serialInput').val(serializedProtocol);
$('#entryForm').removeAttr('onsubmit');
$('#entryForm').submit();
}
Just change:
$('#entryForm').submit();
To:
$('#entryForm')[0].submit();
Also rename your submit element as #Matmarbon has so eloquently explained.
Explanation:
$('#entryForm').submit(); simply triggers the submit event and takes you back to square one.
$('#entryForm')[0].submit(); submits the form ... more like the default action, without triggering the submit event.

how to stop the redirection of login lightbox, if username password is wrong?

lightbox
<div class="modalBody">
<form method="post" action="login.php">
<table>
<tr>
<td>User Name*</td>
<td>
<input name="fname" type="text" class="input" value="" /></td> </tr>
<tr> <td>Password</td>
<td>
<input name="password" type="password" class="input" /> </td> </tr>
<td>Not registered yet, Click here</td>
</tr>
<tr height="25"> <td colspan="2" align="center">
<input type="image" name="BtnSubmit" id="BtnSubmit" src="images/login-button.png" alt="Submit" onClick="javascript:return onSub();" style="border-width:0px;" /></a></td> </tr>
<span style="color:#FF0000" >
<?php if(isset($_REQUEST['msg']) && $_REQUEST['msg'] == 'wrong')
echo ' Please Enter Username & Password!!!!!!';
elseif(isset($_REQUEST['msg']) && $_REQUEST['msg'] == 'incorect1')
echo ' Username Or Password Is Incorrect!!!!!';
?> </span></table>
</form> </div>
javascript:
<script language="javascript" type="text/javascript">
function revealModal(divID)
{
window.onscroll = function () { document.getElementById(divID).style.top = document.body.scrollTop; };
document.getElementById(divID).style.display = "block";
document.getElementById(divID).style.top = document.body.scrollTop;
}
function hideModal(divID)
{
document.getElementById(divID).style.display = "none";
}
</script>
The thing is that if i m submitting with wrong user name & password, the page is redirecting to the header location page only changing the header location like this & the lightbox got disappeared
header('Location:'.$_SERVER['HTTP_REFERER']."?msg=wrong");
But i dont want to redirect to any page after submission if there is wrong user name or password or the fields are blank, i want to stay in that modal box with the error msg.. Any help ?? Thanks ..
First of all; you cannot change headers once HTML has been printed out. So for you to be able to set the header, you must first redirect to a new page - or reload it entirely.
However; it sounds to me like you're in need of AJAX.
When the user submits the form, a call to an AJAX function is made - which in turn, talks with another PHP file, handling the verification for the login.
If the login was successful, you will want to start the session for the user and reload the page using Javascript's: window.location.href. If the login was unsuccessful, you will want to manipulate the HTML of a given "error element" so to speak -- Or simply show an element as simple as:
<div class='formError'>Wrong Username/Password combination

Unable to set breakpoint in Chrome

I have written a simple javaScript function to validate required userName field using JS for my learning purposes.
I am facing two issues -
In submit button, onclick event handler does not invoke
checkRequired method, and form is posted back.
I am not able to set breakpoint in chrome debugger.
Even using debugger exclusively in code does not bring the control
to debugger breakpoint.
TaskManager.js
function checkRequired() {
debugger;
var userName = document.getElementById("txtUserName");
if (userName.length == 0) {
alert("username is required attribute");
return false;
}
return true;
}
AddNewUser:
<html>
<head>
<title>Add new User</title>
<style type="text/css" media="all">
button {
width: 65px;
}
</style>
<script src="TaskManager.js" type="text/javascript"></script>
</head>
<body>
<form method="post" action="AddNewUser.html" style="width: 560px; height: 850px; margin-left: 10px; margin-top: 10px">
<fieldset>
<legend>New User</legend>
<table>
<tr>
<td>
<label>User Name:</label></td>
<td>
<input type="text" id="txtUserName" name="User Name" maxlength="10" /></td>
</tr>
<tr>
<td>
<button id="btnSubmit" type="submit" onclick="checkRequired()">Add User</button>
</td>
<td>
<button id="btnCancel">Cancel</button>
</td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
Thank you for any help to resolve the issue.
If your breakpoint is not reached then the function is somehow not accessible and you should get an error in the console. Is the function in the global scope?
Here's your code, to which I made a couple of changes to let it work.
First of all the result of your handler has to be taken into account:
<button id="btnSubmit" type="submit" onclick="javaScript:return checkRequired();">
Then you have to check against .value.length inside the textbox you're trying to validate:
var userName = document.getElementById("txtUserName");
if (userName.value.length === 0) {[...]
Anyway I would advise you to use an unobtrusive approach if possible, and bind the event directly in your javascript code, instead of defining it in the markup:
var submitBtn = document.getElementById("btnSubmit");
submitBtn.onclick = function checkRequired() {
console.log('aho');
var userName = document.getElementById("txtUserName");
[...]
Check if the script file is being loaded. Put an alert at the top of the file outside the function definition.
If the alert does not display check carefully the name of your script file. Is it the same as referenced in the script tag? Is it in the same directory?

Categories

Resources