Using AJAX when submitting forms - javascript

I'm very new to form submission with AJAX and have been following many tutorials on it's use, however I cannot seem to get it working in my current scenario.
I have a modal with a form inside of it linked to a PHP script and some JQuery AJAX.
When i submit the form the page appears white, I'm fairly sure this is because of the conditional logic in my PHP script.
So, where I have $stmt->rowCount() and the conditional logic it returns nothing as the script does nothing at this point.
Can I link this logic to AJAX success or failure or do I have to return a boolean from my script?
I know this is probably considered a silly question but some clarity would be of great use.
Form
<form id="userForm" method="post" action="test/process_data.php">
<div class="form-group">
<label for="email">First name:</label>
<input type="text" class="form-control" name="forename" id="forename" placeholder="E.g John" required>
</div>
<div class="form-group">
<label for="email">Surname:</label>
<input type="text" class="form-control" name="surname" id="surname" placeholder="E.g Smith" required>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" name="email" id="email" placeholder="someone#example.com">
</div>
<div class="form-group">
<label for="company">Company:</label>
<input type="text" class="form-control" name="company" id="company" placeholder="Company name">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
Just take me to the partner
</form>
AJAX Script
<script>
$("#userForm").submit(function(e) {
var forename = $('#forename').val();
var surname = $('#surname').val();
var email = $('#email').val();
var company = $('#company').val();
$.ajax({
url: "process_data.php",
type: "POST",
data: {
"forename" : forename,
"surname" : surname,
"email" : email,
"company" : company
},
success: function(data){
$("#forename").val('');
$("#surname").val('');
$("#email").val('');
$("#company").val('');
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
}
</script>
PHP Script to handle data
if (empty($_POST["forename"]) ||
empty($_POST["surname"]) ||
empty($_POST["email"]) ||
empty($_POST["company"]))
{
}
else{
$forename = $_POST['forename'];
$surname = $_POST['surname'];
$email_address = $_POST['email'];
$company_name = $_POST['company'];
$id = rand();
$date_time = date('Y-m-d');
try
{
// Construct the SQL to add a book to the database
$sql = "INSERT INTO user_data (forename, surname, email_address, company_name, id, date_time)
VALUES (:forename, :surname, :email_address, :company_name, :id, :date_time)";
// Prepare the SQL and bind parameters
$stmt = $conn->prepare($sql);
$stmt->bindParam(':forename', $forename);
$stmt->bindParam(':surname', $surname);
$stmt->bindParam(':email_address', $email_address);
$stmt->bindParam(':company_name', $company_name);
$stmt->bindParam(':id', $id);
$stmt->bindParam(':date_time', $date_time);
$stmt->execute();
// If the statement affected the database
if ($stmt->rowCount() > 0)
{
}
else{
}
} catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
}

Use serialize() method on the form to define the data property in your ajax call. Also added error handling.
$.ajax({
url: "process_data.php",
type: "POST",
data: $("#userForm").serialize(),
success: function(data){
//Successful
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
if (!window.console) console = { log: function () { } };
console.log(JSON.stringify(XMLHttpRequest), textStatus, errorThrown);
}
});

Use preventDefault(); before sending ajax request. Now when the form is done submitting you can do like this.
<script>
$("#userForm").submit(function(e) {
var forename = $('#forename').val();
var surname = $('#surname').val();
var email = $('#email').val();
var company = $('#company').val();
e.preventDefault(); // avoid to execute the actual submit of the form.
$.ajax({
url: "process_data.php",
type: "POST",
data: {
"forename" : forename,
"surname" : surname,
"email" : email,
"company" : company
},
success: function(data){
}
});
$("#userForm").fadeOut(800, function()
{
$(this)[0].reset();
}).fadeIn(800);
}
</script>

Related

JavaScript Misbehaviour

I am trying to send my form data to an .php file with AJAX but JS is misbehaving
, what actually happens is that when i leave the input fields empty every thing works fine (i.e. the php program executes and make changes in my database as expected) but when i fill form data , like when i fill name , email ,password my client side page refreshes and php file dosent gets executed .
Sorry for any grammatical mistakes .
I appreciate any help from anyone !
Thanks alot !
var form = document.getElementById("form_signup");
var formdata = new FormData(form);
$('#form_signup').on('submit', function(ev) {
console.log(formdata);
ev.preventDefault();
$.ajax({
url: "./process_php/Signup1.php",
data: $('form').serialize(),
cache: false,
processData: false,
contentType: false,
type: "POST",
success: function(response) {
console.log("done" + response);
}
});
return false;
});
<?php
if (!isset($_REQUEST['username'])) {
die();
}
$username = "temp_username";
$email = "temp_email";
$password = "temp_password";
$sqlconnection = new mysqli("", "", "", "");
$insertstatement = "INSERT INTO new_users (Name , Email , Password , Subscriber ) VALUES ('$username' , '$email' , '$password' , 'Normal' ) ";
if ($sqlconnection->query($insertstatement) === TRUE) { //if entered into db successfully
echo "DONE";
}else {
//run js to inform
}
?>
<!--I have loaded jquery and also my external js file-->
<form class="font1" id="form_signup">
<!-- main content , signup form -->
<h2 id="form_name" class="font1">LOGIN</h2>
<input type="text" name="username" placeholder="Username" minlength="3" autofocus id="username"><br>
<input type="email" name="email" placeholder="Email" minlength="10"><br>
<input type="password" name="pass" placeholder="Password" minlength="8"><br>
<input type="submit" value="Confirm">
</form>
Seems problem with $('form').serialize(). Here form is not the one same as var form = document.getElementById("form_signup");
$('#form_signup').on('submit', function(ev) {
console.log(formdata);
ev.preventDefault();
$.ajax({
url: "./process_php/Signup1.php",
data: $('#form_signup').serialize(),
// rest of the code

jQuery AJAX POST request to PHP must be submitted twice to work

We are building a basic login form that redirects to different pages based on user credentials.
For some reason, we cannot get our login form to return an employee-type value and redirect to the proper page unless we submit the same information twice (the first time, it throws everything into the URL, kind of like a GET request, except that it's writing it to the URL before anything else, even the "#").
We are using Vue.js, but I don't know that it's really relevant to the issue at hand, except that it means the HTML and JS are in the same "component" file.
HTML:
<form class="login-form" id="loginform">
<div class="form-group space">
<label class="float-label" for="username">Username</label>
<input type="username" name="username" id="username" class="form-control" >
</div>
<div class="form-group">
<label class="float-label" for="username">Password</label>
<input type="password" name="password" id="password" class="form-control" >
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary float-right" id="login">Log in</button>
</div>
</form>
JS:
$(function () {
$("#loginform").on('submit', function (e) {
e.preventDefault();
console.log($('#loginform').serialize());
$.ajax({
type: 'post',
url: 'https://fleetr-208415.appspot.com/',
data: $(this).serialize(),
cache: false,
success: function (data) {
var employeeId = data;
console.log(employeeId);
if (employeeId == 1)
{
adminScreen();
}
else if (employeeId == 2)
{
dispatcherScreen();
}
else if (employeeId == 3)
{
truckerScreen();
}
else
{
alert("error");
}
}
});
});
})
function truckerScreen()
{
// similar behavior as an HTTP redirect
window.location.replace("/#/trucker");
}
function dispatcherScreen()
{
window.location.replace("/#/dispatch");
}
function adminScreen()
{
window.location.replace("/#/admin");
}
PHP:
<?php header(“Access-Control-Allow-Origin: *“);
require ‘connection.php’;
$username = $_POST[‘username’];
$password = $_POST[‘password’];
$result = mysqli_query($conn, ‘select name, email, employee_type from employee where employee_id=“‘.$username.‘” and password=“‘.$password.‘“’);
if(mysqli_num_rows($result)==1)
{
while ($row = $result->fetch_assoc())
{
$name = $row[“name”];
$email = $row[“email”];
$employee_type = $row[“employee_type”];
}
echo $employee_type;
}
?>
So if you were submitting username: James, and password: 123, on first submit the URL would become
www.blahblah.net/?username=James&password=123#/login
And then, upon resubmitting the same information, you would be redirected to the proper page. Note that simply reloading the URL with the form information does not have the same effect.
Neither of us has any experience using PHP or AJAX for form submission/user validation, and we are at a total loss as to why this weird error is happening.

How to Autofill and login into a website from external login page?

Different customers use different websites to log-in to their account. i want to provide them a single form to put their credentials onto it, and select the domain/platform t they want themselves log in to and those credentials are passed to the desired website's login form log them into it. So, help me to send the credentials to the website. You can see the login form # www.ubfmgps.com/login.html
Here is my html form to get the credentials
<form action="#" id="gaq-form" class="form-b" method="post">
<fieldset>
<p>
<span>
<label for="fba">Username</label>
<input type="text" id="txtUserName" name="txtUserName" autocomplete="on" required>
</span>
<span>
<label for="fbb">Password</label>
<input type="Password" id="txtUserPassword" name="txtUserPassword" required>
</span>
</p>
<p>
<solid>Choose Platform</solid>
<select name="platform" id="platform" width=100px>
<p> <option value="Jimishare" id="Jimishare">Jimishare</option>
<option value="Tracksolid" id="Tracksolid">Tracksolid</option>
<option value="Gpsyeah" id="Gpsyeah">Gpsyeah</option>
</select>
</p>
</p>
<p><button type="submit" onclick="login();">Log Me In</button></p>
</fieldset>
</form>
<script type="text/javascript">
function login()
{
if(document.getElementById("platform").value=='Jimishare')
{
var txtUserName = document.getElementById("username").value;
var txtUserPassword = document.getElementById("password").value;
$.ajax({
url : "http://www.jimishare.com",
type : 'post',
data : 'txtUserName=' + encodeURIComponent(username) + 'txtUserPassword=' + encodeURIComponent(password),
dataType : 'json',
error : function(data) { console.log("error"); console.error(data); },
success : function(data) { console.log("success"); console.info(data); }
});
}
else if (document.getElementById("platform").value=='Tracksolid') {
document.write("Tracksolid");
var account = document.getElementById("username").value;
var password = document.getElementById("password").value;
$.ajax({
url : "http://www.tracksolid.com/mainFrame",
type : 'post',
data : 'account=' + encodeURIComponent(account) + 'password=' + encodeURIComponent(password),
dataType : 'json',
error : function(data) { console.log("error"); console.error(data); },
success : function(data) { console.log("success"); console.info(data); }
});
}
else {
document.write("Gpsyeah");
}
}
</script>
As everyone said, you are looking for a SSO system. Anyway, if you want to make a quick login system, you have to add some javascript to perform this operation.
You need to define a mapping which describe the username and password fields name for each sites. Assuming you have jQuery, you can try like this :
$(document).ready(function() {
form = $("#gaq-form");
websitePickerField = $("select[name='platform']");
usernameField = $("#username");
passwordfield = $("#password");
submitBtn = $('#submit');
form.submit(function() {
updateFormAttrs($(this).val());
});
});
function updateFormAttrs(currentWebsite) {
var options = mapping[currentWebsite];
form.attr('action', options.url);
usernameField.attr('name', options.usernameName);
passwordfield.attr('name', options.passwordName);
submitBtn.attr('name', options.submitName);
}
See this jsfiddle

Ajax validation no request send to server

I apologize for opening what might be a very basic post, I am learning Ajax please keep that in mind.
I have a simple registration form.
What im trying to do
validate the form
if all is in order register new user
I have managed to get the Ajax script to register a new user but my problem comes in with the validation part hench im turning here for a bit of help and advice
HTML
<div id="regResponse">
</div>
<form class="form-horizontal" id="regForm" role="form" method="post" action="../register.php" >
<div class="form-group">
<label class="control-label col-sm-2" for="regName">Name:</label>
<div class="col-sm-10">
<input type="text" name="regName" class="form-control" id="name" placeholder="">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="regLastName">Surname:</label>
<div class="col-sm-10">
<input type="text" name="regLastname" class="form-control" id="lastname" placeholder="">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="regEmail">Email:</label>
<div class="col-sm-10">
<input type="text" name="regEmail" class="form-control" id="regEmail" placeholder="">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="regPword">Pword:</label>
<div class="col-sm-10">
<input type="text" name="regPword" class="form-control" id="regPword" placeholder="">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="confRegPword">Confirm Pword:</label>
<div class="col-sm-10">
<input type="text" name="confRegPword" class="form-control" id="regPword2" placeholder="">
</div>
JQUERY AJAX
function sendForm() {
var valid;
valid = validateContact()
if(valid){
// Get the form.
var form = $('#regForm');
// Get the messages div.
var formMessages = $('#regResponse');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error').addClass('success');
// Set the message text.
$(formMessages).html(response); // < html();
// Clear the form.
$('').val('')
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success').addClass('error');
// Set the message text.
var messageHtml = data.responseText !== '' ? data.responseText : 'Oops! An error occured and your message could not be sent.';
$(formMessages).html(messageHtml); // < html()
});
});
}
}
function validateContact(){
var valid = true;
var name = document.getElementById("name").value;
var lastname = document.getElementById("lastname").value;
var email = document.getElementById("regEmail").value;
if(name ==''){
document.getElementById("name").style.borderColor="red";
name.value="Please Enter Name";
valid = false;
}
if(lastname ==''){
valid = false;
}
if(email ==''){
valid = false;
}
return valid;
}
PHP
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//get variables from reg form
$name = $_POST['regName'];
$lastName = $_POST['regLastname'];
$email = $_POST['regEmail'];
:
$sql ="INSERT INTO members......."
($result = mysql_query($sql) or trigger_error(mysql_error()."in".$sql);
if($result){
echo '<h3 style="blue">Registration Succesesfull</h3>';
}
else{
echo '<h3 style="blue">OOPS...Something went wrong here</h3>';
}
}//request POST method
Like I said as form the registration part all is working but as soon as I added the JavaScript validation the whole script stopped working. My biggest problem is that my browser is not showing me any errors so I dont know where I am going wrong
Any help will be much appreciated
Your sendForm function is not triggered.
Code below as your reference, is the right way to trigger submit event via jquery.
jQuery
$(function() {
$('form').submit(function(e) {
e.preventDefault();
var valid;
valid = validateContact()
if(valid ) {
$.ajax({
type: 'POST',
url: "http://facebook.com",
data: {},
dataType: 'json',
success: function() {
alert('success');
},
error: function() {
alert('error');
}
})
}
});
});
function validateContact(){
var valid = true;
var name = document.getElementById("name").value;
var lastname = document.getElementById("lastname").value;
var email = document.getElementById("regEmail").value;
if(name ==''){
document.getElementById("name").style.borderColor="red";
name.value="Please Enter Name";
valid = false;
}
if(lastname ==''){
valid = false;
}
if(email ==''){
valid = false;
}
return valid;
}
I think you need to add a button in your html and call function sendForm() on that button's click event.

Login form using PHP and AJAX

I am simply trying to log in on a popup log in box. I used AJAX to check whether log in is successful or not. If it is successful move to header location otherwise Give an error.
Code look like this:
<script>
$(document).ready(function () {
$('#login').click(function () {
var email = $("#email").val();
var pass = $("#pass").val();
var dataString = 'email=' + email + '&pass=' + pass;
if ($.trim(email).length > 0 && $.trim(pass).length > 0) {
$.ajax({
type: "POST",
url: "ajaxlogin.php",
data: dataString,
cache: false,
success: function (data) {
if (data) {
$("body").load("index.php").hide().fadeIn(1500).delay(6000);
//or
window.location.href = "index.php";
}
else {
$("#login").val('Login')
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
});
}
return false;
});
});
</script>
Form:
<div class="user_login">
<form action="" method="post">
<label>Email / Username</label>
<input type="email" Placeholder="Email-id" name="email" Required="required" id="email"/>
<br />
<label>Password</label>
<input type="password" Placeholder="Password" name="pass" Required="required" id="pass"/>
<br />
<div class="checkbox">
<input id="remember" type="checkbox" />
<label for="remember">Remember me on this computer</label>
</div>
<div class="action_btns">
<div class="one_half"><i class="fa fa-angle-double-left"></i> Back</div>
<div class="xyx"><input type="submit" value="Login" name="submitm" id="login"/></div>
<div id="error"></div>
</div>
</form>
Forgot password?
</div>
and php file is separate named as ajaxlogin.php:
include('includes/db.php');
if (isset($_POST['email']) && isset($_POST['pass'])) {
$pass = $_POST['pass'];
$email = $_POST['email'];
$query = "SELECT * FROM login WHERE email='$email' AND BINARY pass=BINARY '$pass'";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
$_SESSION['user'] = $email;
}
}
Both Script and form are on same page. Output that i am currently getting is Error message Both for right and wrong Username/Password Match. But if i delete "return false;" from script it moves to header location without log in.
try this script,
$(document).ready(function()
{
$('#login').click(function()
{
var email = $("#email").val();
var pass = $("#pass").val();
if ($.trim(email).length > 0 && $.trim(pass).length > 0)
{
$.ajax({
type: "POST",
url: "ajaxlogin.php",
data: {email:email,pass:pass},
cache: false,
success: function(data) {
if (data)
{
$("body").load("index.php").hide().fadeIn(1500).delay(6000);
window.location.href = "index.php";
}
else
{
$("#login").val('Login')
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
});
}
return false;
});
});
Looks like you are not returning any data from ajaxlogin.php
so the success function always takes control to else and throws you an error message on the screen.

Categories