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.
Related
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");
I'm receiving an error of undefined when I try and retrieve values in the JSON. I'm new to ajax / js etc and trying to create an 'elegant' drop down login down.
I've tried various things and read a few of the posts that I've found here but I notice that the layout has changed somewhat and I also notice that I'm using success and now that deprecated.
So could I ask for help in firstly understanding what the problem is and how i solve the undefined issue and secondly what is the best way to achieve this. I'd prefer not to use deprecated code if I can help it.
I've also noticed that since changing the code so that it gets to the 'success' park of the ajax call, the drop down box no longer rolls back up or displays the error messages. -.-
Thanks in advance.
The Ajax
function validLogin(){
$('.error').hide();
var username = $('#username').val();
if(username == ""){
$('label#usernameError').show();
$('input#username').focus();
return false;
}
$('.error').hide();
var password = $('#password').val();
if(password == ""){
$('label#passwordError').show();
$('input#password').focus();
return false;
}
var params = {username: username, password: password};
var url = "../js/loginProcessAjax.php";
$("#statusLogin").show();
$("#statusLogin").fadeIn(400).html('<img src="images/loading.gif" />');
$.ajax({
type: 'POST',
url: url,
data: params,
datatype: 'json',
beforeSend: function() {
document.getElementById("statusLogin").innerHTML= 'checking...' ;
},
success: function(data) {
alert("success Area ofAjax");
$("#statusLogin").hide();
if(data.success == true){
alert("if data.success Area of Ajax");
alert(data.message);
}else{
alert("data.message... " + data.message);//undefined
$("#errorConsole").html(data.message);
}
},
error: function( error ) {
console.log(error);
}
}, 'json');
}
PHP
<?php
if($_POST){
if($users->userExists($username) === false){
$data['message'] = "User doesn't exist";
$data['success'] = false;
}else if($users->userExists($username) === false){
$data['message'] = 'That username does not exist';
$data['success'] = false;
}else if($users->emailActivated($username) === false){
$data['message'] = 'You need to activate the account, please check your email.';
$data['success'] = false;
}else{
$login = $users->login($username, $password);
if($login === false){
$data['message'] = 'Incorrect Password or username';
$data['success'] = false;
}else{
$data['success'] = true;
//destroy old session and create new - prevents session fixation attacks
session_regenerate_id(true);
//all details are correct - the method returns the id to be sotred as a session
$_SESSION['id'] = $login;
}
echo json_decode($data);
}
}
Markup:
<form method="post" action="" id="ourLoginFormID_JS">
<div class="ourContactFormElement2">
<label for="username">Username:</label>
<input type="text" id="username" name="username" autocomplete="off" class="required" value="<?php if(isset($_POST['username'])) echo htmlentities($_POST['username']); ?>" />
</div>
<div class="ourContactFormElement2">
<label for="password">Password:</label>
<input type="password" id="password" name="password" autocomplete="off" class="required"/>
</div>
<div class="ourContactFormElement2">
<label> </label>
<input type="submit" name="loginButton" id="loginButton" value="Login!" onclick="validLogin(); return false;"/>
</div>
<div id="statusLogin"></div>
</form>
Your if/else/else/else chain only outputs json if the final else block executes. You need to move the json_encode call outside the block:
if (...) {
} else if (...) {
} else if (...) {
} else {
...
}
echo json_encode($data);
This way your code will output the encoded $data, no matter WHICH of the various if() clauses actually executed.
The problem with your undefined error is this:
datatype: 'json',
Javascript is case sensitive and the property is dataType not datatype. Because of this, jQuery is not being told to automatically parse the JSON and so you're just getting the JSON string, causing the undefined error on data.message.
Also I don't see where you access $_POST['username'] or where you instantiate the $users object, I see $username but not $_POST['username'].
A couple of things. You might want to explicitly use contentType parameter of application/json here so that it is clear that you are both sending and receiving JSON.
The main issue is that when sending POST data to PHP that is not form-encoded, $_POST will not be populated automitically. You need to read http raw input like this:
$json = file_get_contents('php://input');
if(!empty($json)) { // replace your if($_POST) with this
$object = json_decode($json);
$username = $object->username;
$password = $object->password;
// the rest of your code
}
Hi I’m quite new to jquery -ajax and I’d like some help please to join it with CI.
I have followed this tutorial on Submitting a Form with AJAX and I’d like to add this functionality to my CodeIgniter site. What I’d like to do is when the user submits the form, if there are any validation errors to show the individually on each input field (as in native ci process), or if this is not possible via validation_errors() function. If no errors occured to display a success message above the form.
Here's my code so far:
my view
// If validation succeeds then show a message like this, else show errors individually or in validation_errors() in a list
<div class="alert alert-success">Success!</div>
<?php echo validation_errors(); //show all errors that ajax returns here if not individualy ?>
<?php echo form_open('admin/product/add, array('class' => 'ajax-form')); ?>
<p>
<label for="product_name">Product *</label>
<input type="text" name="product_name" value="<?php echo set_value('product_name', $prod->product_name); ?>" />
<?php echo form_error('product_name'); ?>
</p>
<p>
<label for="brand">Brand</label>
<input type="text" name="brand" value="<?php echo set_value('brand', $prod->brand); ?>" />
<?php echo form_error('brand'); ?>
</p>
...
my controller
public function add($id){
// set validation rules in CI native
$rules = $this->product_model->rules;
$this->form_validation->set_rules($rules);
if ($this->form_validation->run() === true) {
// get post data and store them in db
$data = $this->input_posts(array('product_name', 'brand', 'category_id', 'description'));
$this->product_model->save($data, $id);
// no errors - data stored - inform the user with display success-div
} else {
// validation failed - inform the user by showing the errors
}
//load the view
$this->load->view('admin/products/add', $data);
}
and here’s the js script
$(document).ready(function () {
$('form.ajax-form').on('submit', function() {
var obj = $(this), // (*) references the current object/form each time
url = obj.attr('action'),
method = obj.attr('method'),
data = {};
obj.find('[name]').each(function(index, value) {
// console.log(value);
var obj = $(this),
name = obj.attr('name'),
value = obj.val();
data[name] = value;
});
$.ajax({
// see the (*)
url: url,
type: method,
data: data,
success: function(response) {
console.log(response); // how to output success or the errors instead??
}
});
return false; //disable refresh
});
});
How should I pass my validation results (either success or the post errors) throught the ajax request and display them on my view??
From some little research I did I've found that you can use a single controller, that holds both the native proccess and the ajax request (instead of using 2 controllers), but my main difficulty is, I don't understand how the results of the validation will pass through the js script and display them on my view?? Please note that I don't want to display anything on an alert box, instead show the results on a div or the errors individualy(if possible).
EDIT I did some changes to my application, here's the code so far:
the controller
public function manage($id = NULL){
$this->load->library('form_validation');
$data['categ'] = $this->category_model->with_parents();
//fetch a single product or create(initialize inputs empty) a new one
if (isset($id) === true) {
$data['prod'] = $this->product_model->get($id);
$data['attr'] = $this->attribute_model->get_by('product_id', $id, null, true);
} else {
$data['prod'] = $this->product_model->make_new();
$data['attr'] = $this->attribute_model_model->make_new();
}
if (isset($_POST['general_settings'])) {
if ($this->form_validation->run('product_rules') === true) {
// get post inputs and store them in database
$data = $this->product_model->input_posts(array('product_name', 'brand', 'category_id', 'general_description'));
$this->product_model->save($data, $id);
$status = true;
} else {
// validation failed
$status = validation_errors();
}
if ( $this->input->is_ajax_request() ) {
echo json_encode($status);
exit;
}
redirect('admin/product');
}
//if (isset($_POST['attributes_settings'])) { the same thing here }
// load the view
$this->load->view('admin/products/manage', $data);
}
and the js
success: function(response) {
//console.log(response);
if (data.status === true) {
$('#ajaxResults').addClass('alert alert-success').html(response);
} else {
$('#ajaxResults').addClass('alert alert-error').html(response);
};
}
But I'm having some issues
Although I get the error messages from validation_errors() as an alert-error when there are no errors I get the true in an alert-error too, insted of alert-success.
2.how should I return the success message too? eg. a message saying "Saves were done!".
Althought in a non-ajax-request the data are stored in the database, in case fo ajax the don't store. Any ideas What may be wrong???
HTML:
<div id="ajaxResults"></div>
Javascript ajax:
success: function(response) {
$('#ajaxResults').text(response);
}
this script you've wrote is only if the validation succeeds, right?
Wrong. The code in "success" gets executed any time you get a response back from the server (assuming the HTTP header is 200). Does your javascript knows if the server has any error for you? No.
You need your JavaScript to recognize if the validation failed or succeeded. You have many ways to do that. One of these could be sending the message to display followed by a 0 or 1.
So your PHP will looks like:
return "0 " . $errorMessage;
and
return "1 " . $successMessage;
and your javascript should then recognize, with if statement and substring, if the message starts with 0 or with 1.
Use this way i hope this will work for you
<script type='text/javascript'>
var base_url = '<?=base_url()?>';
function ajax_call()
{
var ids = $("#all_users").val();
$.ajax({
type:"POST",
url: base_url+"expense/home/get_expense",
data: "userid=" + ids,
success: function(result){
$("#your_div_id").html(result);
}
});
}
</script>
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.
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.