Currently I' am setting up a email verification system for my personal site. I (try) to handle this with jQuery and AJAX (code follows). But the problem is that it does not return to the echo 2; in my signup.inc.php so that I can continue working in the AJAX call.
As I understand it the compiler should return to/continue from the point where it was redirected, in this case the send_ver_email($user_email) below and echo 2. What did I get wrong? This is pretty new to me and I don't have so much experience , but I don't not what else to try. Tried moving and merging documents, but nothing works.
The AJAX call in JS:
$.ajax({
type: 'POST',
url: 'include/signup.inc.php',
data: 'user_name=' + user_name +
'&user_email=' + user_email +
'&user_pw=' + user_pw,
dataType: 'html',
success: function (data) {
if (data == 0) { // invalid email
... do something
} else if (data == 1) { // account already exists
... do something
} else if (data == 2) {
**This is where it should land after the successful sign up**
return false;
}
}
});
signup.inc.php works great and stores the data in database, so this is not the problem:
include_once "dbc.inc.php";
include_once "verification.inc.php";
if (isset($_POST)) {
//get posted data;
//select $statement
// error handlers
if (filter_var($user_email, FILTER_VALIDATE_EMAIL) === false) {
echo 0;
exit();
} else if ($statement->rowCount() > 0) {
echo 1;
exit();
} else {
// db entry (works great no problems there)
send_ver_email($user_email);
echo 2;
exit();
}
}
the AJAX receives the 2 and reacts as intended if send_ver_email($user_email) is disabled, so I'am very sure that it has something to do with the structure or the way send() handles things. This function is included in verification.inc.php which includes the whole PHPMailer package. And the Email works too! I get every single mail
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
include_once "../PHPMailer/src/Exception.php";
include_once "../PHPMailer/src/PHPMailer.php";
include_once "../PHPMailer/src/SMTP.php";
function generate_ver_code() {
// ...
}
function send_ver_email ($user_mail) {
$verCode = generate_ver_code();
$mail = new PHPMailer;
$mail->SMTPDebug = 2;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = '.......';
$mail->Password = '........';
$mail->setFrom('........', '.......');
$mail->addAddress('.........', '..........');
$mail->Subject = '...........';
$mail->Body = "......................";
$mail->isHTML(true);
$mail->AltBody = '.........';
$mail->send()
}
I am also very grateful for tips about code style and layout :)
EDIT 1: A different approach:
if($mail->send()) {
echo 2;
exit();
} else {
// some error handling
}
This does not crash, I logged everywhere around it, but the ajax still does not register the echo 2
And another try showed:
if($mail->send()) {
} else {
// some error handling
}
and in signup.inc.php:
send_ver_email($user_email);
--------LOGGED HERE---------
echo 2;
exit();
}
This works fine too... this weirds me out the most. Either I got a really dumb typo somewhere or another newbie mistake (hopefully) or ajax handles this echo calls in a very confusing way.
dataType - delete this one.
Add console.log and open console in Your browser
success: function (data) {
console.log( data );
show Your console, and then You will see why. Maybe an unwanted char or php error
Second thing - there should be if stament like this (I supposed)
if (data == "1") // it is returning string, not integer.
You can also try to use switch case in success.
Related
I'm currently making a Contact page using a mixture of Ajax, PHP and MySQL.
A Few Quick Notes:
All of the PHP and AJAX code is working. The only thing that I can't get to work is the response coming from the PHP to the AJAX.
This Contact page has been optimized so that, in the case that JavaScript is disabled on a browser. The page will use a simple POST method to complete the action.
I have a few custom functions (e.g. n()) that have been declared earlier in the files that I'm providing clips from. Please just disregard these as they don't effect anything related to the issue.
A break down of each file can be found underneath each block of code.
contact_page.php (where the magic happens)
header('Content-type: application/json');
if(isset($_POST['l'])) {
if($_POST['l'] == 'php') { //This is related to the PHP version of the form validation. The code that handles the AJAX is farther down
$fd = $_POST['fd'];
$i = 0;
while ($i < count($fd)) { //Used to make sure all fields have been filled. Otherwise, return null.
$fd[$i] = n($fd[$i],false);
if(empty($fd[$i])) { $fd[$i] = null; }
$i++;
}
if(isset($fd[0],$fd[1],$fd[2],$fd[3])) {
if(filter_var($fd[1], FILTER_VALIDATE_EMAIL) && strlen($fd[1]) > 6) {
$q1 = "INSERT INTO contact_msg VALUES ('".$fd[0]."','".$fd[1]."','".$fd[2]."','".$fd[3]."',NOW(),'$date-$id');";
$r1 = mysqli_query($dbc1,$q1);
if($r1) {
$h = 'From: Jewl Photography Notifications <contact#jewl-photography.net>' . "\r\n" .
'MIME-Version: 1.0' . "\r\n" .
'Content-type: text/html; charset=utf-8' . "\r\n" .
'Reply-To: contact#jewl-photography.net' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$m = m($fd[0],$fd[2],$fd[3],"$date-$id");
mail('nathan#lmartin.net','New Message From: '.$fd[0],$m,$h);
header('Location: https://jewl-photography.net/Contact?w=SNT');
} else {
header('Location: https://jewl-photography.net/Contact?w=INT_ERR');
}
} else {
header('Location: https://jewl-photography.net/Contact?w=FLS_EMAIL');
}
} else {
header('Location: https://jewl-photography.net/Contact?w=MISS_ALL');
}
}
//Below is the code that handles the AJAX
if($_POST['l'] == 'ajax') {
if(isset($_POST['name'],$_POST['email'],$_POST['subject'],$_POST['message'])) {
$fd = array(n($_POST['name'],true),
n($_POST['email'],false),
n($_POST['subject'],false),
n($_POST['message'],false));
if(filter_var($fd[1], FILTER_VALIDATE_EMAIL)) {
$q1 = "INSERT INTO example_table VALUES ('".$fd[0]."','".$fd[1]."','".$fd[2]."','".$fd[3]."',NOW(),'$date-$id');";
$r1 = mysqli_query($dbc1,$q1);
if($r1) {
echo json_encode('SENT');
$h = '
**Header Info**
';
$m = m($fd[0],$fd[2],$fd[3],"$date-$id");
mail('example#example.net','New Message From: '.$fd[0],$m,$h);
} else {
echo json_encode('ERROR_ADD');
}
} else { echo json_encode('FALSE_EMAIL'); }
} else { echo json_encode('NOT_ALL'); }
}
}
The contact_page.php is pretty simple.
It takes the POST info from the Ajax(shown below).
Runs it through a number of encoding functions (e.g. htmlspecialchars() and the like, represented by n() ).
Also tests for if certain requirements are met. If not, it should send a response back to the AJAX (see Step 6)
Adds it to a SQL table.
Sends an email to the moderator to let them know that a new message has been sent.
Then send's a response back to the Contact page using a json object: echo json_encode('Response Text Here');
Everything works except for step 6. For some reason, the AJAX refuses to receive the response. I'm not getting any PHP, SQL or JavaScript errors or warnings, and my Ajax (as you will see below) is using dataType JSON.
Contact.php (the user-side contact page)
<script>
//This first half isn't ajax, skip down a few lines
//The very bottom of tis block of code is the form's html
$(function() {
$('#fglk').submit(function() {
var e = [];
e[0] = $('#name').val();
e[1] = $('#emal').val();
e[2] = $('#subj').val();
e[3] = $('#mesg').val();
if(e[1].length > 6 && e[1].length < 255) {
$('.err-span').removeClass('error');
$('.err-span').html('');
} else {
$('.err-span').addClass('error');
$('.err-span').html('Provide valid Email!');
e[1] = null;
}
/**AJAX Related code \/ **/
if(e[0] && e[1] && e[2] && e[3]) {
var data = new Object();
data.l = 'ajax';
data.name = e[0];
data.email = e[1];
data.subject = e[2];
data.message = e[3];
var options = new Object();
options.data = data;
options.dataType = 'json';
options.type = 'post';
options.success = function (response) {
if(response == 'SENT') {
$('.err-span').html('Sent!');
$('.err-span').addClass('sent');
$('.err-span').addClass('error');
} else if(response == 'ERROR_ADD') {
$('.err-span').html('An internal error prevented your message from being sent!');
$('.err-span').addClass('error');
} else if(response == 'NOT_ALL') {
$('.err-span').html('Please fill out all fields!');
$('.err-span').addClass('error');
} else if(response == 'FALSE_EMAIL') {
$('.err-span').html('You must provide a valid email!');
$('.err-span').addClass('error');
}
};
options.url = 'https://example.net/php/contact_page.php';
$.ajax(options);
} else {
}
return false;
});
});
</script>
<p style='color: red;'>
<? //These $_GET parameters are for if raw PHP is used to send the message
if($_GET['w'] == 'INT_ERR') {
echo '**Some Text**';
}
if($_GET['w'] == 'FLS_EMAIL') {
echo '**Some Text**';
}
if($_GET['w'] == 'MISS_ALL') {
echo '**Some Text**';
}
if($_GET['w'] == 'SNT') {
echo '**Some Text**';
}
?>
</p>
<form action='https://example.net/php/contact_page.php?l=php' id='fglk' method='post'>
<label>Full Name:</label><br><input type='text' id='name' name='fd[]' required><br>
<label>Email:</label><br><input type='email' id='emal' name='fd[]' required><br>
<label>Subject:</label><br><input type='text' id='subj' name='fd[]'><br>
<label>Message:</label><br><textarea id='mesg' name='fd[]' required></textarea><br>
<span class='err-span'></span>
<input type='submit' name='fd[]' value='Send'>
</form>
Contact.php is pretty self explanatory.
It takes the info from the form.
Runs the email through a basic email validation
Passes it to a few JSON objects.
Runs those objects through the $.ajax() function.
Issues the return false; to prevent the form from sending and reloading the page.
After the PHP runs, the AJAX should then take the response and send a message that is written accordingly.
It doesn't throw any errors in my console. It will show an error if I provide an email that is under 6 chars long (this isn't related to the PHP code at all though). But won't show any of the responses.
I've used the same AJAX code before and it's worked fine, the main difference is the PHP backend.
If you have any questions about the code please let me know!
Thanks for your help!
I have this (soon-to-be, hopefully) ABM application running on XAMPP.
I've already dealt with its validations and the query for the insert.
I have a file for registering subjects, in an html form, with a button type="submit".
So, when the options are selected and the input filled, when pressing the button a function is called (in a javascript file) --> it validates the data and sends a request to put the info in a database. Here's the js file:
function registerSubjects(){
var carreraMateria = "";
var nombreMateria = "";
var descripcionMateria = "";
var cargaHorariaMateria = "";
if(validacionFormularioAlta()){ //this is the main validating function
$.ajax({
url: 'http://localhost/path/registerSubjects.php',
type: "POST",
data: {"carreraMateria": carreraMateria,
"nombreMateria": nombreMateria,
"descripcionMateria": descripcionMateria,
"cargaHorariaMateria": cargaHorariaMateria,
},
dataType: "html",
beforeSend: function() {
console.log("I'm in before send part");
},
success: function(data) {
if( data == "OK"){
console.log("it saved the data");
location.href = "http://localhost/path/main.php";
return;
}
//Note: There are better ways, this is just because I'm learning, will try to improve on it later :)
if( data == "ERROR"){
console.log("not saved");
alert("error, please try again");
return;
}
alert("Server message: " + data);
}
});
}else{
alert("Incorrect inputs");
}
}
Data from the form is "caught" using these variables (javascript file):
carreraMateria = document.getElementById("carreraMateria").selectedIndex;
nombreMateria = document.getElementById("nombreMateria").value;
descripcionMateria = document.getElementById("descripcionMateria").value;
cargaHorariaMateriaElemento = document.getElementById("cargaHorariaMateria");
cargaHorariaMateriaSeleccion = document.getElementById("cargaHorariaMateria").selectedIndex;
cargaHorariaMateria = parseInt(document.getElementById("cargaHorariaMateria").value);
And..... this is the registerSubjects.php which deals with some server-side validations and the INSERT:
<?php
//Connection data
include("../extras/conexion.php");
//Inicialization of variables
$carreraMateria = "";
$nombreMateria = "";
$descripcionMateria = "";
$cargaHorariaMateria = "";
//Getting data
$carreraMateria = $_POST['carreraMateria'];
$nombreMateria = $_POST['nombreMateria'];
$descripcionMateria = $_POST['descripcionMateria'];
$cargaHorariaMateria = $_POST['cargaHorariaMateria'];
//CONNECTION
$CONN = new mysqli($serverName, $username, $password, $dataBase);
// Verifico la conexion
if ($CONN->connect_error) {
die("Problema al conectar con la base de datos" . $CONN->connect_error);
return;
}
//INSERT!
//Query para introducir los datos en la base
$SQL = "INSERT INTO subjects(career_id, name, description, hours) VALUES (?, ?, ?, ? )";
if($stmt = $CONN->prepare($SQL))
$stmt->bind_param('ssss', $carreraMateria, $nombreMateria, $descripcionMateria, $cargaHorariaMateria);
$stmt->execute();
$id = $stmt->affected_rows;
$stmt->close();
}
//Check for row modification
if($id>0 ){
echo "OK";
}else{
echo "ERROR";
}
return;
?>
And so it is... I had the connection part and its checking in a different file, but was causing some problems. I've written that in the files themeselves and now the ajax is working "fine"... well, at least is working :/
The thing is... I can't insert anything... I'm stuck in my own alert, in the part that says (in the AJAX part):
if( data == "ERROR"){
console.log("not saved");
alert("error, please try again");
return;
}
Can't seem to be realizing what's wrong. At first I wasn't "catching" the values in the JS file correctly, I've fixed that, but now I can't have the INSERT working right.
Apparently I'm getting the values right (from the form, from what was selected), and I'm referencing them well, so I'm pretty confused.
EDIT1:
I've tried getting the values received in the php file; I've done this:
$carreraMateria = $_POST['carreraMateria'];
var_dump($_POST["carreraMateria"]);
$nombreMateria = $_POST['nombreMateria'];
var_dump($_POST["nombreMateria"]);
$descripcionMateria = $_POST['descripcionMateria'];
var_dump($_POST["descripcionMateria"]);
$cargaHorariaMateria = $_POST['cargaHorariaMateria'];
var_dump($_POST["cargaHorariaMateria"]);
And the result was:
string(0) ""
string(0) ""
string(0) ""
string(0) ""
Then I GUESS I'm not getting the data correctly...? :/
EDIT2:
I've disabled the PHP and AJAX parts, and was just testing the JavaScript. I've "caught" the values and printed them into console log, and they show fine, so now the problem is with transferring them into the PHP file to insert them into the database.
if($stmt = $CONN->prepare($SQL)) {
$stmt->bind_param('ssss', $carreraMateria, $nombreMateria, $descripcionMateria, $cargaHorariaMateria);
$stmt->execute();
$stmt->execute();
$id = $stmt->affected_rows;
$stmt->close();
}
there was a missing open bracked
This is functioning now :)
In the javascript file, I had declared the variables meant for initialization inside the function registerSubjects(), and so they were empty when trying to pass them. They had to be declared as global variables, outside the function.
Im trying to do a recover password system with jQuery messages and Im having a problem.
The code below is working fine, when I click in the button to recover my username and password I get the message <p class="sucess">Email sent with your data..</p>.
But I want to put the email of the user in the message. Like this:
<p class="sucess">Email sent with your data for email#example.com!</p>
Im trying like this in my php
else {
echo 'sucess'; //here I show the jQuery message
echo $result['email']; //and then I want to show my $result['email']
return;
}
I already try like this:
echo 'sucess'.$result['email'].'';
But I have always the same problem, Im entering here in my jQuery:
else
{
alert('Error in system');
}
And if I dont put this echo in $result['email'] the sucess message works fine, but when I try to echo my $result['email'] Im always entering in this jQuery condition.
Somebody there have any idea why this is happening?
My php:
switch ($action){
case 'recover':
$email = $_POST['email'];
if($email == ''){
echo 'errorempty';
}else{
$searchEmail = $pdo->prepare("SELECT * FROM admins WHERE email=:email");
$searchEmail->bindValue(":email", $email);
$searchEmail->execute();
$num_rows = $searchEmail->rowCount();
$result = $searchEmail->fetch(PDO::FETCH_ASSOC);
if($num_rows <=0 )
{
echo 'erroremail';
return;
}
else {
echo 'sucess';
echo $result['email'];
return;
}
}
break;
default:
echo 'Error';
}
}
My jQuery:
$('#recover').submit(function(){
var login = $(this).serialize() + '&action=recover';
$.ajax({
url: 'switch/login.php',
data: login,
type: 'POST',
success: function(answer){
if(answer== 'erroempty'){
$('.msg').empty().html('<p class="warning">Inform your email!</p>').fadeIn('slow');
}
else if (answer == 'erroemail'){
$('.msg').empty().html('<p class="error">Email dont exist!</p>').fadeIn('slow');
}
else if(answer == 'sucess'){
$('.msg').empty().html('<p class="sucess">Email sent with your data..</p>').fadeIn('slow');
window.setTimeout(function(){
$(location).attr('href','dashboard.php');
},1000);
}
else{
alert('Error in system');
}
},
beforeSend: function(){
$('.loginbox h1 img').fadeIn('fast');
},
complete: function(){
$('.loginbox h1 img').fadeOut('slow');
},
error: function(){
alert('Error in system');
}
});
return false;
});
you can simple echo the $email like this
$email=$result["email"];
echo $email;
then in ajax success function
if(answer.email)
{
$('.msg').empty().html('<p class="sucess">Email sent with your data..'+answer.email+'</p>').fadeIn('slow');
}
The problem is, that you server side is returning just unstructured data and the client side part will just receive a plain string like sucessdummy#example.com in the answer variable.
This answer variable is compared with strings that do not match thought your script ends in the error case. I would go for a solution by returning some kind of structured data like json.
Your server side code could look something like
$result = array('msg'=>'success','mail'=>$result['email']);
header('Content-type: application/json');
echo json_encode($result);
You have to pass the dataType:'json' option in your jquery ajax call to make it work and can access the data in the call back function like answer.msg, answer.mail
Ok so this is driving me mad. I've got 2 modal forms - login and register. Javascript does the client side validation and then an ajax call runs either a registration php file or a login php file which returns OK if successful or a specific error message indicating what was wrong (incorrect password, username already taken,etc). There is an If Then statement that checks if the return message is OK and if it is then a success message is displayed and the other fields hidden.
The register form works perfectly. I get my OK back and fields get hidden and the success message displays.
The login form however doesn't work. A successful login returns an OK but the if statement fails and instead of a nicely formatted success message I just get the OK displayed without the username and password fields being hidden which is what makes me think the IF is failing although I cannot see why it would.
I've been staring at this code for hours now and all I can see is the same code for both and no idea why one is working and one is not ....
On to the code...Here is the Login javascript:
$("#ajax-login-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "php/login.php",
data: str,
success: function(msg) {
$("#logNote").ajaxComplete(function(event, request, settings) {
if(msg == 'OK') {
// Display the Success Message
result = '<div class="alertMsg success">You have succesfully logged in.</div>';
$("#ajax-login-form").hide();
$("#swaptoreg").hide();
$("#resetpassword").hide();
} else {
result = msg;
}
// On success, hide the form
$(this).hide();
$(this).html(result).slideDown("fast");
$(this).html(result);
});
}
});
return false;
});
and here is the register javascript:
$("#ajax-register-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "php/register.php",
data: str,
success: function(msg) {
$("#regNote").ajaxComplete(function(event, request, settings) {
if(msg == 'OK') {
// Display the Success Message
result = '<div class="alertMsg success">Thank you! Your account has been created.</div>';
$("#ajax-register-form").hide();
} else {
result = msg;
}
// On success, hide the form
$(this).hide();
$(this).html(result).slideDown("fast");
$(this).html(result);
});
}
});
return false;
});
I don't think I need to add the php here since both just end with an echo 'OK'; if successful and since I'm seeing the OK instead of the nicely formatted success message I'm confident that it is working.
Any suggestions?
EDIT: Here's the login php:
<?php
require("common.php");
$submitted_username = '';
$user = stripslashes($_POST['logUser']);
$pass = stripslashes($_POST['logPass']);
if(!empty($_POST))
{
$query = "
SELECT
id,
username,
password,
salt,
email
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $user
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query ");
}
$login_ok = false;
$row = $stmt->fetch();
if($row)
{
$check_password = hash('sha256', $pass . $row['salt']);
for($round = 0; $round < 65536; $round++)
{
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password'])
{
$login_ok = true;
}
}
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo 'OK';
}
else
{
echo '<div class="alertMsg error">Incorrect username or password</div>';
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?>
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo 'OK';
}
else
{
echo '<div class="alertMsg error">Incorrect username or password</div>';
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?> <!------- There is a space here! -->
There is a space after the closing ?> which is being sent to the user. The closing ?> is optional, and it is highly recommended to NOT include it, for just this reason. Get rid of that ?>.
I am trying to use ajax to add a div to display an error message. But instead of the correct error message I get null every time. The null is a result of
<?php echo json_encode($_SESSION['msg']['login-err']); ?>;
How can I fix this? Why is it showing as null?
JavaScript:
$(document).ready(function(){
$("#open").click(function(){
$("#register").fadeIn(500);
});
$("#close").click(function(){
$("#register").fadeOut(500);
});
$("#log").click(function(){
username=$("#username").val();
password=$("#password").val();
submit=$("#log").val();
$.ajax({
type: "POST",
url: "",
data: "submit="+submit+"&username="+username+"&password="+password,
success: function(html) {
if(html==true) {
}
else {
$("#error-log").remove();
var error_msg = <?php echo json_encode($_SESSION['msg']['login-err']); ?>;
$("#s-log").append('<div id="error-log" class="err welcome dismissible">'+error_msg+'</div>');
<?php unset($_SESSION['msg']['login-err']); ?>
}
}
});
return false;
});
members.php:
<?php if(!defined('INCLUDE_CHECK')) header("Location: ../index.php"); ?>
<?php
require 'connect.php';
require 'functions.php';
// Those two files can be included only if INCLUDE_CHECK is defined
session_name('Login');
// Starting the session
session_set_cookie_params(7*24*60*60);
// Making the cookie live for 1 week
session_start();
if($_SESSION['id'] && !isset($_COOKIE['FRCteam3482Remember']) && !$_SESSION['rememberMe'])
{
// If you are logged in, but you don't have the FRCteam3482Remember cookie (browser restart)
// and you have not checked the rememberMe checkbox:
$_SESSION = array();
session_destroy();
// Destroy the session
}
if(isset($_GET['logoff']))
{
$_SESSION = array();
session_destroy();
header("Location: ../../index.php");
exit;
}
if($_POST['submit']=='Login')
{
// Checking whether the Login form has been submitted
$err = array();
// Will hold our errors
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['rememberMe'] = (int)$_POST['rememberMe'];
// Escaping all input data
$row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));
if($row['usr'])
{
// If everything is OK login
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$_SESSION['rememberMe'] = $_POST['rememberMe'];
// Store some data in the session
setcookie('FRCteam3482Remember',$_POST['rememberMe']);
}
else $err[]='Wrong username and/or password!';
}
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
header("Location: index.php");
}
else
header("Location: workspace/index.php");
echo 'true';
exit;
}
Normally a AJAX request makes a request to a PHP page which returns a value. It is often JSON but does not have to be. Here is an example.
$.ajax({
type: "POST",
url: "a request URL",
data:{
'POST1':var1,
'POST2':var2
}
success: function(result)
{
//Do something based on result. If result is empty. You have a problem.
}
});
Your PHP page doesn't always return a value so its hard to know whats going on. Your work-around for this is to use javascript variables wich hold echoed PHP data when your page returns empty. But this won't work in your case. Echoing PHP variables into javascript might work fine on occasion to but it is not good practise.
It won't work in your case because your javascript variables are set when the page is first loaded. At this point the variable $_SESSION['msg']['login-err'] has not been set (or might hold some irrelevant data) and this is what your javascript variables will also hold.
When you do it the way I mentioned you can also use functions like console.log(result) or alert(result) to manually look at the result of the PHP page and fix any problems.
I would suggest doing something like the following.
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
echo $_SESSION['msg']['login-err'];
}
else
echo 'success';
}
Javascript
$.ajax({
type: "POST",
url: "",
data: "submit="+submit+"&username="+username+"&password="+password,
success: function(response) {
if(response=='success') {
alert("Woo! everything went well. What happens now?");
//do some stuff
}
else {
alert("oh no, looks like we ran into some problems. Response is"+ response);
$("#error-log").remove();
var error_msg = response;
$("#s-log").append('<div id="error-log" class="err welcome dismissible">'+error_msg+'</div>');
}
}
});
This may not necessarily work exactly as you intended but its a good start for you to build on.
By going through the code , it seems that you are doing redirect first then sending the response.
There is something wrong in below code snippet
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
header("Location: index.php");
}
else
header("Location: workspace/index.php");
echo 'true';
exit;
}