ajax call to check duplicate data - php

Here is the form to have ajax check out user existence.
<!DOCTYPE html>
<html>
<head><title>Register new user!</title>
<script src="jquery-1.7.1.min.js"></script>
</head>
<body>
Username:
<input type="text" name="username" id="username"/><span id="user"></span><br/>
Password:
<input type="password" name="password" id="password"/><br/>
<input type="button" value="Register" name="submit" id="submit" onclick="register_user();"/>
</body>
<script>
function register_user()
{
$.ajax(
{
type:"POST",
data:username,
url:"userexists.php"
})
.fail(function()
{
$('#user').html("This user already exists");
}
);
}
</script>
</html>
And here is the userexists.php module
<?php
// connection to the db
define(IPHOST,"localhost");
define(DBPASSWORD,"");
define(DBUSER,"root");
define(DATABASE,"ajaxtest");
define(TABLENAME,"at");
$conn=mysql_connect(IPHOST,DBUSER,DBPASSWORD) or die(mysql_error());
mysql_select_db(DATABASE) or die(mysql_error());
$username=$_POST('username');
$sql="SELECT username FROM ".TABLENAME." WHERE username=".$username;
$query=mysql_query($sql);
if(0!=mysql_numrows($query))
{
//
}
else
{
}
?>
But I am stuck to really figure out how the ajax function actually works, what should I enter the blank field after I know that the entered username has been used, for example ? I don't understand ajax at all.
[UPDATE]
Thank you, I understand it now, I have got several answers, don't know which one to choose as the best reply. No option to choose all.

You have a lot of mistakes in your code, try codes below:
<!DOCTYPE html>
<html>
<head><title>Register new user!</title>
<script src="jquery-1.7.1.min.js"></script>
</head>
<body>
Username:
<input type="text" name="username" id="username"/><span id="user"></span><br/>
Password:
<input type="password" name="password" id="password"/><br/>
<input type="button" value="Register" name="submit" id="submit" onclick="register_user();"/>
</body>
<script>
function register_user()
{
$.ajax({
type: "POST",
data: {
username: $('#username').val(),
},
url: "userexists.php",
success: function(data)
{
if(data === 'USER_EXISTS')
{
$('#user')
.css('color', 'red')
.html("This user already exists!");
}
else if(data === 'USER_AVAILABLE')
{
$('#user')
.css('color', 'green')
.html("User available.");
}
}
})
}
</script>
</html>
And for your php code:
<?php
// connection to the db
define(IPHOST,"localhost");
define(DBPASSWORD,"");
define(DBUSER,"root");
define(DATABASE,"ajaxtest");
define(TABLENAME,"at");
$conn=mysql_connect(IPHOST,DBUSER,DBPASSWORD) or die(mysql_error());
mysql_select_db(DATABASE) or die(mysql_error());
$username = mysql_real_escape_string($_POST['username']); // $_POST is an array (not a function)
// mysql_real_escape_string is to prevent sql injection
$sql = "SELECT username FROM ".TABLENAME." WHERE username='".$username."'"; // Username must enclosed in two quotations
$query = mysql_query($sql);
if(mysql_num_rows($query) == 0)
{
echo('USER_AVAILABLE');
}
else
{
echo('USER_EXISTS');
}
?>

Since you're new to AJAX, let me try and help you a bit better with some explanations as we go.
AJAX stands for Asynchronous Javascript And XML. Using it, you can make a request to another page and have your original page behave differently according to the results returned by the other page.
So how is this useful? Well; You could set an onblur even on a 'username' field to check a remote script to see if a username is already in use. (Which you are already doing in your current setup. Good work!)
Firstly; the .fail() is telling your current page "If the ajax request fails, lets do this code". This is called a callback. A callback is a function of javascript code to execute when the asynchronous request is finished.
So what you want to actually do is use the .done() method. This tells your jQuery request "Hey, when you're done doing this request, do this chunk of code. While you're doing that, im going to sit here and handle anything else that happens".
So you can see there is a slight difference between using .done() and .fail(), however I can see how you can be easily confused with .fail() being new to ajax.
So lets get back to your current problem. Lets modify the ajax to something more like this:
$("#submit").click(function()
{
$.ajax({
type: "POST",
data: "username="+$("#username").val(),
url: "userexists.php"
})
.done(function(response){
$('#user').html(response);
});
});
What this does is bind an onclick handler for your submit button with the id "submit". So now you can remove onclick="register_user". Secondly, it says, "Hey webpage, go send userexists.php the username textbox value with the parameter name username. When you've finished that request, set the html of #user to the response.
So off it goes and does it.
Now your PHP file, you can do:
<?php
// connection to the db
define(IPHOST,"localhost");
define(DBPASSWORD,"");
define(DBUSER,"root");
define(DATABASE,"ajaxtest");
define(TABLENAME,"at");
$conn = mysql_connect(IPHOST,DBUSER,DBPASSWORD) or die(mysql_error());
mysql_select_db(DATABASE) or die(mysql_error());
$username = mysql_real_escape_string($_POST['username']); // Stop some MySQL injections
$sql="SELECT username FROM ".TABLENAME." WHERE username='$username'";
$query=mysql_query($sql);
if(mysql_numrows($query) == 0)
{
echo 'Username is available!'
}
else
{
echo 'Sorry, username is in use.';
}
?>
So once your script does its query, if it finds a result it will say in the HTML div "Username is available!". Otherwise, if it finds a match, it says "Sorry, username is unavailable".
Hope this helps you understand ajax a little better!

