I am using jquery to make a .php file execute but my major problem is when ever a error is thrown from back-end i used a alert to display that error_msg..but ever i submit with a error intentionally...its just moving on to page specified in action...no error alert poped up...plz help me out of this.!!pardon me if am wrong
here gose the DB_Function.php
<?php
class DB_Functions {
private $db;
// constructor for database connection
function __construct() {
try {
$hostname = "localhost";
$dbname = "miisky";
$dbuser = "root";
$dbpass = "";
$this->db = new PDO("mysql:host=$hostname;dbname=$dbname", $dbuser, $dbpass);
}
catch(PDOException $e)
{
die('Error in database requirments:' . $e->getMessage());
}
}
/**
* Storing new user
* returns user details of user
*/
public function storeUser($fname, $lname, $email, $password, $mobile) {
try {
$hash = md5($password);
$sql = "INSERT INTO users(fname, lname, email, password, mobile, created_at) VALUES ('$fname', '$lname', '$email', '$hash', '$mobile', NOW())";
$dbh = $this->db->prepare($sql);
if($dbh->execute()){
// get user details
$sql = "SELECT * FROM users WHERE email = '$email' LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
$rows = $dbh->fetch();
$n = count($rows);
if($n){
return $rows;
}
}
}
catch (Exception $e) {
die('Error accessing database: ' . $e->getMessage());
}
return false;
}
/*to check if user is
already registered*/
public function isUserExisted($email) {
try{
$sql = "SELECT email FROM users WHERE email = '$email' LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
if($dbh->fetch()){
return true;
}else{
return false;
}
}catch (Exception $e) {
die('Error accessing database: ' . $e->getMessage());
}
}
/*to check if user
exist's by mobile number*/
public function isMobileNumberExisted($mobile){
try{
$sql = "SELECT mobile FROM users WHERE mobile = '$mobile' LIMIT 1";
$dbh = $this->db->prepare($sql);
$result = $dbh->execute();
if($dbh->fetch()){
return true;
}else{
return false;
}
}catch(Exception $e){
die('Error accessing database: ' . $e->getMessage());
}
}
//DB_Functions.php under construction
//more functions to be added
}
?>
here gose the .php file to be clear on what am doing..!!
<?php
require_once 'DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => false);
if (!empty($_POST['fname']) && !empty($_POST['lname']) && !empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['mobile'])){
// receiving the post params
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$email = trim($_POST['email']);
$password = $_POST['password'];
$mobile = trim($_POST['mobile']);
// validate your email address
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
//validate your password
if(strlen($password) > 6){
//validate your mobile
if(strlen($mobile) == 12){
//Check for valid email address
if ($db->isUserExisted($email)) {
// user already existed
$response["error"] = true;
$response["error_msg"] = "User already existed with " . $email;
echo json_encode($response);
} else {
if($db->isMobileNumberExisted($mobile)) {
//user already existed
$response["error"] = true;
$response["error_msg"] = "user already existed with" . $mobile;
echo json_encode($response);
} else {
// create a new user
$user = $db->storeUser($fname, $lname, $email, $password, $mobile);
if ($user) {
// user stored successfully
$response["error"] = false;
$response["uid"] = $user["id"];
$response["user"]["fname"] = $user["fname"];
$response["user"]["lname"] = $user["lname"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = true;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
}
} else {
$response["error"] = true;
$response["error_msg"] = "Mobile number is invalid!";
echo json_encode($response);
}
} else {
//min of 6-charecters
$response["error"] = true;
$response["error_msg"] = "password must be of atleast 6-characters!";
echo json_encode($response);
}
} else {
// invalid email address
$response["error"] = true;
$response["error_msg"] = "invalid email address";
echo json_encode($response);
}
} else {
$response["error"] = true;
$response["error_msg"] = "Please fill all the required parameters!";
echo json_encode($response);
}
?>
and here gose the main file .js
$(document).ready(function(){
//execute's the function on click
$("#submit").click(function(e){
/*jquery to call the url requested
and parse the data in json*/
$.ajax({
url: "register.php",
type: "POST",
data: {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
password: $("#password").val(),
mobile: $("#mobile").val()
},
dataType: "JSON",
/*Give out the alert box
to display the results*/
success: function (json){
if(json.error){
alert(json.error_msg);
e.preventDefault();
}else{
alert("Registeration successful!",json.user.email);
}
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
e.preventDefault();
}
});
});
});
and here gose the corresponding .html file
<form method = "POST" name = "register" id = "register" class="m-t" role="form" action="login.html">
<div class="form-group">
<input type="text" name = "fname" id = "fname" class="form-control" placeholder="First Name" required="">
</div>
<div class="form-group">
<input type="text" name = "lname" id = "lname" class="form-control" placeholder="Last Name" required="">
</div>
<div class="form-group">
<input type="email" name = "email" id = "email" class="form-control" placeholder="Email" required="">
</div>
<div class="form-group">
<input type="password" name = "password" id = "password" class="form-control" placeholder="Password" required="">
</div>
<div class="form-group">
<input type="mobile" name = "mobile" id = "mobile" class="form-control" placeholder="Mobile No" required="">
</div>
<div class="form-group" id="recaptcha_widget">
<div class="required">
<div class="g-recaptcha" data-sitekey="6Lc4vP4SAAAAABjh8AG"></div>
<!-- End Thumbnail-->
</div>
<?php include("js/captcha.php");?>
</div>
<div class="form-group">
<div cle the terms and policy </label></div>
</div>ass="checkbox i-checks"><label> <input type="checkbox"><i></i> Agre
<button type="submit" name = "submit" id = "submit" class="btn btn-primary block full-width m-b">Register</button>
<p class="text-muted text-center"><small>Already have an account?</small></p>
<a class="btn btn-sm btn-white btn-block" href="login.html">Login</a>
<
/form>
From the comments:
So only after displaying Registeration successful! I want to submit the form and redirect it to login.html
Well the solution is quite simple and involved adding and setting async parameter to false in .ajax(). Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called. If you set async: true then that statement will begin it's execution and the next statement will be called regardless of whether the async statement has completed yet.
Your jQuery should be like this:
$(document).ready(function(){
//execute's the function on click
$("#submit").click(function(e){
/*jquery to call the url requested
and parse the data in json*/
$.ajax({
url: "register.php",
type: "POST",
data: {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
password: $("#password").val(),
mobile: $("#mobile").val()
},
async: false,
dataType: "JSON",
/*Give out the alert box
to display the results*/
success: function (json){
if(json.error){
alert(json.error_msg);
e.preventDefault();
}else{
alert("Registeration successful!",json.user.email);
('#register').submit();
}
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
So the form will only get submitted if the registration is successful, otherwise not.
Edited:
First of all make sure that <!DOCTYPE html> is there on the top of your page, it stands for html5 and html5 supports required attribute.
Now comes to your front-end validation thing. The HTML5 form validation process is limited to situations where the form is being submitted via a submit button. The Form submission algorithm explicitly says that validation is not performed when the form is submitted via the submit() method. Apparently, the idea is that if you submit a form via JavaScript, you are supposed to do validation.
However, you can request (static) form validation against the constraints defined by HTML5 attributes, using the checkValidity() method.
For the purpose of simplicity I removed your terms and conditions checkbox and Google ReCaptcha. You can incorporate those later in your code.
So here's your HTML code snippet:
<form method = "POST" name = "register" id = "register" class="m-t" role="form" action="login.html">
<div class="form-group">
<input type="text" name = "fname" id = "fname" class="form-control" placeholder="First Name" required />
</div>
<div class="form-group">
<input type="text" name = "lname" id = "lname" class="form-control" placeholder="Last Name" required />
</div>
<div class="form-group">
<input type="email" name = "email" id = "email" class="form-control" placeholder="Email" required />
</div>
<div class="form-group">
<input type="password" name = "password" id = "password" class="form-control" placeholder="Password" required />
</div>
<div class="form-group">
<input type="mobile" name = "mobile" id = "mobile" class="form-control" placeholder="Mobile No" required />
</div>
<!--Your checkbox goes here-->
<!--Your Google ReCaptcha-->
<input type="submit" name = "submit" id = "submit" class="btn btn-primary block full-width m-b" value="Register" />
</form>
<p class="text-muted text-center"><small>Already have an account?</small></p>
<a class="btn btn-sm btn-white btn-block" href="login.html">Login</a>
And your jQuery would be like this:
$(document).ready(function(){
//execute's the function on click
$("#submit").click(function(e){
var status = $('form')[0].checkValidity();
if(status){
/*jquery to call the url requested
and parse the data in json*/
$.ajax({
url: "register.php",
type: "POST",
data: {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
password: $("#password").val(),
mobile: $("#mobile").val()
},
async: false,
dataType: "JSON",
/*Give out the alert box
to display the results*/
success: function (json){
if(json.error){
alert(json.error_msg);
e.preventDefault();
}else{
alert("Registeration successful!",json.user.email);
$('#register').submit();
}
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
}
});
});
your form submit takes action before ajax action so its reloading the page and use form submit instead of submit button click
//execute's the function on click
$("#register").on('submit',function(e){
e.preventDefault(); // prevent page from reloading
Ok steps to be sure that everthing works fine while you try to use ajax
1st : use form submit and use e.preventDefault(); to prevent page reloading
//execute's the function on click
$("#register").on('submit',function(e){
e.preventDefault(); // prevent page from reloading
alert('Form submited');
});
if the alert popup and form not reloading the page then the next step using ajax
//execute's the function on click
$("#register").on('submit',function(e){
e.preventDefault(); // prevent page from reloading
$.ajax({
url: "register.php",
type: "POST",
dataType: "JSON",
data: {success : 'success'},
success : function(data){
alert(data);
}
});
});
and in php (register.php)
<?php
echo $_POST['success'];
?>
this code should alert with "success" alert box .. if this step is good so now your ajax and php file is connected successfully then pass variables and do another stuff
Related
I am currently working on a PHP based web-interface, with a login system.
But for some reason when I hit login, it seems to get to the login.php and return a response back.
But the thing is, the response is not what I need to have, and furthermore logging in is still not happening.
The HTML based login form (Within a modal):
<form class="form" method="post" action="<?php echo Utils::resolveInternalUrl('backend/Login.php') ?>" id="loginForm">
<div class="form-group">
<label for="loginUsername">Username:</label> <input type="text" class="form-control" name="loginUsername" id="loginUsername" />
</div>
<div class="form-group">
<label for="loginPassword">Password:</label> <input type="password" class="form-control" name="loginPassword" id="loginPassword"/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Login</button>
</div>
</form>
Javascript/jQuery related to login:
var form = $('#loginForm');
form.submit(function (e) {
e.preventDefault();
$.ajax({
'data': form.serialize(),
'type': $(this).attr('method'),
'url': $(this).attr('action'),
'dataType': 'JSON',
success: function (data) {
alert("Success: " + data)
},
error: function (error) {
alert("Error: " + error)
}
})
})
PHP backend, related to login:
if($_SERVER['REQUEST_METHOD'] == "POST") {
$database = Database::getDefaultInstance();
if(isset($_POST['loginUsername']) && isset($_POST['loginPassword'])) {
$connection = $database->getConnection();
$username = $_POST['loginUsername'];
$password = $_POST['loginPassword'];
echo $username . ":" . $password;
$stmt = $connection->query("SELECT * FROM banmanagement.users;");
if($stmt->fetch()) {
session_start();
$_SESSION['username'] = $username;
$_SESSION['sessionId'] = Utils::randomNumber(32);
echo json_encode("Successfully logged in as ${username}.");
exit;
} else {
echo json_encode("No user exists with the name \"${username}\".");
exit;
}
} else {
echo json_encode("Username and/or password is not provided.");
exit;
}
} else {
echo json_encode("Submit method is not POST.");
exit;
}
The result of it:
Click here for screenshot
Edit:
Changed SQL query to: SELECT COUNT(*) FROM banmanagement.users WHERE username=:username;
Edit 2:
Per suggestion, I have used var_dump the output var_dump($_POST) is: array(0) { }.
$stmt = $connection->query("SELECT * FROM banmanagement.users;");
I'm assuming you're using PDO on the backend. If so, you don't need the semicolon in your query. That's why your fetch is failing.
$stmt = $connection->query("SELECT * FROM banmanagement.users");
Ok, so that wasn't it. I was reading the wrong braces. Have you tried var_dump($_POST) to see what, if anything, is being sent?
I try this php code(I have already read about sql Injection)but apparently it does not run, no error message or anything else ...
<?php
function SignIn(){
session_start();
require_once("dbConnection.php");
if(isset($_POST['submit'])){
$db_handle = new DBConnection();
$username = $_POST["username"];
if(filter_var($username, FILTER_VALIDATE_EMAIL)===true && strpos(explode('#',$username),"studio.unibo.it")===true){
$query = $db_con->prepare("SELECT * FROM studenti_in_sessione
WHERE Username=:username");
$query->execute(array(":username"=>$username));
$row = $query->fetch(PDO::FETCH_ASSOC);
$count = $query->rowCount();
if($row['Username']==$username){
echo "<script language = javascript>
alert(\"Autenticazione riuscita,Le invieremo nella mail istituzionale un codice univoco di autenticazione.\");
window.history.go(-1);
</script>";
$querySession = $db_con->prepare("SELECT Nome, Cognome, Matricola FROM studenti_in_sessione
WHERE Username:=username");
$querySession->execute(array(":username"=>$username));
$rowStud = $querySession->fetch(PDO::FETCH_ASSOC);
$exit = array_values($rowStud);
$queryInsert = $db_con->prepare("INSERT INTO studente (Nome, Cognome, Matricola, Username, Codice) VALUES('".$exit[0]."',
'".$exit[1]."','".$exit[2]."','".$username."');");
$resultInsert = $queryInsert->execute();
sendCode($username);
}
}}else{
echo "<script language = javascript>
alert(\"L'indirizzo deve essere #studio.unibo.it.\");
window.history.go(-1);
</script>";
}
if(isset($_POST['submit'])){
SignIn();
}
?>
This is html form
<div class="box-header">
<h2>Login</h2>
</div>
<form name="form" class="form" method="POST">
<label for="username">Username</label>
<br/>
<input type="text" id="username" name="username">
<input name="submit" id="submit" type="submit" value="Login">
</div>
Finally script.js
$('document').ready(function()
{
/* validation */
$(".form").validate({
rules:
{
user_email: {
required: true,
email: true
},
},
messages:
{
user_email: "please enter your email address",
},
submitHandler: submitForm
});
/* validation */
/* login submit */
function submitForm()
{
var data = $(".form").serialize();
$.ajax({
type : 'POST',
url : '../Slide_upload/database/signIn.php',
data : data,
success : function(response){
if(response=="ok"){
}
else{
}
}
});
return false;
}
/* login submit */
});
I probably made mistakes but I can not figure out where ...
For sure, you are missing a bracket to close your function that is not being executed.
Add it before the lines
if(isset($_POST['submit'])){
SignIn();
}
This will make your function call working.
So after validating the form via Jquery, I like to know if the username and password are valid. If they are, it should redirect to another page, else I want to find a way of showing it to the user. At this point, I'm really confused. Here's the jquery code:
$(document).ready(function(e) {
$('.error').hide();
$('#staffLogin').submit(function(e) {
e.preventDefault();
$('.error').hide();
uName = $('#staff_username').val();
pWord = $('#staff_password').val();
if(uName == ''){
$('#u_error').fadeIn();
$('#staff_username').focus();
return false;
}
if(pWord == ''){
$('#p_error').fadeIn();
$('#staff_password').focus();
return false;
}
$.ajax({
type : 'POST', url : 'staff_access.php', data : 'uName='+uName+'&pWord='+pWord,
success: function(html){
if(html == 'true'){
window.location = 'staff_page.php';
}
else{
$('#val_error').fadeIn();
}
}
})
});
});
PHP:
<?php
include('admin/config.php');
$username = $_POST['uName'];
$password = $_POST['pWord'];
$conn = mysqli_connect(DB_DSN,DB_USERNAME,DB_PASSWORD,dbname);
if ($conn) {
$qry = "SELECT lastname, firstname, FROM staff_user WHERE username='".$username."' AND pass='".$password."";
$res = mysqli_query($qry);
$num_row = mysqli_num_rows($res);
$row=mysql_fetch_assoc($res);
if ($num_row == 1) {
session_start();
$_SESSION['login'] = true;
$_SESSION['lastname'] = $row['lastname'];
$_SESSION['firstname'] = $row['firstname'];
$_SESSION['username'] = $row['username'];
echo "true";
}
else{
echo "false";
}
}
else{
$conn_err = "Could not connect.".mysql_error();
}
mysqli_close($conn);
?>
FORM:
<form name="staff_login" method="post" action="" id="staffLogin">
<fieldset>
<legend>Staff Login</legend>
<span class="fa fa-user fa-5x"></span>
<br><br>
<input type="text" name="staff_username" id="staff_username" placeholder="Username">
<br><span class="error" id="u_error">Username Required</span><br>
<input type="password" name="staff_password" id="staff_password" placeholder="Password">
<br><span class="error" id="p_error">Password Required</span><br>
<span class="error" id="val_error">Incorrect Username and Password combination</span>
<input type="submit" name="staff_login" value="Login">
</fieldset>
</form>
Your ajax data is sent in wrong format. POST data should be sent as an object.
$.ajax({
type : 'POST',
url : 'staff_access.php',
data : {
uName: uName,
pWord: pWord
},
dataType: 'text',
success: function(html){
if(html == 'true'){
window.location = 'staff_page.php';
}
else{
$('#val_error').fadeIn();
}
}
});
Also avoid using texts like 'html'. You may end up getting unnecessary errors due to that.
Use more relevant words like "success: function(response)"
Try to define a dataTpe in your ajax config - dataType: "html"
I have a sample script that will authenticate my users to access the page. My issue is when I post the values the js file does reflect that the data has been serialized but when it is posted to the php file to check if the database record exists the users still gets access to the page whether the login in details are correct or wrong. For some reason it seems not to take my `$_POST['pass'] and my $_POST['user_email'] values. But if I manually type in the user email and password in the php file to replace the variables it will works.
HTML form
<form class="login" id="login-form" name="login-form" method="post">
<p class="title">LOGIN</p>
<input type="text" placeholder="Email" id="user_email" name="user_email" autofocus/>
<i class="fa fa-user"></i>
<input type="password" placeholder="Password" id="pass" name="pass" />
<i class="fa fa-key"></i>
<button>
<i class="spinner" style="outline:none;"></i>
<span class="state">Log in</span>
</button>
</form>
My js file to post the values. I added the console.log just to test see what values are been taken in by the script
$('document').ready(function()
{
var working = false;
$('.login').on('submit', function(e) {
e.preventDefault();
if(working)return
working = true;
var $this = $(this),
$state = $this.find('button > .state');
$this.addClass('loading');
$state.html('Authenticating');
var data = $("#login-form").serialize();
console.log(data);
$.ajax({
type : 'POST',
url : 'login_process.php',
data : data,
success : function(response) {
console.log(response);
if(response=="ok"){
setTimeout(function() {
$this.addClass('ok');
$state.html('Welcome');
setTimeout(function() {
$state.html('Log in');
$this.removeClass('ok loading');
working = false;
}, 4000);
setTimeout(function() {
window.location.href = "/Home.aspx";
}, 4000);
}, 3000);
//$("#btn-login").html('<img src="btn-ajax-loader.gif" /> Signing In ...');
//setTimeout(' window.location.href = "home.php"; ',4000);
} else {
console.log('ERROR IN LOGINING IN');
}
}
});
return false;
});
});
PHP file 'login_process'
<?php
session_start();
require_once 'dbconfig.php';
if(isset($_POST['pass']))
{
$user_email = urldecode(trim($_POST['user_email']));
$user_password =trim($_POST['pass']);
//$password = md5($user_password);
$password = $user_password;
try {
$stmt = $db_con->prepare("SELECT * FROM tbl_users WHERE user_email=:email");
$stmt->execute(array(":email"=>$user_email));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();
if($row['user_password']==$password){
echo "ok"; // log in
$_SESSION['user_session'] = $row['user_id'];
}
else{
echo "email or password does not exist."; // wrong details
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
You are missing the dataType make with dataType : 'json' just after data, You can return the result in json by json_encode() ti debug result
I'm hoping someone could look over my code and let me know what's going on. I have a form. When it is submitted the popup comes up and tells me that it failed and I get a page that just says "undefined". Anyone got any ideas on A: why the send is failing and B: How I need to amend my JavaScript to get the page to go back to the homepage after submission.
HTML:
<div class="contact-form">
<p class="mandatory">* indicates Manadatory Field</p>
<div data-role="fieldcontain" class="text-field">
<label for="firstname">First Name*:</label>
<input type="text" name="firstname" value="" placeholder="" class="required" id="firstname" />
</div>
<div data-role="fieldcontain" class="text-field">
<label for="surname">Last Name:</label>
<input type="text" name="surname" value="" placeholder="" id="surname" />
</div>
<div data-role="fieldcontain" class="text-field">
<label for="email">Email Address*:</label>
<input type="email" name="email" value="" placeholder="" class="required" id="email" />
</div>
<div data-role="fieldcontain" class="text-field">
<label for="mobilephone">Mobile Number:</label>
<input type="number" name="mobilephone" value="" placeholder="" id="mobilephone" />
</div>
<div data-role="fieldcontain">
<label for="message">Message*:</label>
<textarea name="message" id="message" placeholder="" class="required"></textarea>
</div>
<div class="send">Send Message</div>
JAVASCRIPT
$(function () {
$("#symptomsemployersbutton").click(function () {
$("#symptomsemployers").toggle("slow");
});
});
$('#send-feedback').live("click", function () {
var url = 'submit.php';
var error = 0;
var $contactpage = $(this).closest('.ui-page');
var $contactform = $(this).closest('.contact-form');
$('.required', $contactform).each(function (i) {
if ($(this).val() === '') {
error++;
}
}); // each
if (error > 0) {
alert('Please fill in all the mandatory fields. Mandatory fields are marked with an asterisk *.');
} else {
var firstname = $contactform.find('input[name="firstname"]').val();
var surname = $contactform.find('input[name="surname"]').val();
var mobilephone = $contactform.find('input[name="mobilephone"]').val();
var email = $contactform.find('input[name="email"]').val();
var message = $contactform.find('textarea[name="message"]').val();
//submit the form
$.ajax({
type: "GET",
url: url,
data: {
firstname: firstname,
surname: surname,
mobilephone: mobilephone,
email: email,
message: message
},
success: function (data) {
if (data == 'success') {
// show thank you
$contactpage.find('.contact-thankyou').show();
$contactpage.find('.contact-form').hide();
} else {
alert('Unable to send your message. Please try again.');
}
}
}); //$.ajax
}
return false;
});
PHP
<?php
header('content-type: application/json; charset=utf-8');
if (isset($_GET["firstname"])) {
$firstname = strip_tags($_GET['firstname']);
$surname = strip_tags($_GET['surname']);
$email = strip_tags($_GET['email']);
$mobilephone = strip_tags($_GET['mobilephone']);
$message = strip_tags($_GET['message']);
$header = "From: ". $firstname . " <" . $email . ">rn";
$ip = $_SERVER['REMOTE_ADDR'];
$httpref = $_SERVER['HTTP_REFERER'];
$httpagent = $_SERVER['HTTP_USER_AGENT'];
$today = date("F j, Y, g:i a");
$recipient = 'mark#launchintervention.com';
$subject = 'Contact Form';
$mailbody = "
First Name: $firstname
Last Name: $surname
Email: $email
Mobile Phone: $mobilephone
Message: $message
IP: $ip
Browser info: $httpagent
Referral: $httpref
Sent: $today
";
$result = 'success';
if (mail($recipient, $subject, $mailbody, $header)) {
echo json_encode($result);
}
}
?>
Your conditional statement never fires in your success function because it will always be false. (data == 'success') will never work because your json encoding of that string returns the value, "success" as opposed to success. I don't know why you're json encoding it anyway, but you should do something else such as
$result = array(
'status' => 'success'
);
echo json_encode($result);
Then you can do
(data.status == 'success')
As far as redirecting after the result returns successful, after the following line:
$contactpage.find('.contact-form').hide();
You should do something like:
setTimeout(function(){
window.location = 'mydomain.tld/my-homepage.ext';
}, 5000);
And your element with the class of contact-thankyou should have some type of text like, "We have received your submission. You will be redirected to the home page in 5 seconds.". Then after 5 seconds they will be redirected based on the previously defined setTimeout function.
You also have an rn at the end of your header declaration which i assume should be \r\n, however you do not continue concatentation of the headers and therefore it is not required. Please review the RFC2822 on this.