preventDefault() won't work with form.submit() - javascript

I'm trying to get my login form to either close my lightbox, or change the text of an errorbox depending on whether or not the login attempt was a success. I'm not sure, but i think it has to do with my
onclick="formhash(this.form, this.form.password);"
which is a JS function that hashes a password, then continues the form submit. it ends with
form.submit();
Here's my code:
HTML:
<form action="includes/process_login.php" method="post" name="login_form">
Email: <input class="searchform" type="text" name="email" size="20"/><br />
Password: <input class="searchform" type="password" name="password" id="password" size="20"/><br />
<input type="button" class="searchform"
value="Submit" size="40" style="height:45px; width:90px"
onclick="formhash(this.form, this.form.password);" />
<input type="text" id="errorbox" style="height:45px; width:180px" value=""><br>
</form>
JS:
<script>
!(function($){
$(function() {
$('form[name="login_form"]').on('submit', function(event){
event.preventDefault();//don't reload the page
$.post('includes/process_login.php', $(this).serialize(), function(data){
//data is a json object which contans the reponse
data = $.parseJSON(data);
$("fade").fadeOut();
$("light").fadeOut();
},
function(data){//error callback
data = $.parseJSON(data);
if(data.forbidden){
$("#errorBox").html("Error!");
}
else if(data.error){
$("#errorBox").html("Invalid request!");
}
});
});
return false;
});
})(window.jQuery);
</script>
PHP:
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start(); // Our custom secure way of starting a PHP session.
$response = array();
if (isset($_POST['email'], $_POST['p'])) {
$email = $_POST['email'];
$password = $_POST['p'];
if (login($email, $password, $mysqli) == true) {
http_response_code(200);//HTTP OK, requires php 5.4
$response['success'] = true;
} else {
// Login failed
$response['error'] = true;
http_response_code(401);//HTTP forbidden
}
} else {
// The correct POST variables were not sent to this page.
$response['error'] = true;
http_response_code(400);//HTTP bad request
}
echo json_encode($response);
When I log in, the preventDefault() doesn't work. It opens process_login.php in a new page and displays "{"success":true}" on a blank page. Any suggestions? (keeping in mind that it needs to be as secure as possible)