It's technically up to you. (For example) You could return a "1" for "user exists" and "0" for "user doesn't exist", or return a more detailed XML. The client app (Javascript) will read the returned result and print out an appropriate message to the user.
The .fail method should be used in case your function actually fails (server side error etc). So it doesn't seem appropriate for what you're trying to do. I would put in your ".done()" code a test of the returned values as described above and print out the correct message.
Javascript:
.done(function ( data ) {
if(data == "0")
alert("Your username is OK");
else
alert("Your username is already used");
});
PHP:
if(0!=mysql_numrows($query))
{
echo "0";
}
else
{
echo "1";
}

Function .fail in ajax is used when server return unexpected datas. But your php code dont return anything. Use something like this:
function register_user()
{
$.ajax(
{
type:"POST",
data:username,
url:"userexists.php"
})
.done(function(_return)
{
if(_return)
{
if(_return['status']=='yes')
{
$('#user').html(_return['msg']);
}
}
})
.fail(function());
}
And in php:
if(0!=mysql_numrows($query))
{
$return = array('status'=>'yes',
'msg'=>"User alredy exist");
echo json_encode($return);
return true;
}
Now you can add more conditions with many statuses and parse it in javascript.

Related

Return success/failure variable with ajax from php script

I'm a really new coder and struggling with a task I'm now working on and trying out for days.
I searched Google and Stack Overflow but can't find a (for me understandable) solution to my problem:
I created a Twitter Bootstrap landing page and there a modal shows up when clicked. In this modal I have a form with a newsletter subscription:
<form id="newsletter" method="post">
<label for="email">Email:</label><br/>
<input type="text" name="email" id="email"/><br/>
<button type="submit" id="sub">Save</button>
</form>
<span id="result"></span>
Now I want to insert the data into a mySQL DB and do some basic validation that returns errors or a success message. The script works fine without ajax, but probably needs alterations on what it returns for ajax?
include("connection.php");
if ($_POST['email']) {
if(!empty($_POST['my_url'])) die('Have a nice day elsewhere.');
if (!$_POST['email']) {
$error.=" please enter your email address.";
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$error.=" please enter a valid email address.";
}
if($error) {
$error= "There was an error in your signup,".$error;
} else {
$query="SELECT * FROM `email_list` WHERE email='".mysqli_real_escape_string($link, $_POST['email'])."'";
$result = mysqli_query($link, $query);
$results = mysqli_num_rows($result);
if ($results) {
$error.=" this email address is already registered.";
} else {
$query = "INSERT INTO `email_list` (`email`) VALUES('".mysqli_real_escape_string($link, $_POST['email'])."')";
mysqli_query($link, $query);
$message = "Thanks for subscribing!";
}
}
}
After a lot of reading ajax seems to be the way to do it without the bootstrap modal closing after submit (to suppress default event).
The insertion into the DB works fine, also the validation.
But I can't manage to get the different error messages displayed (stored in the $error variable of the php file) or alternatively the $message in case of success.
This is the jquery script:
$("#sub").submit(function (){
event.preventDefault();
$.ajax( {
url: "newsletter2.php",
type: "POST",
data: {email: $("#email").val()},
success: function(message) {
$("#result").html(message);
},
error: function(error) {
$("#result").html(error);
}
});
I try to display the value of the error and message variable in the php script within the #result span.
Any help is appreciated. Please formulate it very straight forward since I'm really new to this field.
Thank you a lot in advance.
Edit:
Added some to the php file to create an array and store the messages within:
$response = array();
$response['success'] = $success;
$response['error']= $errors;
exit(json_encode($response));
But have still some trouble to get the ajax to work. Tried the shorthand $.post instead of $.ajax but can't them now even to get to work posting data...
$("#sub").submit(function (){
event.preventDefault();
$.post("newsletter.php", {email: $("#email").val() });
});
Quick time is much appreciated. I'm stuck after hours of testing and can't find the error. If I submit the form regularly it works fine, so the php/mysql part isn't the problem.
I also realized that when I click the "#sub" button, it still tries to submit the form via get (URL gets values passed). So I'm not sure if the event.preventDefault(); isn't working? jQuery is installed and working.
The $.ajax error function gets called when there is a connection error or the requested page cannot be found
You have to print some text out with the php and the ajax success function gets this output. Then you parse this output to see how it went.
The best practice is this:
php part:
$response = array();
$response['success'] = $success;
$response['general_message'] = $message;
$response['errors'] = $errors;
exit(json_encode($response));
js/html part:
$.post("yourpage.php", a , function (data) {
response = JSON.parse(data);
if(response['success']){
//handle success here
}else{
//handle errors here with response["errors"] as error messages
}
});
Good luck with your project
You need to echo your messages back to your AJAX. There is no place in you PHP code where the messages are going back to the message variable in your AJAX success.
include("connection.php");
if ($_POST['email']) {
if(!empty($_POST['my_url'])) die('Have a nice day elsewhere.');
if (!$_POST['email']) {
$error.=" please enter your email address.";
echo $error; die;
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$error.=" please enter a valid email address.";
echo $error; die;
}
if($error) {
$error= "There was an error in your signup,".$error;
echo $error; die;
} else {
$query="SELECT * FROM `email_list` WHERE email='".mysqli_real_escape_string($link, $_POST['email'])."'";
$result = mysqli_query($link, $query);
$results = mysqli_num_rows($result);
if ($results) {
$error.=" this email address is already registered.";
echo $error; die;
} else {
$query = "INSERT INTO `email_list` (`email`) VALUES('".mysqli_real_escape_string($link, $_POST['email'])."')";
mysqli_query($link, $query);
$message = "Thanks for subscribing!";
echo $message; die;
}
}
}
I basicly just had the same case. I structured my code a little bit different but it works so...
$("#sub").submit(function (){
event.preventDefault();
$.ajax( {
url: "newsletter2.php",
type: "POST",
dataType: 'json',
data: {email: $("#email").val()},
})
.success(function(message) {
$("#result").html(message);
}),
.error(function(error) {
$("#result").html(error);
})
on server side I used C#(asp.net) and just returned a Json
return Json(new { Message = "Something...", Passed = true}, JsonRequestBehavior.AllowGet);
Oukay, finally I managed to solve the problem with the great inputs here. I did the following:
PHP:
$response = array();
$response['success'] = $success;
$response['error'] = $error;
exit(json_encode($response));
JS:
$("#newsletter").submit(function(event) {
event.preventDefault();
$.ajax({
url: 'newsletter3.php',
method: 'post',
data: {email: $('#email').val()},
success: function(data) {
var response = JSON.parse(data);
console.log(response);
if (response['success']) {
$("#error").hide();
$("#success").html(response['success']);
$("#success").toggleClass("alert alert-success");
} else {
$("#error").html(response['error']);
if(!$("#error").hasClass("alert alert-danger"))
$("#error").toggleClass("alert alert-danger");
}
}
});
});
The functionality is now that you click on a button and a modal pops-up, then you can enter your email and the php script validates if its valid and if it's already in the db. Error and success messages get JSON encoded and then are displayed in a span that changes color according to bootstrap classes danger or success.
Thank you very much for helping me, I'm very happy with my first coding problem solved :)
I use this on my ajax
request.done(function (response, data) {
$('#add--response').html(response);
});
and this on the PHP
die("Success! Whatever text you want here");

PHP Session ID Variable Returned With AJAX

I'm working on an AJAX login system and am not sure how to return the PHP session variable from AJAX unto the login page. My question is, how do I return the php variable unto the login page, if that is even possible. Below is the sample I created.
Login Page
<?php
session_start();
?>
<form>
<input type="text" id="username" />
<input type="text" id="password"/>
<input type="button" id="submit" />
</form>
<script type="text/javascript" >
$('#submit').click(function() {
var username = $('#username').val();
var password = $('#password').val();
$.post('ajax_file.php',
{
username: username,
password:password,
},
function (data) {
/* what do I do here that will return the php variable
$_SESSION['user_id'] and let the user be logged in when
they go to homepage.php*/
setTimeout('window.location.href="homepage.php"', 2000);
});});
</script>
Here is the ajax page. I understand that the logic doesn't make sense for the session variable to pop out of nowhere, let's just assume that is was created earlier in the page.
$username = $_POST['username'];
$password = $_POST['password'];
if(login($username, $password)) {
return $session_user_id = $_SESSION['user_id'];
}
You can just do the AJAX post, set the session variable to the session in the page receiving the post, and it will be stored in the session (it's the same session). In the AJAX callback forward the user to the home page.
Of course you must consider the scenario that the login credentials are incorrect.
The trick is that your JavaScript doesn't even have to know about sessions at all; you can configure PHP to use HttpOnly cookies for its session management via the respective ini setting.
I would implement the AJAX script like this:
session_start(); // start the session
if (login($username, $password)) {
// alter session to hold user id
$_SESSION'user_id'] = $user_id_from_database_or_something;
return true;
} else {
return false;
}
The AJAX complete handler looks at the return value and redirect to the homepage if it was true. Something like below (I'm assuming that the PHP return is translated into something like echo json_encode($return_value):
if (data) {
// do redirect
} else {
// login failed
}
Then, when the user comes to the homepage their browser would send a session cookie so you can determine if they're logged in.
Improving the Answer
FOr Jquery, USe function below
function sendAjax(showAllExist, controller)
{
$.ajax({
type: "post",
url: login.php,
data: yourformdatacomeshere,
beforeSend: function() {
//do whatever you want to do before request
},
error: function() {
//display in case of error
},
success: function(data) {
//display in case of error
if(data!=""){
//redirect use to home pahe
window.location.href ='homepage.php';
}else{
//display login is not correct
}
},
complete: function() {
//hide any event which you have started on beforeSend
}
});
return true;
}
Cant you just do this:
$.post('ajax_file.php',
{
username: username,
password:password,
loginSession: <?php echo $_SESSION['user_id']; ?>
},
function (data) {
//Check here if login is correct.
if correct, create this variable:
var logged= "?logged="+data.SessionID;
/* what do I do here that will return the php variable
$_SESSION['user_id'] and let the user be logged in when
they go to homepage.php*/
setTimeout('window.location.href="homepage.php"+logged+"'", 2000);
});})
When data comes back go the homepage.php with a sessionID.
on the php script do this:
if(isset($_GET['logged'])){
start_session();
$_Session['LOGGED']='true';
}
use this method which is improvised above shail answer.
your ajax file code
$username = $_POST['username'];
$password = $_POST['password'];
if(login($username, $password)) {
$session_user_id = $_SESSION['user_id'];// this is from your code
$responseArray = array("message"=>"success","sessionId"=>$session_user_id);
}
else
{
$session_user_id = "";
$responseArray = array("message"=>"error","sessionId"=>$session_user_id);
}
echo json_encode ( $responseArray );
die ();
then in ajax function make below changes.
var frmdata = jQuery("#logindata").serialize(); // which contains the data of username and password
jQuery.ajax({
type : "POST"
,url :'ajax_file.php'
,data :frmdata
,dataType: "json"
,success : function(data){
if(data.message == "success")
{
//redirect it to your desire page
}
else
{
//redirect it to your login page
}
}
,beforeSend: function(html){
// some loader goes here while ajax is processing.
}
});
hope this help feel free to ask anything for this answer.

PHP: How to excute query without form postback?

I have a form in which i want to do the validations. But there is a field which i want to validate writing a query. I dont want the form to postback because after postback all the values filled in the form are lost. Is there any way i can write a query without postback or if i have to postback how to retain the values ? Please help
If you use AJAX (jQuery), you can post an XML Request without refreshing the browser, if this is what you need.
For this, just create a form with some textfields and a submit button, give everything an ID and add an click-Listener for the button:
$('#submit-button').click(function() {
var name = $('#username').val();
$.ajax({
type: 'POST',
url: 'php_file_to_execute.php',
data: {username: name},
success: function(data) {
if(data == "1") {
document.write("Success");
} else {
document.write("Something went wrong");
}
}
});
});
If the user clicks on the button with the "submit-button"-ID, this function is called. Then you send the value of the textfield using POST to the php_file_to_execute.php. Inside this .php-File, you can validate the username and output theresult:
if($_POST['username'] != "Neha Raje") {
echo "0";
} else {
echo "1";
}
I hope that I could help you! :)
You might want to rephrase what you wrote, its a bit unclear. FYI I do it like this;
<form method="post">
Text 1: <input type="text" name="form[text1]" value="<?=$form["text1"]?>" size="5" /><br />
Text 2: <input type="text" name="form[text2]" value="<?=$form["text2"]?>" size="5" /><br />
<input type="submit" name="submit" value="Post Data" />
</form>
And when I am processing the data, it's like this;
<?php
if ($_POST["submit"]) {
$i = $_POST["form"];
if ($i["text1"] or ..... ) { $error = "Something is wrong."; }
if ($i["text2"] and ..... ) { $error = "Maybe right."; }
if (!$error) {
/*
* We should do something here, but if you don't want to return to the same
* form, you should definitely post a header() or something like that here.
*/
header ("Location: /"); exit;
}
//
}
if (!$_POST["form"] and !$_GET["id"]) {
} else {
$form = $_POST["form"];
}
?>
By this method, the values are not lost unless you set them to get lost.
Use jQuery's $.post() method as:
$('#my_submit_button').click(function(event){
event.preventDefault();
var username = $('#username').val();
$.post('validate.php', {username: username, my_submit_button: 1}, function(response){
console.log(response); //response contain either "true" or "false" bool value
});
});
In validate.php get the username from your form asynchronously as like this:
if(isset($_POST['my_submit_button']) && $_POST['my_submit_button'] == 1 && isset($_POST['username']) && $_POST['username'] != "") {
// now here you can check your validations with $_POST['username']
// after checking validations, return or echo appropriate boolean value like:
// if(some-condition) echo true;
// else echo false;
}
Note: Please consider knowing security-related vulnerabilities and other issues before using AJAX for executing database-altering scripts.

How to validate password with jquery and php?

I've never done this before, and I haven't found much help on Google or StackOverflow yet.
Here's what I have: A password input:
<input type="text" placeholder="password" name="pass" id="password" />
and some jQuery to check the password:
<script>
$('form').submit(function(){
input = $('#password').val();
var finish = $.post("pass.php", { request: "opensesame" }, function(data) {
return (input==data) ? true : false;
});
if(finish){
alert('sent');
}else{
alert('not sent');
}
return false;
});
</script>
And a password-dispensing php page (pass.php):
<?php
if(isset($_POST['request'])&&$_POST['request']=="opensesame"){
echo 'graphics';
}
?>
Now, I can get it to alert 'graphics', but I can't get it to match the data with the input value to check if it's the right password or not.
What am I doing wrong, and what are the potential dangers to authenticating a password in this way?
The "A" in "AJAX" stands for asynchronous.
The code after you call $post will execute before the contents of the $post function. The value of finish will always be a jqXHR object, the result of (input==data) ? true : false will be ignored.
More clearly:
var finish = $.post("pass.php", { request: "opensesame" }, function(data) {
// THIS EXECUTES SECOND, and the return value is discarded
return (input==data) ? true : false;
});
// THIS EXECUTES FIRST, with finish set to a jqXHR object
if(finish){
...
You need to rethink your methods of password checking, or use synchronous postbacks by adding the following before your $.post calls:
$.ajaxSetup({async:false});
Or by using $.ajax and passing async: false:
jQuery.ajax({
type: 'POST',
url: "pass.php",
data: { request: "opensesame" },
success: function(result) { ... },
async: false
});
The first thing to do would be to clean up the code, it's too obscure, I'm afraid.
I'd write it as follows:
<script>
$('form').submit(function(event){
event.preventDefault(); // stop the form from submitting
var passwd = $('#password').val();
var finish = $.post("pass.php", { request: passwd }, function(data) {
if(data){
alert('Success!');
}else{
alert('Failure :(');
}
});
});
</script>
Things to note here:
AJAX POST is asynchronous, you can't check for a variable right after changing it in the callback, you need to process stuff inside the callback.
You must verify the password on the server, not in javascript!!
Adding to the previous bullet, don't write your password inside the javascript!
And on the server:
<?php
if(isset($_POST['request']) && $_POST['request']=="opensesame"){
echo 'true';
}else{
echo 'false';
}
?>
Things to note here:
You used isset() to check for the existence of the variable, good call. Keep doing it.
jQuery POST expects a javascript value from the server (unless you tell it otherwise).
This is why my code prints either 'true' or 'false', this translates to a boolean value in javascript.
I would advise returning an object with error details, such as the one below:
<?php
$result = array('success'=>false, 'reason'=>'Unknown error.');
if(isset($_POST['request'])){
if(trim($_POST['request'])!=''){
if($_POST['request']=='opensesame'){
$result['success'] = true;
$result['reason'] = 'Welcome home!';
}else $result['reason'] = 'Password is wrong';
}else $result['reason'] = 'Password must not be empty';
}else $result['reason'] = 'Expected parameter "request"';
echo json_encode($result);
?>
You have to serialize your input fields to all the data to your script:
$.post("pass.php", { request: $('form').serialize() }, function(data) {
// ...
As long as you are on your own server I don't see much potential dangers, as it sends a POST-request which a normal form would do anyway.
Its quite unsafe to send data like this, anyone can intercept and read the data which you send by ajax and the value returned by ajax using firebug or other such tools. So you should serialize or sanitize the fields and also encrypt the data before sending them.
& the code to alert after checking finish will be executed before the response comes from ajax (note that it is asynchronous) thus you would get an object stored in the finish variable.

Jquery Ajax and PHP form submission

I've been working on a login form, that uses Jquery and Ajax to submit to a PHP file that processes the request then sends back a response. I think that somewhere, somehow the PHP script may be incorrect, because the form always comes back true allowing the person to login even when I purposely feed an incorrect password.
Here is the html code:
<div id="login">
<span class="error">Uh oh! Something went wrong please try again!</span>
<span class="success">Congrats! You've been logged in, redirecting you to your homepage</span>
<form action="process/core/login.php" method="post">
<p>Email: <input type="text" name="email" <?php if($_POST['email'] != '') { echo 'value="'. $_POST['email'] .'"'; }?> /></p>
<p>Password: <input type="password" name="pword" /></p>
<p><input type="submit" value="Login" id="login-btn" /></p>
</form>
</div>
<script>
function redirect(){
window.location = "home.php"
}
$("#login-btn").click(function(){
$.ajax({
type: "post", // type of post
url: "process/core/login.php", // submitting file
data: $("form").serialize(), // data to submit
success: function() {
$(".success").show("slow"); // sucess function
setTimeout('redirect()', 3000);
},
error: function() {
$('.error').show("slow"); // error function
}
});
return false;
});
</script>
Here is the PHP script:
<?php
session_start();
require '../../lib/core/connect.php';
if(!empty($_POST['email']) && !empty($_POST['pword'])) {
$userInfo = mysql_query("SELECT * FROM users WHERE email = '". mysql_real_escape_string($_POST['email']) ."'");
$userInfo = mysql_fetch_assoc($userInfo);
if($_POST['email'] == $userInfo['email'] && md5($_POST['pword']) == $userInfo['pword']) {
if($userInfo['active'] == 1) {
$_SESSION['AuthEmail']=$userInfo['email'];
$_SESSION['AuthUid']=$userInfo['uid'];
$_SESSION['AuthName']=$userInfo['fname'] . ' ' . $userInfo['lname'];
$_SESSION['AuthActive']=$userInfo['active'];
$_SESSION['AuthType']=$userInfo['type'];
return true;
print 'success';
} else {
return false;
print 'fail not active';
}
} else {
return false;
print 'Email and or password didn\'t match';
}
} else {
return false;
print 'Didn\'t enter one of the required values';
}
?>
Somewhere I have an error, I even changed all of the PHP script values to return false and somehow the success message in the ajax still fired successfully. Any help would be greatly appreciated, I've searched the entire forum finding related topics but found nothing that got real in depth with errors.
Thanks
I think you need to actually have thrown an exception for an error handler to be called http://php.net/manual/en/language.exceptions.php false is not an error it's simply not true.
The ajax success callback will fire when a HTTP 200 is returned from the server (in other words, when a proper response is returned). So this means that no matter which code path is executed in your PHP code, the success callback will still be called, and the user will be redirected.
You can either modify the success callback to check the response and act appropriately (preferred), or throw an exception on the server for the return false scenarios.

Categories