jQuery $.post() and PHP issue - php

It's not updating and I'm missing what I'm doing wrong. Uses HTML, jQuery, and PHP. All code is posted below.
What I'm trying to do is allow a user to change a 'client' seed and when it' changed it's updated. In the it's displayed. All that does is refresh every 100ms from a file that's echoing it out. There's no issue there.
PHP Code:
<?php
session_start();
include_once('db.php');
if(isset($_POST['action'])) {
switch($_POST['action']) {
case 'get_client':
echo json_encode(array('result' => $_SESSION['client']));
break;
case 'modify_client':
if(isset($_POST['client']) && strlen($_POST['client']) == 6 && is_numeric($_POST['client'])) {
$_SESSION['client'] = $_POST['client'];
echo json_encode(array('result' => true));
$secret = 123;
$_SESSION['server'] = hash('sha512', $_SESSION['roll'] . $_SESSION['client'] . $secret );
}
else {
echo json_encode(array('result' => false));
}
break;
}
}
?>
Javascript/jQuery:
<script type="text/javascript">
$.post('./php/show_client.php', { action: 'get_client' }, function(result) {
var result = JSON.parse(result);
})
});
$("#client_seed_modify").on("click", function() {
$.post('./php/show_client.php', { action: 'modify_client', client: $("#client_seed").val() }, function(result) {
var result = JSON.parse(result);
if(result ) {
if(result.result) {
alert('Your Client Seed has been changed. This has also changed the server seed. Please note that you have the ability to change your client seed freely, but regardless of whether or not you decide to, it does NOT stay the same every roll.');
}
}
});
</script>
HTML:
<a>Current Client Seed: <span class="clientShow" style=""> </span></a>
<p class="field">
<input type="text" placeholder="Change your Client Seed" name="client" id="cient_seed" class="client_seed">
</p>
<p class="field">
<input type="submit" value="Change Client Seed" style="width: 360px;" name="client_seed_modify" id="client_seed_modify">
</p>

You are confusing server side code and client side code. PHP executes on the server, meaning that any links to resources should be file paths to where the actual files on the server are located. Javascript/JQuery is client side code, meaning that it runs in the user's browser, so any links should be urls not file paths.
Instead of using a local file path on the server like you are now with:
$.post('./php/show_client.php' ...
Your url passed to $.post() should be a URL which accesses that PHP script.
$.post('mysite.com/directory/show_client.php' ...

Related

How to make Phonegap connect to localhost

I am working with phonegap for the first time to build hybrid mobile app with back-end(php, mysql). So i am doing a test on how phonegap can connect to php on localhost to send and retrieve data. But no data was retrieved, I have reduced my codes to the this and i see no errors in both ajax call and php code. So i guess it should be the way phonegap connects to backend that i am getting wrong, please help.
html form and ajax call:
<form id="form1">
<input type="text" id="email" />
<input type="password" id="password" />
<input type="submit" name="login" id="login" value="Login">
</form>
<script type="text/javascript">
$("form").submit(function(){
var data= ("#form1").serialize();
$.post("http://localhost/securityapp/login.php",data,function(response){
alert(response);
});
});
</script>
php file:
<?php
include 'db.php';
session_start();
if ($_POST ) {
echo $_POST;
}
?>
Basically it is meant to alert to values sent to php script as the response but it is not doing so, network tab says 200 for status. what am i doing wrong? I feel phonegap isn't connecting to the url defined
This is how I solved this issue:
created a table on a database that holds the current URL/IP of the server
Created a check-url.php file, this file runs a query on the database to see IP/URL of
the server
I created a connection.js file, this file basically makes a request to a check-url.php
to get current IP of the server to use in Cordova app
check-url.php
header("Access-Control-Allow-Origin: *"); //to allow phonegap access it because of cross origin and domain restrictions
require 'db.php';
$query= "SELECT url FROM settings";
$query= mysqli_query($conn,$query);
$row = mysqli_fetch_assoc($query);
$row= $row['url'];
echo $row; //current IP exmaple:http://127.0.0.1:80/
connection.js
//check current server ip from database
export function check_url(callback) {
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4) { // request is done
if (httpRequest.status === 200) { // successfully
callback(httpRequest.responseText); // we're calling our method
}
}
};
httpRequest.open('GET', "http://127.0.0.1:80/projectname/check-url.php");
httpRequest.send();
}
So any time I want to connect to backend by Cordova I import the function check-url() from connection.js into my front-end ajax request url like this:
<script type="module">
import {check-url} from './connection.js';
check-url(function(result) {
var currentIP= result;
$.ajax({
type:"POST",
url: currentIP + "projectapp/login.php",
data:data,
success: function(data){
//do something
}
});
});
</script>
Note: The URL/IP in connection.js, database, and server IP should be the same, as this helps you not to repeat IP always and also to test when using PhoneGap mobile and also when you switch to live, change it to the current IP address of your project.

AJAX call not sending data to PHP script

I have tried to run an AJAX call within a PHP file, which sends data to another PHP file on the server that is taken from an html input when I press the submit button. Unfortunately when I click on the button, nothing happens, not even in the console. I have tried to debug the issue by creating a window.alert() of the input within the AJAX call, but it somehow shows a certain "object Object" result in the alert box. I have tried to change the path to see if the file is being detected or not, but it seems it is being detected as when I deliberately add a wrong path it throws a 404, and even tried to add echo calls to the PHP file being called but nothing appears. The only issue I can really think of now is something wrong with my implementation, but I'm not sure what it is.
Update: I have tried looking up certain questions such as here and here, but they don't work for me
Code from where the AJAX calls are being made:
<?php
require "../../../AutoLoader.php";
use mvcApplication\core\controllers\ControllerFactory;
?>
<script>
$(document).ready(function () {
$('#submit').click(function () {
$.ajax({
url: '../app/views/generic/deletefunc.php',
type: 'GET',
data: {
Id: $('#Id'),
value: "0"
},
processData: false
});
});
});
</script>
<br>
<br>
<center>
<h3>Enter Teacher ID:</h3><input type="text" id="Id"
placeholder="Input ID here"/>
<br>
<button class="col-sm-4" id="submit">Submit</button>
</center>
<br>
deletefunc.php (code where the data should be received)
<?php
require_once '../../../AutoLoader.php';
use mvcApplication\core\controllers\ControllerFactory;
function deleteTeacher($a)
{
echo $a;
$entity = ControllerFactory::initTeacherC();
$entity->delete($a);
}
function deleteStudent($a)
{
echo $a;
/*$entity = ControllerFactory::initStudentC();
$entity->delete($data);*/
}
function deleteCourse($a)
{
echo $a;
/*$entity = ControllerFactory::initCourseC();
$entity->delete($data);*/
}
if (isset($_GET['Id']) && isset($_GET['value'])) {
switch ($_GET['value']) {
case "0":
deleteTeacher($_GET['Id']);
break;
case "1":
deleteStudent($_GET['Id']);
break;
case "3":
deleteCourse($_GET['Id']);
break;
}
}
According to ajax docs http://api.jquery.com/jquery.ajax/;
processData (default: true) Type: Boolean By default, data passed in
to the data option as an object (technically, anything other than a
string) will be processed and transformed into a query string, fitting
to the default content-type "application/x-www-form-urlencoded".
I think you have to set processData to True on your ajax call because you're using GET (get needs querystring, url data) or just don't set it so it would be the default which is true.

strange behavior while including a class in php

I'm experiencing a strange behavior with PHP. Basically I want to require a class within a PHP script. I know it is straight forward and I did it before but when I do so, it change the behavior of my jquery (1.8.3) ajax response. I'm running a wamp setup and my PHP version is 5.4.6.
Here is a sample as for my index.html
head (omitting the jquery js include)
<script>
$(document).ready(function(){
$('#submit').click(function(){
var action = $('#form').attr('action');
var form_data = {
fname: $('#fname').val(),
lname: $('#lname').val(),
phone: $('#phone').val(),
email: $('#email').val(),
is_ajax: 1
};
$.ajax({
type: $('#form').attr('method'),
url: action,
data: form_data,
success: function(response){
switch(response){
case 'ok':
var msg = 'data saved';
break;
case 'ko':
var msg = 'Oops something wrong happen';
break;
default:
var msg = 'misc:<br/>'+response;
break;
}
$('#message').html(msg);
}
});
return false;
});
});
</script>
body
<div id="message"></div>
<form id="form" action="handler.php" method="post">
<p>
<input type="text" name="fname" id="fname" placeholder="fname">
<input type="text" name="lname" id="lname" placeholder="lname">
</p>
<p>
<input type="text" name="phone" id="phone" placeholder="phone">
<input type="text" name="email" id="email" placeholder="email">
</p>
<input type="submit" name="submit" value="submit" id="submit">
</form>
And as for the handler.php file:
<?php
require('class/Container.php');
$filename = 'xml/memory.xml';
$is_ajax = $_REQUEST['is_ajax'];
if(isset($is_ajax) && $is_ajax){
$fname = $_REQUEST['fname'];
$lname = $_REQUEST['lname'];
$phone = $_REQUEST['phone'];
$email = $_REQUEST['email'];
$obj = new Container;
$obj->insertData('fname',$fname);
$obj->insertData('lname',$lname);
$obj->insertData('phone',$phone);
$obj->insertData('email',$email);
$tmp = $obj->give();
$result = $tmp['_obj'];
/*
Push data inside array
*/
$array = array();
foreach($result as $key => $value){
array_push($array,$key,$value);
}
$xml = simplexml_load_file($filename);
// check if there is any data in
if(count($xml->elements->data) == 0){
// if not, create the structure
$xml->elements->addChild('data','');
}
// proceed now that we do have the structure
if(count($xml->elements->data) == 1){
foreach($result as $key => $value){
$xml->elements->data->addChild($key,$value);
}
$xml->saveXML($filename);
echo 'ok';
}else{
echo 'ko';
}
}
?>
The Container class:
<?php
class Container{
private $_obj;
public function __construct(){
$this->_obj = array();
}
public function addData($data = array()){
if(!empty($data)){
$oldData = $this->_obj;
$data = array_merge($oldData,$data);
$this->_obj = $data;
}
}
public function removeData($key){
if(!empty($key)){
$oldData = $this->_obj;
unset($oldData[$key]);
$this->_obj = $oldData;
}
}
public function outputData(){
return $this->_obj;
}
public function give(){
return get_object_vars($this);
}
public function insertData($key,$value){
$this->_obj[$key] = $value;
}
}
?>
The strange thing is that my result always fall under the default switch statement and the ajax response fit both present statement. I noticed then if I just paste the Container class on the top of the handler.php file, everything works properly but it kind of defeat what I try to achieve.
I tried different way to include the Container class but it seem to be than the issue is specific to this current scenario.
I'm still learning PHP and my guess is that I'm missing something really basic. I also search on stackoverflow regarding the issue I'm experiencing as well as PHP.net, without success.
Regards,
My guess is that you have white space at the end of your class file, which is causing the output to be ' ok' instead of 'ok'. This can be the result of using certain applications to edit your files, or accidentally adding a space after the closing ?>. Try removing the closing ?> in your php class all together. This is not only allowed (php will automatically end processing at the end of the file anyways), but often encouraged in many style guides to prevent exactly the kind of thing that you are describing.
Another thing I usually do for this type of situation, is instead of returning a plain string, I return a json string, which jQuery will automatically turn into a javascript object for you. This would also prevent, or at least let you know right away that you are having the above type of problem.
so php would echo like this:
exit( json_encode( array( 'status' => 'ok' ) ) );
and jQuery would receive like this:
$.ajax({
type: $('#form').attr('method'),
url: action,
data: form_data,
dataType: 'json',
success: function(response){
switch(response.status){
case 'ok':
var msg = 'data saved';
break;
case 'ko':
var msg = 'Oops something wrong happen';
break;
default:
var msg = 'misc:<br/>'+response;
break;
}
$('#message').html(msg);
}
});
Note the added dataType parameter in the ajax call, as well as using response.status to check the status property that we created in PHP.
This also allows you to return more than one value in your response. You can build the object or array however you like on the PHP side, and you would basically receive the same as a javascript object on the javascript side.

Cross Domain Writing to a JSON File via Ajax/JSONP calling an external PHP file

UPDATED AND SOLVED
Thanks to #Christofer Eliasson for the hint. Adding:
header("access-control-allow-origin: *");
to my PHP file solved the issue. Perhaps not the most beautiful way of dealing with the problem but this works.
To make it a bit better/safer:
$http_origin = $_SERVER['HTTP_ORIGIN'];
if ($http_origin == "http://domain1.com")
{
header('Access-Control-Allow-Origin: *');
}
Here is another cross-domain related question.
I have a simple HTML form on domain1.com where a user can add his/her email to a mailing list, here a simple json file, "mails.json", hosted on a second domain (domain2.com).
When the user submits his/her email, a JS script is called whose aim is to check the email and to send the data of the form (here the user's email) to the mails.json file hosted on domain2.com via ajax GET and JSONP.
Ajax calls a PHP script hosted on domain2.com that should get the user's email and write it to mails.json. Moreover, it should send back to domain1.com some messages regarding the success or errors, given that the user has already entered his email before.
Currently, the email is sent and saved to mails.json but I cannot manage to get my PHP script to send back messages to domain1 regarding its execution. Thanks for your advices and feel free to check and modify the code below.
The HTML form hosted on domain1.com
<div id="mail">
<form method="post" action="http://domain2.com/script.php" class="notifyme">
<input type="email" value="" name="email" class="email" id="email" placeholder="Type your email here" required>
<input type="submit" value="Get notified ยป" id="submit" name="submit">
<div class="clear"></div>
</form>
<div class="errmail hide"><span class="uremail"></span> is not a valid email address. Try again :)</div>
<div class="error hide">Ouch :( <span class="uremail"></span> is already registered.</div>
<div class="success hide">Thank You :) <span class="uremail"></span> will be notified once we're ready.</div>
</div>
The Javascript file hosted on domain1.com
//jQuery Initialization
$(function(){
// Form
$('#submit').click(function () { //onSubmit
$('.error,.errmail,.success').hide();
var email = $('input[name=email]').val();
//Email validation
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
var valid = pattern.test(email);
if (!valid && email !== 'undefined') {
$('.errmail').removeClass('hide').show('fast');
if (!email){$('.uremail').append('This');}
else{$('.uremail').append(email);}
return false;
} else {
//start Ajax
$.ajax({
url: "http://domain2.com/script.php?json_callback=?",
dataType: "jsonp text",
//GET method is used
type: "GET",
//pass the data
data: 'email=' + email,
//Do not cache the page
cache: false,
//Cross Domain
crossDomain: true,
//success
success: function (html) {
//if list.php returned 1/true (send mail success)
if (html==1) {
$('.success').removeClass('hide').show('fast');$('.uremail').append(email);
}
else if (html == 0){
$('.error').removeClass('hide').show('fast');$('.uremail').append(email);
}
else { alert('Sorry, unexpected error. Please try again later.'); }
}
});
}
//cancel the submit button default behaviours
return false;
});
});
UPDATED
The PHP "script.php" file hosted on domain2.com
header('content-type: application/json; charset=utf-8');
$http_origin = $_SERVER['HTTP_ORIGIN'];
if ($http_origin == "http://domain1.com")
{
header('Access-Control-Allow-Origin: *');
}
$logname = 'mails.json';
$logcontents = file_get_contents($logname);
//Retrieve form data.
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];
//flag to indicate which method it uses. If POST set it to 1
if ($_POST) $post=1;
if(strpos($logcontents,$email) !== false) {
if ($_POST) {die('You are already subscribed.');}
else{ $result = 0;echo $result; }
}
else {
$filecontents = $email.',';
$fileopen = fopen($logname,'a+');
$filewrite = fwrite($fileopen, json_encode($filecontents) );
$fileclose = fclose($fileopen);
if(!$fileopen or !$filewrite or !$fileclose) {
if ($_POST) {die('Error occured');}
else{ $result = 0;echo $result; }
}
else {
if ($_POST) {echo 'Your email has been added.';}
else{ $result = 1;echo $result; }
}
}
As you set the proper content-type header at the beginning of your script, you can return the data with a regular echo. You will just have to prepare the data to match the JSONP-format first. Something like this:
<?
// Some data to return
$data = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
// JSONP response
echo $_GET['callback'] . '('.json_encode($data).')';
?>
// For this example, the response would be something like this:
// jsonp1277656587731([1,2,3,4,5,6,7,8,9])
When you do a JSONP ajax-request with jQuery, jQuery will automatically send a callback GET-variable for you to use on the server-side. As seen in the example.
Some additional reading: http://www.geekality.net/2010/06/27/php-how-to-easily-provide-json-and-jsonp/
I faced a similar problem in the past and I did try to tinker around with cross domain settings on webserver(Apache2) but no luck. By hit and try I eliminated the hostname from the 'url' parameter of my ajax call and it worked for me. I still did not understand completely though.
Can you quickly check url parameter from :
http://domain2.com/script.php?json_callback=?
to just:
script.php?json_callback=?.
There may be additional web server configuration settings ..but just wanted to see if that worked....

ajax call to check duplicate data

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.

Categories