You could try moving it all into a single handler call. By changing the type="button" to type="submit" on your form.
<form action="includes/process_login.php" method="post" name="login_form">
Email: <input class="searchform" type="text" name="email" size="20"/><br />
Password: <input class="searchform" type="password" name="password" id="password" size="20"/><br />
<input type="submit" class="searchform" value="Submit" size="40" style="height:45px; width:90px" />
<input type="text" id="errorbox" style="height:45px; width:180px" value=""><br>
Then you could move your formhash function into the submit function
!(function($){
$(function() {
$('form[name="login_form"]').on('submit', function(event){
event.preventDefault();//don't reload the page
formhash(var1, var2);
$.post('includes/process_login.php', $(this).serialize(), function(data){
//data is a json object which contans the reponse
data = $.parseJSON(data);
$("fade").fadeOut();
$("light").fadeOut();
},
...//the rest of your code

Related

Showing "Thank you message" with AJAX and running php script

I have a form and I want when someone click submit, run upis.js write thank you message and run php script for inserting into database. For now it takes values I can see them in my url but it doesnt run upis.php. Can you tell me why?
Here is the code for form:
<form>
<label>Ime</label>
<input type="text" name="ime" id="ime" required><br>
<label>Prezime</label>
<input type="text" name="prezime" id="prezime" required><br>
<label>Ime slavljenika</label>
<input type="text" name="ime_slavljenik" id="ime_slavljenik" required><br>
<label>Prezime slavljenika</label>
<input type="text" name="prezime_slavljenik" id="prezime_slavljenik" required><br>
<label>Kontakt email</label>
<input type="email" name="email" id="email" required>
<button onclick="return upis()">Posalji</button>
<div id="placefortableanketa">
</div><br><br>
</form>
and upis.js
<script>
function upis(){
var ime = document.getElementById("ime").value;
var prezime = document.getElementById("prezime").value;
var ime_slavljenik = document.getElementById("ime_slavljenik").value;
var prezime_slavljenik = document.getElementById("prezime_slavljenik").value;
var email = document.getElementById("email").value;
var dataString = "ime="+encodeURIComponent(ime)+"&prezime="+encodeURIComponent(prezime)+"&ime_slavljenik="+encodeURIComponent(ime_slavljenik)+"&prezime_slavljenik="+encodeURIComponent(prezime_slavljenik)+"&email="+encodeURIComponent(email);
$.ajax({
type:"post",
url: "upis.php",
cashe: false,
data: dataString,
success: function(data){
//window.alert(data);
document.getElementById("placefortableanketa").innerHTML = data;
},
error: function (req, status, err) {
console.log('Something went wrong', status, err);
}
})
return false;
}
</script>
and upis.php
<?php
require_once 'include/db.php';
require_once 'include/functions.php';
$allowed_params = allowed_post_params(['ime', 'prezime', 'ime_slavljenik', 'prezime_slavljenik', 'email','submit']);
// niz sadrzi dozvoljene maksimalne duzine za sva polja
$fields_lengths = ['ime' => 64, 'prezime' => 64, 'ime_slavljenik'=>64, 'prezime_slavljenik'=>64, 'email' => 64];
// provera da li su polja odgovoarajuce duzine
foreach ($fields_lengths as $field => $length) {
if (!has_length($_POST[$field], ['min' => 0, 'max' => $length])) {
header('Location: greska.html');
die();
}
}
try {
// Priprema upita za unos podataka u bazu
$prep = $db->prepare("INSERT INTO prijavljeni (ime, prezime, ime_slavljenik, prezime_slavljenik, email) VALUES(:ime, :prezime, :ime_slavljenik, :prezime_slavljenik, :email)");
$prep->bindParam(':ime', $ime);
$prep->bindParam(':prezime', $prezime);
$prep->bindParam(':ime_slavljenik', $ime_slavljenik);
$prep->bindParam(':prezime_slavljenik', $prezime_slavljenik);
$prep->bindParam(':email', $email);
$ime = isset($allowed_params['ime']) ? $allowed_params['ime'] : "";
$prezime = isset($allowed_params['prezime']) ? $allowed_params['prezime'] : "";
$ime_slavljenik = isset($allowed_params['ime_slavljenik']) ? $allowed_params['ime_slavljenik'] : "";
$prezime_slavljenik = isset($allowed_params['prezime_slavljenik']) ? $allowed_params['prezime_slavljenik'] : "";
$email = isset($allowed_params['email']) ? $allowed_params['email'] : "";
// izvrsavanja upita
$rez = $prep->execute();
$htmltable = "Hvala na poslatoj prijavi.";
echo $htmltable;
} catch (PDOException $e) {
echo 'greska kod upita';
}
?>
I cant see what can be problem here because js takes values from form but doesnt actually run upis.php(it doesnt take url upis.php) I dont understand why..
If you're developing your application using Firefox or Chrome look in the network tab of web inspector to ensure the JavaScript resource successfully sends an XHR request. Check the URL that the POST XHR request is sent to.
Is the URL set correctly in the url property of the AJAX settings?
You may need to prepend "upis.php" with a forward slash e.g. "/upis.php"
You should call script from index.php, you missed action and method in form
<form action="upis.php" method="post">
<label>Ime</label>
<input type="text" name="ime" id="ime" required><br>
<label>Prezime</label>
<input type="text" name="prezime" id="prezime" required><br>
<label>Ime slavljenika</label>
<input type="text" name="ime_slavljenik" id="ime_slavljenik" required><br>
<label>Prezime slavljenika</label>
<input type="text" name="prezime_slavljenik" id="prezime_slavljenik" required><br>
<label>Kontakt email</label>
<input type="email" name="email" id="email" required>
<button onclick="return upis()">Posalji</button>
<div id="placefortableanketa">
</div><br><br>
</form>

Preventing page refresh on form submission stops code from executing

I have read so many solutions about preventing page reload from form submission, most of them are to return false with a "JQuery script" or preventDefault().
The problem is, if you prevent the page reload with Javascript or JQuery, the code won't be executed, so in my case, the email will not be sent. So, how could I run both?
Here is my HTML form.
<form id="myform" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<p><input class="w3-input w3-padding-16" type="text" placeholder="name" required name="name"></p>
<p><input class="w3-input w3-padding-16" type="email" placeholder="email" required name="email"></p>
<p><input class="w3-input w3-padding-16" type="text" placeholder="subject" required name="subject"></p>
<p><input class="w3-input w3-padding-16" type="text" placeholder="comment" required name="comment"></p>
<p>
<button class="w3-button w3-light-grey w3-padding-large" type="submit">
<i class="fa fa-paper-plane"></i> SEND MESSAGE
</button>
My PHP code to collect data and send email:
<?php
$name = $email = $comment = $subject = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = form($_POST["name"]);
$email = form($_POST["email"]);
$subject = form($_POST["subject"]);
$comment = form($_POST["comment"]);
$to = "myemail#gmail.com";
mail($to,$subject,$comment,$email);
}
function form($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
My JQuery:
$(document).ready(function() {
$(document).on('submit', '#myform', function() {
return false;
});
});
I got this from here
http://remotephpdevelopers.com/blog/prevent-form-submission/
seems like something you are looking for. You just need to pass event through. Hope this helps
$(“#submitButton”).click(function(event){
event.preventDefault();
//do your thing
});
Please use $.ajax method for this without page load:
$("#btn").click(function()
{
$.ajax({
type : 'POST',
url : 'url',
data : $('#form').serialize()
});
});

Access POST values sent by Ajax in PHP

I'm using Ajax to get POST values from a form. However, when I try to insert the form values in a database on submit, it doesn't get inserted. I still have no idea why it does not work.
Here is my HTML
<form method="post" action="" id="home-sign-up-form">
<input type="text" name="suFirstName" placeholder="First Name" class="text-input-minor" id="sign-up-first-name-text-input">
<input type="text" name="suLastName" placeholder="Last Name" class="text-input-minor" id="sign-up-last-name-text-input">
<input type="text" name="suEmail" placeholder="Email" class="text-input-minor" id="sign-up-email-text-input">
<input type="password" name="suPassword" placeholder="Password" class="text-input-minor" id="sign-up-password-text-input">
<input type="password" name="suConfirmPassword" placeholder="Confirm Password" class="text-input-minor" id="sign-up-confirm-password-text-input">
<input type="text" name="suDisplayName" placeholder="Display Name (you can change this later)" class="text-input-minor" id="sign-up-display-name-text-input">
<br><font class="text-error" id="sign-up-error-text"></font><br>
<label><input type="checkbox" name="suRememberMe" value="yes" id="sign-up-remember-me-checkbox"><font id="sign-up-remember-me-text">Remember me</font></label>
<input name="signUp" type="submit" value="Sign Up" id="sign-up-submit">
</form>
My JS (the first console.log does go through and work):
if (validForm)
{
console.log("valid form");
console.log(JSON.stringify($('#home-sign-up-form')[0].seriaize()));
$.ajax(
{
type:'POST',
url:'form-submit.php',
data:$('#home-sign-up-form')[0].serialize(),
success:function(response)
{
$suForm.hide();
$tosppText.hide();
$mailSentIcon.show();
$emailSentText.show();
$emailSentTextEmail.text($suEmail);
$suBox.css("padding-left", "10px");
$suBox.css("padding-right", "10px");
}
});
}
And my PHP/MySQL:
<?php require 'dbconnect.php'; ?>
if (isset($_POST['suEmail']))
{
echo "<script type='text/javascript'>alert('got');</script>";
$suFirstName = mysqli_real_escape_string($_POST['suFirstName']);
$suLastName = mysqli_real_escape_string($_POST['suLastName']);
$suEmail = mysqli_real_escape_string($_POST['suEmail']);
$suPassword = mysqli_real_escape_string($_POST['suPassword']);
$suDisplayName = mysqli_real_escape_string($_POST['suDisplayName']);
$code = substr(md5(mt_rand()),0,15);
$query = $connection->query("INSERT INTO users (firstName,lastName,email,password,displayName,confirmCode,verified)Values('{$suFirstName}','{$suLastName}','{$suEmail}','{$suPassword}','{$suDisplayName}','{$confirmCode},'{$verified}')");
}
The alert in the PHP code so I would assume that it isn't getting the 'signUp' POST variable. Thanks so much! Any help is appreciated! :D
$("#home-sign-up-form").submit(function(event) {
alert("Handler for .submit() called.");
event.preventDefault();
$.ajax({
type: 'POST',
url: 'form-submit.php',
data: $('#home-sign-up-form').serialize(),
success: function(response) {
console.log(response);
var data = JSON.parse(response);
$suForm.hide();
$tosppText.hide();
$mailSentIcon.show();
$emailSentText.show();
//$emailSentTextEmail.text($suEmail);
$emailSentTextEmail.text(data.suEmail);
$suBox.css("padding-left", "10px");
$suBox.css("padding-right", "10px");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<form method="post" action="" id="home-sign-up-form">
<input type="text" name="suFirstName" placeholder="First Name" class="text-input-minor" id="sign-up-first-name-text-input">
<input type="text" name="suLastName" placeholder="Last Name" class="text-input-minor" id="sign-up-last-name-text-input">
<input type="text" name="suEmail" placeholder="Email" class="text-input-minor" id="sign-up-email-text-input">
<input type="password" name="suPassword" placeholder="Password" class="text-input-minor" id="sign-up-password-text-input">
<input type="password" name="suConfirmPassword" placeholder="Confirm Password" class="text-input-minor" id="sign-up-confirm-password-text-input">
<input type="text" name="suDisplayName" placeholder="Display Name (you can change this later)" class="text-input-minor" id="sign-up-display-name-text-input">
<br><font class="text-error" id="sign-up-error-text"></font>
<br>
<label>
<input type="checkbox" name="suRememberMe" value="yes" id="sign-up-remember-me-checkbox"><font id="sign-up-remember-me-text">Remember me</font>
</label>
<input name="signUp" type="submit" value="Sign Up" id="sign-up-submit">
</form>
<?php
if (isset($_POST['suEmail']))
{
$con=mysqli_connect("localhost","root","cakpep","backoffice");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$suFirstName = mysqli_real_escape_string($con,$_POST['suFirstName']);
$suLastName = mysqli_real_escape_string($con,$_POST['suLastName']);
$suEmail = mysqli_real_escape_string($con,$_POST['suEmail']);
$suPassword = mysqli_real_escape_string($con,$_POST['suPassword']);
$suDisplayName = mysqli_real_escape_string($con,$_POST['suDisplayName']);
$code = substr(md5(mt_rand()),0,15);
$query = $connection->query("INSERT INTO users (firstName,lastName,email,password,displayName,confirmCode,verified)Values('{$suFirstName}','{$suLastName}','{$suEmail}','{$suPassword}','{$suDisplayName}','{$confirmCode},'{$verified}')");
echo json_encode($_POST);
}
?>
add this to trigger when submit form
$("#home-sign-up-form").submit(function(event) {
and then on php return the response with json string
echo json_encode($_POST);
and then in the response ajax parse json text to object like this
var data = JSON.parse(response);
$emailSentTextEmail.text(data.suEmail);
i hope this what you want..

Page refresh after login?

I am trying to get my page to refresh after login this is the format of my index.php
<?php
if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username']))
{
// let the user access the main page
// i have made the main content with jquery mobile framework
}
elseif(!empty($_POST['username']) && !empty($_POST['password']))
{
// let the user login
include "login.php";
}
else
{
// display the login form
<form method="post" action="index.php" name="loginform" id="loginform">
<fieldset>
<label for="username">Username:</label><input type="text" name="username" id="username" /><br />
<label for="password">Password:</label><input type="password" name="password" id="password" /><br />
<input type="submit" name="login" id="login" value="Login" />
</fieldset>
</form>
Inside my login.php
<?php
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$checklogin = mysql_query("SELECT * FROM users WHERE Username = '".$username."' AND Password = '".$password."'");
if(mysql_num_rows($checklogin) == 1)
{
$row = mysql_fetch_array($checklogin);
$email = $row['email'];
$uid = $row['u_id'];
$_SESSION['Username'] = $username;
$_SESSION['EmailAddress'] = $email;
$_SESSION['LoggedIn'] = 1;
$_SESSION['uid'] = $uid;
$flag=1;
header("Location: http://5aday.dihops.net/index.php");
// echo "<meta http-equiv=\"refresh\" content=\"0;index.php\">";
//header("Refresh: 2; url=http://5aday.dihops.net/index.php");
// THIS IS WHERE I AM STUCK
}
else
{
echo "<h1>Error</h1>";
echo "<p>Sorry, your account could not be found. Please click here to try again.</p>";
}
?>
}
?>
I dont know what I am doing wrong. But once the user gives his username and password and submits it .... I get a blank page. and the user has to manually refresh the webpage to see the content of the webpage.
As per the link mentioned the header(location) must be placed at the top of the page ... So I rearranged the if conditions ....
I added this at the top of the index.php
if(!empty($_POST['username']) && !empty($_POST['password']))
{
include "login.php";
} ?>
then in the body i added the other if statements
if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username']))
{
// let the user access the main page
// i have made the main content with jquery mobile framework
}else
else
{
// display the login form
<form method="post" action="index.php" name="loginform" id="loginform">
<fieldset>
<label for="username">Username:</label><input type="text" name="username" id="username" /><br />
<label for="password">Password:</label><input type="password" name="password" id="password" /><br />
<input type="submit" name="login" id="login" value="Login" />
</fieldset>
</form>
}
That has fixed the problem.
You have no content under:
if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username']))
{
// let the user access the main page
// i have made the main content with jquery mobile framework
}
So.. when you log in, there's nothing to see.
It doesn't seem there's any HTML elements for JavaScript to grab a handle on and edit either. Unless you're using JavaScript to then create elements from scratch. If so, have you checked that the JavaScript has even loaded? Also, check for errors in the console.
Try this code
<?php
if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username']))
{
echo "Welcome".$_SESSION['Username'];
}
elseif(!empty($_POST['username']) && !empty($_POST['password']))
{
// let the user login
include "login.php";
}
else
{
// display the login form
<form method="post" action="index.php" name="loginform" id="loginform">
<fieldset>
<label for="username">Username:</label><input type="text" name="username" id="username" /><br />
<label for="password">Password:</label><input type="password" name="password" id="password" /><br />
<input type="submit" name="login" id="login" value="Login" />
</fieldset>
</form>
Try using PHP_SELF for redirect the same page
header('Location:'.$_SERVER['PHP_SELF']);
it might help
Stay page after Login, Refresh page. try JAVASCRIPT in php
echo "<script>window.location.replace('/')</script>";

Form values via AJAX to PHP first being cut off and then not being recognized

Submitting the following form:
<form name="register" method="post" onSubmit="registerUser();">
<fieldset>
<label for="user_name">Name</label>
<input name="user_name" type="text" id="user_name" placeholder="Name" />
<label for="user_email">Email</label>
<input name="user_email" type="email" id="user_email" placeholder="Email"/>
<label for="user_password">Password</label>
<input name="user_password" type="password" id="user_password" placeholder="Password" />
<input name="s" type="hidden" value="register" />
</fieldset>
<input type="submit" value="Register" />
</form>
via AJAX
function registerUser(){
var myform = $("form[name='register']"),
data = {};
myform.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: urlService,
type: 'POST',
data: data,
success: function(response){
}
});
return false;
}
The "s" value of "register was being cut off to "regist" when echoed in following PHP statement. So in an effort correct it I escaped the values as so in the prior jQuery statement:
value = escape(that.val());
This then allowed the full value to be passed, although adding "%20" to the name value. I continued as follows...
forwarded on to PHP
print_r($_POST);
try{
$db = new PDO('mysql:host=' . $dbhost . ';dbname=' . $dbname, $dbuser, $dbpass);
switch($_POST['s']){
case 'register':
$response = 'registered ok + ';
break;
case 'login':
break;
}
$response = 'services read';
echo $response;
} catch(PDOException $e){
echo $e->getMessage();
}
At this point all of the $_POST values are being echoed, HOWEVER the value of "register" is not being recognized by the SWITCH statement.
I am not sure what I am doing incorrectly nor at which point... any help in cleaning up these glitches would be greatly appreciated.

Categories

Resources