Sending a form in the modal window - php

sorry that I start this topic. I know that there were a lot of topics in this matter. But still I can not deal with it, because I need the success / failure messages to be displayed as below:
<!-- Form in modal -->
<?PHP if(isset($_SESSION['error_msg'])){echo $_SESSION['error_msg']; unset($_SESSION['error_msg']);}?>
<?PHP if(isset($_SESSION['success_msg'])){echo $_SESSION['success_msg']; unset($_SESSION['success_msg']);}?>
<form id="test-form action="test.php" method="POST">
<input type="text" name="name" placeholder="Name">
<input type="email" name="email" placeholder="Email">
<input type="submit" name="save-test-form" value="Save">
</form>
/* test.php */
<?PHP
if(isset($_POST['save-test-form'])){
if(!empty($_POST['name'])){
if(!empty($_POST['email'])){
$_SESSION['success_msg'] = 'All is well.';
}else{
$_SESSION['error_msg'] = 'Enter the email.';
}
}else{
$_SESSION['error_msg'] = 'Enter the name.';
}
}
?>
And jquery?
My point is to submit this form without reloading the page (because it's in the modal window) and I have to display success / failure messages in the form (also without reloading the page). I do not know how to do it.
I will be grateful for the help and explanation of how to do it step by step.

Your PHP script is executed on page reload, so when using Ajax you must manually show messages from server:
// PHP
$response = [];
if(isset($_POST['save-test-form'])){
if(!empty($_POST['name'])){
if(!empty($_POST['email'])){
$response['success'] = 'All is well.';
}else{
$response['error_msg'] = 'Enter the email.';
}
}else{
$response['error_msg'] = 'Enter the name.';
}
echo json_encode($response); // Format array as json and output it
die(); // No other output, just JSON
}
// jQuery
$.ajax({
url: '',
method: 'POST',
dataType: 'json',
data: {},
success: function (response) {
if (typeof response.success !== 'undefined') {
$('#responseMessage').text(response.success);
} else {
$('#responseMessage').text(response.error_msg);
}
}
})

Related

unable to redirect the url after get data from ajax

I get the data through ajax then I validate it and redirect user as per condition. Like if user login successful then redirect to dashboard otherwise redirect to restrict page. I get the result data in network console(developers tool) but I am unable to redirect to specific page.
Here is my index.php page.
<div id="loginContainer">
<form id="loginFrm" method="post">
<h3>Members Login Area</h3>
<img id="divider" src="images/divider.png">
<input type="email" name="lemail" required placeholder="Enter a valid email address">
<input name="lpassword" placeholder="Password" type="password" required>
<input type="submit" value="Sign In">
<input id="submit" type="hidden" name="submit">
<p>Forgot Password ?</p>
<p id="bottom">Don't have account? Sign up here</p>
</form>
</div>
<script>
$(document).ready(function () {
$("#loginFrm").submit(function () {
var data = $("#loginFrm").serialize();
insertRecords(data);
return false;
});
function insertRecords(data) {
$.ajax({
url: 'loginProcess.php',
data: data,
type: 'POST',
dataType: 'html',
success: function (data) {
$("#result").html(data);
},
error: function () {
alert('Error : COde not work properly');
}
});
}
});
</script>
This is my loginProcess.php page where i get the data from users input.
<?php
ob_start();
error_reporting(E_ALL);
print_r($_POST);// see all result in network console
require_once('inc/dbconnection.php');
require_once('inc/functions.php');
$emailErr = $password="";
if (isset($_POST['submit'])) {
if (empty($_POST["lemail"])) {
$emailErr = 'Please enter your email address.';
} else {
$email = filterEmail($_POST["lemail"]);
if ($email == FALSE) {
$emailErr = 'Please enter a valid email address.';
}
}
if (empty($_POST["lpassword"])) {
$passwordErr = 'Please enter your password here.';
} else {
$password = sha1($_POST['lpassword']);
}
}
// after pressing login, checking if the variables exist in the database
if (empty($emailErr) && empty($passwordErr)) {
$query = $db->prepare("SELECT password FROM users WHERE email=?");
$query->execute(array($email));
if ($query->fetchColumn() === $password) {
// starts the session created if login info is correct
session_start();
$_SESSION['email'] = $email;
header("Location: dashboard.php",true, 302);
exit;
} else {
header("Location: restrict.php",true, 302);
exit;
}
} else {
header("Location: index.php?Email=$emailErr&Password=$passwordErr",true, 302);
die;
}
ob_end_flush();
?>
Note: i've checked after remove the (true, 302) in header function
You cannot redirect in php with AJAX. You need to redirect in success function of AJAX like below:
window.location.href = 'dashboard.php'
The AJAX request will fail if the page you're fetching the result from does not contain data in a format expected by the ajax() Javscript function (caused by a redirected result page).
Why not pass the URL from PHP to the Javascript function, check if the URL to redirect to is set then redirect accordingly instead?
window.location.replace('dashboard.php');
Are you sure you should be redirecting from your PHP form processing script? I believe you should just generate the ERROR/NO ERROR response their and redirect the page from your form page by handling the AJAX response cases.

Contact form - Passing variables from PHP to jQuery

[I suspect the issue at hand has to do with how the php array gets passed to jQuery, if that isn't the case I apologize for the misleading title]
The contact form below is working -- except when I submit the forms' data, sometimes one field always keeps its red border indicating missing input, even when it actually has data.
To elaborate: I have a working php-only solution but on submit it causes a page-reload which I would like to avoid. After some research, it seems I need php/jQuery/ajax to perform these things asynchronously and to stay on the same site.
Desired behaviour:
So there are three required input fields called name, email and message, if any one is left out, it should receive a red border and no email gets sent.
Actual behaviour:
If for example only name and message are filled out and submitted, the empty email field is colored red.
But if a (valid) email is provided, the second submit action does not remove the red border around the email field.
I know that javascript and friends is a client-side language, and PHP gets processed server-side. Once the form is submitted, the .ajax function takes the serialized form values, uses 'POST' to stuff it into the php script and waits for the server to call us back inside .done()
This is where I'm lost - how is the php array to be used in jQuery?
E.g. no matter what, this line is never reached:
console.log("All fields filled and valid");
index.html:
<!DOCTYPE html>
<head>
<meta http-equiv="content-type" content="text/html" charset="UTF-8" />
<script src="jquery-1.12.4.min.js"></script>
<script src="verify.js"></script>
<style>
.input-error
{
border: 2px solid red;
}
</style>
<script>
$(document).ready(function() // Wait until website (DOM) is completely loaded
{
/* Page top */
$('#pagetop').click(function()
{
console.log(this);
$('body, html').animate({scrollTop: '0px'}, 600);
return false;
});
});
</script>
</head>
<body>
<!-- action is left blank as process.php is called from verify.js -->
<form action="" method="POST" id="contactForm">
<label for="company">Company</label>
<br>
<input type="text" style="width: 904px; height: 24px;" id="company" name="company" value="">
<br><br>
<label for="name">Name *</label>
<br>
<input type="text" style="width: 904px; height: 24px;" id="name" name="user_name" value="">
<br><br>
<label for="email">Email *</label>
<br>
<input type="text" style="width: 904px; height: 24px;" id="email" name="user_email" value="">
<br><br>
<label for="message">Message *</label>
<br>
<textarea style="width: 904px; resize: none;" rows="9" id="message" name="user_message"></textarea>
<br><br>
<input type="submit" id="submit" name="submit" value="Send">
<br><br>
</form>
</body>
verify.js
$(document).ready(function()
{
// process the form
$('#contactForm').submit(function(event)
{
//$('#name, #email, #message').removeClass('input-error');
// process the form
$.ajax(
{
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : $('#contactForm').serialize(),
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data)
{
// log data to the console so we can see
console.log(data);
if (data.errors.name)
{
console.log("Name missing");
$('#name').addClass('input-error');
}
else
{
$('#name').removeClass('input-error');
}
// handle errors for email
if (data.errors.email)
{
console.log("Email missing or invalid");
$('#email').addClass('input-error');
}
else
{
$('#email').removeClass('input-error');
}
// handle errors for message
if (data.errors.message)
{
console.log("Message missing");
$('#message').addClass('input-error');
}
else
{
$('#message').removeClass('input-error');
}
if(data.input_valid == true)
{
console.log("All fields filled and valid");
alert('success');
}
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
process.php
<?php
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// Sanitize input variables
$company = test_input($_POST['company']);
$name = test_input($_POST['user_name']);
$email = test_input($_POST['user_email']);
$message = test_input($_POST['user_message']);
// Validate the variables
// If any of these variables don't exist, add an error to our $errors array
if (empty($name))
$errors['name'] = 'Name is required.';
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL))
$errors['email'] = 'Valid Email is required.';
if (empty($message))
$errors['message'] = 'Message is required.';
$from = '--- Contact Form ---';
$to = 'some#mail.com';
$subject = 'Message from Contact Form';
$body = "From: $name\nCompany: $company\nE-Mail: $email\nMessage:\n\n$message";
// return a response ===========================================================
// if there are any errors in our errors array, return a success boolean of false
if(!empty($errors))
{
// if there are items in our errors array, return those errors
$data['input_valid'] = false;
$data['errors'] = $errors;
}
else
{
// If there are no errors process our form, then return a message
$data['input_valid'] = true;
if(mail($to, $subject, $body, $from))
{
$data['message'] = 'Thank you for your message!';
$data['mail_sent'] = true;
}
else
{
$data['message'] = 'Message could not be sent - please try again later.';
$data['mail_sent'] = false;
}
}
// return all our data to an AJAX call
echo json_encode($data);
// Convert special characters to html entities to prevent XSS attacks
// Also remove white-space and backslashes
function test_input($val)
{
$val = trim($val);
$val = stripslashes($val);
$val = htmlspecialchars($val);
return $val;
}
?>
It looks like if all validations pass in your php script, then data['errors'] is never defined. This might cause an error to be thrown (that you can see in the browser console) in the javascript when you write:
if (data.errors.name)
data.errors will evaluate to undefined in javascript, and when you try to access a property of undefined like data.errors.name, it will throw an error and stop the script.
To fix this, you probably just need to define errors in your php script, (though I'm not 100% sure the JSON methods won't leave out an empty array...). Try doing this in your php script:
if(!empty($errors))
{
// if there are items in our errors array, return those errors
$data['input_valid'] = false;
$data['errors'] = $errors;
}
else
{
// If there are no errors process our form, then return a message
$data['input_valid'] = true;
$data['errors'] = $errors; // even though it is empty
// etc
EDIT:
I don't know if it will work with your jquery version but just in case it doesn't, place this code in your header:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
I used the below code and it worked. Sent the email without having to change the PHP code:
$(document).ready(function() {
$('#contactForm').submit(function(event) {
$.ajax({
type: 'POST',
url: 'process.php',
data: $('#contactForm').serialize(),
dataType: 'json',
encode: true
})
.done(function(data) {
console.log(data);
if(data.input_valid == true) {
console.log("All fields filled and valid");
// If the function is a success remove error classes from all fields
// you can either place the below code above the alert so that it happens
// before you get the success message, or after.
$('#name').removeClass('input-error');
$('#email').removeClass('input-error');
$('#message').removeClass('input-error');
alert('success');
} else {
if (data.errors.name) {
console.log("Name missing");
$('#name').addClass('input-error');
} else {
$('#name').removeClass('input-error');
}
if (data.errors.email) {
console.log("Email missing or invalid");
$('#email').addClass('input-error');
} else {
$('#email').removeClass('input-error');
}
if (data.errors.message) {
console.log("Message missing");
$('#message').addClass('input-error');
} else {
$('#message').removeClass('input-error');
}
}
});
event.preventDefault();
});
});

Checking and submitting form via Ajax in boostrap modal

I have a login form in boostrap's modal window
<form method="post" id="loginForm" action="index.php">
<label for="email">Email:</label>
<input class="form-control" type="text" name="email" value="" id="emailLogin"/><br/>
<label for="password">Password:</label>
<input class="form-control" type="password" name="password" value="" id="passwordLogin"/><br/>
<div id="loginAlert" class="alert alert-danger" role="alert">Email or password incorrect</div> <!-- Hidden by default -->
<button type="submit" name="login" class="btn btn-primary" id="loginButton">Login</button>
<script src="checkLoginForm.js"></script></form>
I would like to check this form (if email and password are correct) before submitting it. If the function, which checks the email and password returns 1, there is something incorrect. Form should not submit in this case and it should just make the alert visible.
If everything is correct, it should submit.
Thing is: I can prevent the form from submitting, if the the email and password are incorrect, but I can't submit it, if they are correct. Here is the code from checkLoginForm.js
$(document).ready(function() {
$("#loginForm").submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'include/ajax.php?action=checkLogin',
data: {
email: $("#emailLogin").val(),
password: $("#passwordLogin").val(),
},
success: function(result) {
console.log(result);
if(result == 0) {
} else {
$("#loginAlert").css({"display": "block"});
}
}
});
});
});
I have no idea what to do, when the result == 0. If I do $("loginForm").submit();, that does not submit the form (else part does work).
Thank you for your replies.
I would advice you to use a simple $.post, it's a shorthand way of using $.ajax for POST requests. Just check if the values provided are correct in your php file, if they are correct process that data and return true or redirect the user to another page else return false.
$(document).ready(function() {
$("#loginButton").on('click', function (e){
e.preventDefault();
var email = $("#emailLogin").val();
var passwd = $("#passwordLogin").val();
$.post('include/ajax.php?action=checkLogin', {email: email, password: passwd}, function (data) {
var res = $.parseJSON(data);
if (res.result == true) {
//you can redirect the or display a message to the user.
//redirect the user to another page
//$("#loginAlert").css({"display": "block"}).html("login successful");
}else {
$("#loginAlert").css({"display": "block"});
}
});
});
});
Then in your php file
if (isset($_GET['action']) && $_GET['action'] == 'checkLogin') {
$passwd = trim(filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING));
$email = trim(filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL));
//validate inputs here
//get data from db
//then compare values
//if values match return true
//$db_mail and $db_passwd are from the db.
if ($email == $db_mail && $passwd == $db_passwd) {
//if the provided information is correct
//process it here, login the user.
//redirect if necessary.
// or return results to JS
echo json_encode(['result' => true]);
} else {
//if the information is wrong return false to JS
//and alert the user
echo json_encode(['result' => false]);
}
}

Ajax login box doesn't call PHP file to continue process

The Ajax function for logging in and validating doesn't seem to get to the .php file for validation.
I'm new to both JS and Ajax and followed a few online tutorials, I then tried to implement this with what I had in place already and the problems started.
I've put an echo at the top of the page that Ajax calls, it never gets displayed. I've typed into url to be sure and it works fine. (displays the echo)
I've gone over the code a few times and can't see any obvious errors but then I'm not entirely certain of what I should be looking for.
If I leave the PHP in the 'header' of the HTML page it works fine but I understand this is bad practice. Grateful for any help.
HTML:
<form method="post" action="" id="ourLoginFormID_JS">
<div class="ourContactFormElement2">
<label for="username">Username:</label>
<input type="text" id="username" name="username" autocomplete="off" class="required" value="<?php if(isset($_POST['username'])) echo htmlentities($_POST['username']); ?>" />
</div>
<div class="ourContactFormElement2">
<label for="password">Password:</label>
<input type="password" id="password" name="password" autocomplete="off" class="required"/>
</div>
<div class="ourContactFormElement2">
<label> </label>
<input type="submit" name="loginButton" id="loginButton" value="Login!" onclick="validLogin()"/>
</div>
<div id="statusLogin"></div>
</form>
The Ajax:
function validLogin(){
$('.error').hide();
var username = $('#username').val();
if(username == ""){
$('label#usernameError').show();
$('input#username').focus();
return false;
}
$('.error').hide();
var password = $('#password').val();
if(password == ""){
$('label#passwordError').show();
$('input#password').focus();
return false;
}
var params = "username="+username+"&password="+password;
var url = "loginProcessAjax.php";
$("#statusLogin").show();
$("#statusLogin").fadeIn(400).html('<img src="image/loading.gif" />');
$.ajax({
type: 'POST',
url: url,
dataType: 'html',
data: params,
beforeSend: function() {
document.getElementById("statusLogin").innerHTML= 'checking...' ;
},
complete: function() {
},
success: function(html) {
$("#statusLogin").hide();
document.getElementById("statusLogin").innerHTML= html;
if(html=="success"){
window.location = "index.php"
}
}
});
}
PHP - I understand there may be some conflicting issues on this page but it doesn't get that far, however if you've any pointers that'd also be fantastic.
<?php
//check fields are filled in
echo "HULLOOOO!!!!!"; // doesn't display when run in function but ok from url
if(empty($_POST) === false){
$username = trim($_POST['username']);
$password = trim($_POST['password']);
//validate fields
if(empty($username) === true || empty($password) === true){
$errors[] = 'Your username and password are needed.';
}else if($users->userExists($username) === false){
$errors[] = 'That username does not exist';
}else if($users->emailActivated($username) === false){
$errors[] = 'You need to activate the account, please check your email.';
}else{
//start login
$login = $users->login($username, $password);
if($login === false){
$errors[] = 'That username or password is invalid';
//
// if(empty($errors) === false){
// echo '<p>' .implode('</p><p>', $errors).'</p>';
// }
}else{
//destroy old session and create new - prevents session fixation attacks
session_regenerate_id(true);
//all details are correct - the method returns the id to be sotred as a session
$_SESSION['id'] = $login;
//send user to their home page
echo "success";
header('Location: userHome.php');
exit();
}
}
}
Your data to the post request is not formatted in the right way. Use {'property1': 'value1', etc}.
First try to display the data with PHP, make it more complex when you're sure the connection between jQuery and PHP is working well.
Use Firebug or developer tools to see if there errors occur.

$.post function for login form in lightbox

So, I have a login form set in a lightbox. I want that when users click on submit, a function check if the username and password are correct before refreshing and go to the member page. It should also show the errors in the lightbox.
I have a problem with the jQuery part more particularly with the $.post function.
jQuery code:
$('#Connection form').submit('Connection',function(){
var Username = $('#UsernameConnection').val();
if(Username=="")
{
$('#UsernameConnection').css('border-color','red');
$('.ErrorUsernameConnection').text('Error 1');
Username = "Empty Field";
}else
if(Username=="Invalid")
{
$('#UsernameConnection').css('border-color','orange');
$('.ErrorUsernameConnection').text('Error 2');
Username = "Invalid field";
}
var Password = $('#Password Connection').val();
if(Password =="")
{
$('#Password Connection').css('border-color','red');
$('.ErrorPassword Connection').text('Error 3');
Password = "Empty field";
}
if((Username==true)&&(Password==true))
{
$.post('fonctions/connection.php',{VALUE1:VALUE2},function(connection)
{
$('.ConnectionError').text(connection);
if(connection=="ok")
{
return true;
}else
{
return false;
}
});
}else
{
return false;
}
});
});
PHP code:
if(isset($_POST['Connection']))
{
all the verifying function goes here.
}
and HTML:
<div id="Connection">
<div class="formConnection">
<form method="POST" autocomplete="off" name="Connection">
<label for="Connection">Username:</label><br/>
<input type="text" name="UsernameConnection" id="UsernameConnection"/><br/>
<span class="ErrorUsernameConnection"></span><br/>
<label for="Connection">Password:</label><br/>
<input type="password" name="PasswordConnection" id="PasswordConnection"/>
<span class="ErrorPasswordConnection"></span><br/>
<input type="checkbox" name="checkbox"/><label>Remember me</label><br/>
<input type="submit" name="Connection" value="Log In" id="Connection" class="LogIn"/>
</form>
</div>
</div>
My question are:
Is $.post the right function for this? If yes,:
Because the script only starts when users click in the submit button, is it necessary to create a new var in the jQuery just for the submit button?
Is the if(isset($_POST['Connection'])) part in the php necessary in this case or can I just put the function right away?
What should VALUE1 and VALUE2 be for this to work?
I think this is what you want to do:
$('#Connection form').submit('Connection',function(){
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", password: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
Basically, you can just serialize your form and post it to the page. Have the page send back a message (success or fail, 1 or 0) and then do something with that data.
I think you're over-complicating matters. You just want to post a form via AJAX—the easiest way to do this is as follows:
$('#login-form').submit(function() {
$.post('login.php', $(this).serialize(), function(response) {
// do something on success or failure here
});
return false;
});
Have your login.php echo a JSON object, or true or false, and display any errors in your lightbox or whatever.

Categories