I have a form for password recovery via email. I send input to PHP to do the following:
Validate {three different validation messages)
If passed, Process
Once the response is received, in AJAX, although is not valid, it is considered successful because it has been processed in php.
I need to differentiate between every response so I can display appropriate alert messages
if field input is empty, I want to show it in alert-info message box
if field input is noa t valid email, I want to show it in alert-warning message box
if field input is not found the in server, I want to show it in alert-danger message box
if successful, I want to show it in alert-success
$(function() {
// Get FORM ID ///////////////////////////////////////////
var form = $('#RecoveryForm');
// Get MESSAGE DIV ID ///////////////////////////////////////////
var formMessages = $('#formresults');
$(form).submit(function(e) {
$( "#submit" ).prop( "disabled", false );
e.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
$(formMessages).text(response);
// Get FORM ID ///////////////////////////////////////////
document.getElementById("RecoveryForm").reset();
//$('#reset-button').click();
})
.fail(function(data) {
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
$("#submit").removeAttr("disabled");
});
});
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div id="formresults"></div>
<form id="RecoveryForm" method="post" action="exa.php">
<table align="center">
<tr><td><div class="input-append"><input type="text" name="email" id="email" class="input-xlarge" placeholder="Email" maxlength="100" /><span class="add-on"><li class="icon-envelope"></li></span></div></td></tr>
</table>
<input type="hidden" name="token" value="<?=Token::generate();?>" />
<center><input type="submit" id="submit" name="Forget" class="btn btn-primary" value="Submit" /></center>
</form>
<script src="ajax/jquery-2.1.0.min.js"></script>
<script src="ajax/app.js"></script>
<!---------------------------------------------------------------->
<?php include 'footer.php'; ?>
</body>
</html>
PHP Code >>
<?php
header('Content-type: application/json');
require 'Access.php'; // Get Access
//response array with status code and message
$response_array = array();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = $_POST["email"];
if ( empty($email) ) {
$response_array['status'] = 'info';
$response_array['message'] = 'No Input';
echo json_encode($response_array);
exit;
}
if ( !filter_var($email, FILTER_VALIDATE_EMAIL) ) {
$response_array['status'] = 'warning';
$response_array['message'] = 'Not Valid Email';
echo json_encode($response_array);
exit;
}
if (#mysql_num_rows(mysql_query("SELECT `id` FROM `accounts` WHERE `email`='$email'")) < 1) {
$response_array['status'] = 'danger';
$response_array['message'] = 'Account Not Found';
echo json_encode($response_array);
exit;
}
$row_user = #mysql_fetch_array(mysql_query("SELECT * FROM `accounts` WHERE `email`='$email'"));
$password = $row_user['pass'];
$to = $row_user['email'];
$subject = "Your Recovered Password";
$message = "Please use this password to login: " . $password;
$headers = "From : XXX#hotmail.com";
// Send the email.
if (mail($to, $subject, $message, $headers)) {
$response_array['status'] = 'Success';
$response_array['message'] = 'Email Sent';
echo json_encode($response_array);
} else {
$response_array['status'] = 'info';
$response_array['message'] = 'Try Again Later';
echo json_encode($response_array);
}
} else {
$response_array['status'] = 'info';
$response_array['message'] = 'Try Again Later';
echo json_encode($response_array);
}
$response_array['status'] = 'info';
$response_array['message'] = 'Try Again Later';
echo json_encode($response_array);
?>
First of all we start validation from the html of cause this can be hampered and manipulated by the user but still a good way to start.
first we add the required attribute to your input fields in html and change the input types to match the data types your expecting eg: input type="email" hiding an input does not prevent it form being tampered with, best to add the Readonly attribute also.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div id="formresults"></div>
<form id="RecoveryForm" method="post" action="exa.php">
<table align="center">
<tr>
<td>
<div class="input-append">
<input type="email" Required name="email" id="email" class="input-xlarge" placeholder="Email" maxlength="100" />
<span class="add-on"><li class="icon-envelope"></li></span>
<p id="mailerror"></p> <!-- This Segment Displays The Validation Rule For Email -->
</div>
</td>
</tr>
</table>
<input type="hidden" Readonly name="token" value="<?=Token::generate();?>" />
<center>
<input type="submit" id="submit" name="Forget" class="btn btn-primary" value="Submit" />
</center>
<script src="ajax/jquery-2.1.0.min.js"></script>
<script src="ajax/app.js"></script>
</form>
</body>
</html>
Second of all you are using jquery although this much much more easy to use i will suggest you start with java script validation, using the onsubmit attribute to catch the form and begin validation. you will be better understand what exactly is going on as a beginner rather than jquery.
<script>
$(function() {
/*Get FORM ID*/
var form = $('#RecoveryForm');
/*Get MESSAGE DIV ID */
var formMessages = $('#formresults');
/*Email Validation*/
var email_regex = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var email = $('#email').val();
if (!email.match(email_regex) || email.length == 0) {
$('#mailerror').text("* Please enter a valid email address *");
$("#email").focus();
return false;
}
else if (email.match(email_regex) && email.length >= 5){
$(form).submit(function(e) {
$( "#submit" ).prop( "disabled", false );
e.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
if (response.status=='Success'){
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
$(formMessages).text(response.message);
}
else if (response.status=='warning'){
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
$(formMessages).text(response.message);
}
else if (response.status=='danger'){
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
$(formMessages).text(response.message);
}
else if (response.status=='info'){
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
$(formMessages).text(response.message);
}
/*Get FORM ID */
document.getElementById("RecoveryForm").reset();
})
.fail(function(data) {
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
$("#submit").removeAttr("disabled");
});
}
});
</script>
Third of all your PHP could have been better written but it works fine presumably :( so we leave that for now.
report different response with php validation
.done(function(response) {
var messageAlert = response.type;
var messageText = response.message;
var alertBox = '<div class="alert ' + messageAlert + '"style="margin-top:10px;"><button type="button" class="close" data-dismiss="alert">×</button><d style="font-size:11px; ">' + messageText + '</d></div>';
(formMessages).html(alertBox);
For every PHP statement add:
$responseArray = array('type' => 'alert-warning', 'message' => '<b>Alert!</b>There is not enough credit');
Then send response json encoded
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray); header('Content-Type: application/json'); echo $encoded; } else { echo $responseArray['message']; }
Related
I'm scratching my head with this one at the moment - if any of you could help that'd be amazing. I have a site which uses AJAX to submit a contact form after a simple validation. All goes well, and the site acts as if the email has sent, but I'm not receiving any emails (yep I've triple checked, it's the right email address).
Here's what I'm working with:
HTML / PHP
<script type="text/javascript" language="javascript" src="js/contact.js"></script>
...
<section id="contact">
<span class="contact_results"></span>
<div class="form">
<input type="text" name="name" id="contactname" required value="<? echo $user_name ?>" placeholder="Your Name:" autocomplete="off">
<input type="email" name="email" id="email" required value="<? echo $email ?>" placeholder="Your E-Mail Address:" autocomplete="off">
<input type="phone" name="phone" id="phone" value="<? echo $phone ?>" placeholder="Your Telephone Number:" autocomplete="off">
<textarea name="message" id="message" required placeholder="Your Message:"><? echo $message ?></textarea>
<button type="submit" name="submit" id="contactbutton">Submit Form</button>
</div>
</section>
Contact.js
$(function() {
$("#contact button").click(function() {
var proceed = true;
//simple validation at client's end
//loop through each field and we simply change border color to red for invalid fields
$("#contact input[required=true], #contact textarea[required=true]").each(function(){
$(this).css('border-color','#EEE');
if(!$.trim($(this).val())){ //if this field is empty
$(this).css('border-color','#FC0'); //change border color to red
proceed = false; //set do not proceed flag
}
//check invalid email
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if($(this).attr("type")=="email" && !email_reg.test($.trim($(this).val()))){
$(this).css('border-color','#FC0'); //change border color to red
proceed = false; //set do not proceed flag
}
});
if(proceed) //everything looks good! proceed...
{
//get input field values data to be sent to server
post_data = {
'user_name' : $('input[name=name]').val(),
'user_email' : $('input[name=email]').val(),
'user_phone' : $('input[name=phone]').val(),
'msg' : $('textarea[name=message]').val()
};
//Ajax post data to server
$.post('contact_sendform.php', post_data, function(response){
if(response.type == 'error'){ //load json data from server and output message
output = '<span class="error">'+response.text+'</span>';
}else{
output = '<span class="success">'+response.text+'</span>';
//reset values in all input fields
$("#contact input[required=true], #contact textarea[required=true]").val('');
$(".form").fadeOut(400); //hide form after success
}
$("#contact .contact_results").hide().html(output).slideDown(400);
}, 'json');
}
});
//reset previously set border colors and hide all message on .keyup()
$("#contact input[required=true], #contact textarea[required=true]").keyup(function() {
$(this).css('border-color','');
$("#result").slideUp();
});
});
contact_sendform.php
<?php
if($_POST)
{
$to_email = "xxxxxxxx#hotmail.com";
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
//Sanitize input data using PHP filter_var().
$user_name = filter_var($_POST["user_name"], FILTER_SANITIZE_STRING);
$user_email = filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL);
$user_phone = filter_var($_POST["user_phone"], FILTER_SANITIZE_NUMBER_INT);
$message = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);
//additional php validation
if(strlen($user_name)<3){ // If length is less than 4 it will output JSON error.
$output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
die($output);
}
if(!filter_var($user_email, FILTER_VALIDATE_EMAIL)){ //email validation
$output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
die($output);
}
if(strlen($message)<3){ //check emtpy message
$output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
die($output);
}
//email body
$message_body = $message."\r\n\r\n-".$user_name."\r\nEmail : ".$user_email."\r\nPhone Number : ". $user_phone ;
// Set Subject
$subject = "Ian! You've got a new message from ".$user_name;
//proceed with PHP email.
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: '.$user_email."\r\n".
'Reply-To: '.$user_email."\r\n" .
'X-Mailer: PHP/' . phpversion();
$send_mail = mail($to_email, $subject, $message_body, $headers);
if(!$send_mail)
{
//If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}else{
$userArray = explode(' ', trim($user_name));
$output = json_encode(array('type'=>'message', 'text' => 'Thanks for getting in touch, '.$userArray[0] .'!'));
die($output);
}
}
?>
As I said - when the form is submitted with the correct data, it displays the confirmation message which only fires when $sendMail works - so I'm at a loss as to what's going wrong. Any insight or help would be majorly appreciated - thanks! :)
I have a comment system in which user comments and through ajax it validates the data and sent to .php page. The problem is it receives the status=1 but does not apply the else if Ajax code. I am stuck here. Any suggestions or help will be highly regarded.
AJAX
<script type="text/javascript">
$(document).ready(function() {
$("#submit_comment").click(function() {
var proceed = true;
$(" #comment_form textarea[required=true]").each(function(){
$(this).css('border-color','');
if(!$.trim($(this).val())){ //if this field is empty
$(this).css('border-color','red'); //change border color to red
proceed = false; //set do not proceed flag
}
});
if(proceed)
post_data = {
'user_email' : $('input[name=email]').val(),
'pid' : $('input[name=productid]').val(),
'msg' : $('textarea[name=comment]').val()
};
$.post('comments.php', post_data, function(response){
if(response.type == 'error'){ //load json data from server and output message
output = '<div class="error">'+response.text+'</div>';
}
else if(response.status && response.type != 'error')
{
output = '<div class="success">'+response.text+'</div>';
$(response.html).hide().insertBefore('#comment_form').slideDown();
$(" #comment_form textarea[required=true]").val('');
$("#comment_form #comment_body").slideUp();
}
$("#comment_form #comment_results").hide().html(output).slideDown();
}, 'json');
});
//reset previously set border colors and hide all message on .keyup()
$("#comment_form input[required=true], #comment_form textarea[required=true]").keyup(function() {
$(this).css('border-color','');
$("#result").slideUp();
});
});
</script>
Form
<?php
include "comment.php";
$comments = array();
$result = mysqli_query($con,"SELECT * FROM comments where product_id='$id' ORDER BY dt LIMIT 5");
while($row = mysqli_fetch_assoc($result))
{
$comments[] = new Comment($row);
}
?>
<?php
foreach($comments as $c){
echo $c->markup();
}
?>
</div>
<?php
}
}
?>
<div class="form-style" id="comment_form">
<div id="comment_results"></div>
<div id="comment_body">
<input type="hidden" name="email" id="email" value="<?php echo $email?>">
<input type="hidden" name="productid" id="productid" value="<?php echo $pid?>" />
<label for="field5"><span>Comment: <span class="required">*</span></span>
<textarea name="comment" id="comment" class="textarea-field" required="true"></textarea>
</label>
<label>
<span> </span><input type="submit" id="submit_comment" value="Submit"">
</label>
</div>
</div>
comment.php
<?php
class Comment
{
private $data = array();
public function __construct($row)
{
$this->data = $row;
}
public function markup()
{ $d = &$this->data;
// Converting the time to a UNIX timestamp:
$d['dt'] = strtotime($d['dt']);
// Needed for the default gravatar image:
return '
<div class="comment">
<div class="name">'.$d['email'].'</div>
<div class="date" title="Added at '.date('H:i \o\n d M Y',$d['dt']).'">'.date('d M Y',$d['dt']).'</div>
<p>'.$d['body'].'</p>
</div>
';
}
}
?>
comments.php
<?php
include("db/db.php");
include "comment.php";
if($_POST)
{
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
//Sanitize input data using PHP filter_var().
$user_name = filter_var($_POST["user_email"], FILTER_SANITIZE_STRING);
$pid = filter_var($_POST["pid"], FILTER_VALIDATE_INT);
$message = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);
$arr = array();
//additional php validation
if(strlen($message)<3){ //check emtpy message
$output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
die($output);
}
mysqli_query($con,"INSERT INTO comments(email,body,product_id) values('$user_name','$message','$pid')");
$arr['dt'] = date('r',time());
$arr['id'] = mysql_insert_id();
$res=mysqli_query($con,$query);
$arr = array_map('stripslashes',$arr);
$insertedComment = new Comment($arr);
if(!$res)
{
$output = json_encode(array('type'=>'error', 'text' => 'Cannot recieve your comment.'));
die($output);
}else{
$output= json_encode(array('type'=>'message', 'text' => 'Hi '.$user_name .' Thank you for your review','status'=>1,'html'=>$insertedComment->markup()));
echo $output;
die($output);
}
}
?>
I have a simple login form in which I have passed the values through AJAX call. The problem is when I enter wrong email or password for first time, It displays me the error message. 2nd time if I enter something wrong it does not show the error. Where am I doing wrong any suggestions/help please.
Form
<?php
if (isset($_SESSION['login_email']) && !empty($_SESSION['login_email'])) {
//header('Location:profile.php');
?>
<script> location.replace("profile.php"); </script>
<?php
} else {
?>
<div class="login_form">
<h1 class="login_heading">Login</h1>
<div class="alert-error"></div>
<div class="alert-success"></div>
<div class="login">
<form method="post" action="">
<label >Email</label>
<input class="inputs_login" type="email" name="email" id="email" placeholder="email" >
<label>Password</label>
<input class="inputs_login" type="password" name="password" id="password" placeholder="password"><br>
<input type="button" name="login_submit" id="login_submit" value="login">
</form>
</div>
</div>
<?php
}
?>
Ajax
<script>
$(document).ready(function() {
$('#login_submit').click(function(e){
//e.preventDefault();
var email = $("#email").val(),
password = $("#password").val();
var proceed = true;
if(proceed){
post_data= { 'Email': email, 'Password': password};
$.post('login_index.php', post_data, function(response){
//load json data from server and output message
if(response.type == 'error')
{
output=$('.alert-error').html(response.text);
}else{
location.href="profile.php";
}
$(".alert-error").delay(3200).fadeOut(300);
}, 'json');
}
});
});
</script>
php
<?php
include "db/db.php";
session_start();
if ($_POST) {
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting json data
$output = json_encode(array(
'type' => 'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
if (isset($_POST['Email']) && isset($_POST['Password'])) {
$email = filter_var($_POST["Email"], FILTER_SANITIZE_STRING);
$pwd = filter_var($_POST["Password"], FILTER_SANITIZE_STRING);
$query = mysqli_query($con, "select * from customers where email='$email' and password='$pwd'");
$count = mysqli_num_rows($query);
$row = mysqli_fetch_array($query, MYSQLI_ASSOC);
if ($row) {
$_SESSION['login_email'] = $row['email'];
$output = json_encode(array(
'type' => 'message',
'text' => 'Hi ' . $email . ' You are successfully login'
));
die($output);
} else {
$output = json_encode(array(
'type' => 'error',
'text' => 'Could not Login! Please check your email/password OR REGISTER FREE ACCOUNT .'
));
die($output);
}
}
}
?>
as title, I am a beginner about website design.
Please never mind if I ask a stupid question.
while i send the form, it didnt work.
here is html:
<form id="form1" name="form1" action="toSQL.php" method="POST" accept-charset="utf-8">
<input type="text" name="Cliname" id="textfield" maxlength = "10" />
<textarea name="message" id="message" rows="3" maxlength = "20" ></textarea>
<input type="submit" value="submit" id="submit" />
</form>
<div class="alert"></div>
and here is js:
<script type="text/javascript">
$(document).ready(function() {
var form = $(this) ;
var submited = $('#submit') ;
var alerted = $('.alert') ;
form.on( 'submit', this, (function(event) {
event.preventDefault();
if ( $.trim($form.find('input[name="Cliname"]').val()) == "" || $.trim($form.find('input[name="message"]').val()) == "" ) {
alert( "please enter!!" ) ;
return ;
}
else {
$.ajax({
url: 'toSQL.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alerted.fadeOut();
},
success: function(data) {
alerted.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
},
error: function(e) {
console.log(e)
}
});
}
}));
});
</script>
server side php:
<?php
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ){
if (isset($_POST['Cliname']) AND isset($_POST['message'])) {
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
if (send($name, $message)) {
echo 'Message sent!';
} else {
echo 'Message couldn\'t sent!';
}
}
else {
echo 'All Fields are required';
}
return;
}
function send( $name, $message ) {
$time = date("Y-m-d H:i:s");
$mysqlConnection=mysql_connect("localhost", 'root', '') or die("connect error!");
mysql_select_db('test') or die ("db error!");
$queryStr="INSERT INTO fortest (time, message, name)
VALUES ( '$time', '$message', '$name')";
mysql_query($queryStr,$mysqlConnection) or die(mysql_error());
return true ;
}
?>
here is the website i reference : http://www.w3bees.com/2013/08/submit-form-without-page-refresh-with.html
Did i miss something?
As a couple people have mentioned already, you are trying to serialize your entire dom object, which isn't going to work. Change it to var form = $("#form1") and it should work.
I recommend you open the webpage in chrome dev tools and click the network tab, click preserve log and then submit the form. When it is submitted you'll see the full headers that were sent to the server and can verify it works correctly to help narrow down the problem
I am trying to learn from an example from online,for a login form with php and jquery and i am using the exactly the same example, but for some reason the AJAX isnt getting anything back but redirecting my to another php.
Here is a link of what i had been trying and the problem.
http://rentaid.info/Bootstraptest/testlogin.html
It supposed to get the result and display it back on the same page, but it is redirecting me to another blank php with the result on it.
Thanks for your time, i provided all the codes that i have, i hope the question isnt too stupid.
HTML code:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form id= "loginform" class="form-horizontal" action='http://rentaid.info/Bootstraptest/agentlogin.php' method='POST'>
<p id="result"></p>
<!-- Sign In Form -->
<input required="" id="userid" name="username" type="text" class="form-control" placeholder="Registered Email" class="input-medium" required="">
<input required="" id="passwordinput" name="password" class="form-control" type="password" placeholder="Password" class="input-medium">
<!-- Button -->
<button id="signinbutton" name="signin" class="btn btn-success" style="width:100px;">Sign In</button>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javasript" src="http://rentaid.info/Bootstraptest/test.js"></script>
</body>
</html>
Javascript
$("button#signinbutton").click(function() {
if ($("#username").val() == "" || $("#password").val() == "") {
$("p#result).html("Please enter both userna");
} else {
$.post($("#loginform").attr("action"), $("#loginform:input").serializeArray(), function(data) {
$("p#result").html(data);
});
$("#loginform").submit(function() {
return false;
});
}
});
php
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
ob_start();
session_start();
include 'connect.php';
//get form data
$username = addslashes(strip_tags($_POST['username']));
$password = addslashes(strip_tags($_POST['password']));
$password1 = mysqli_real_escape_string($con, $password);
$username = mysqli_real_escape_string($con, $username);
if (!$username || !$password) {
$no = "Please enter name and password";
echo ($no);
} else {
//log in
$login = mysqli_query($con, "SELECT * FROM Agent WHERE username='$username'")or die(mysqli_error());
if (mysqli_num_rows($login) == 0)
echo "No such user";
else {
while ($login_row = mysqli_fetch_assoc($login)) {
//get database password
$password_db = $login_row['password'];
//encrypt form password
$password1 = md5($password1);
//check password
if ($password1 != $password_db)
echo "Incorrect Password";
else {
//assign session
$_SESSION['username'] = $username;
$_SESSION['password'] = $password1;
header("Location: http://rentaid.info/Bootstraptest/aboutus.html");
}
}
}
}
?>
Edit
$("button#signinbutton").click(function(){
if($("#username").val() ==""||$("#password").val()=="")
$("p#result).html("Please enter both userna");
else
$.post ($("#loginform").attr("action"),
$("#loginform:input").serializeArray(),
function(data) {
$("p#result).html(data); });
});
$("#loginform").submit(function(){
return false;
});
First of all, Remove :-
header("Location: http://rentaid.info/Bootstraptest/aboutus.html");
and if you want to display the data, echo username and password.
$_SESSION['username'] = $username;
$_SESSION['password'] = $password1;
echo $username."<br>".;
echo $password1;
The reason you are being redirected is that you are also calling $.submit. The classic form submit will redirect you to a new page, which is exactly what you don't want when you're using AJAX. If you remove this call:
$("#loginform").submit(function() {
return false;
});
you probably should have working solution. If not, let me know :)
Modify your javascript section so that
$("button#signinbutton").click(function() {
if ($("#username").val() == "" || $("#password").val() == "") {
$("p#result).html("Please enter both userna");
} else {
$.post($("#loginform").attr("action"), $("#loginform:input").serializeArray(), function(data) {
$("p#result").html(data);
});
}
});
$("#loginform").submit(function() {
return false;
});
is outside the function call.