My site works like this:
User has a balance stored in a database under column named currency. He earns currency then after earning enough he goes to another page to get accounts in exchange of these currencies. I set up everything but something is bugging me since an hour. If user has enough currencies and he retrieve an account, he can refresh and retrieve another account and even though he doesn't have enough currencies my system is still giving him his account on firefox but not on chrome (There are the browser I have tested until now) I'm handling this with session, ajax, and php to handle the delivery and here is the codes:
1. In the file below: I check how much the user has currencies and assign an ability session which will then be checked when retrieving the accounts. User can either get an account with currency amount of 250 or 1000 or 2500 and I am checking how much currency he can have on account:
<?php session_start();
unset($_SESSION["ability"]);
$unames = $_SESSION['username'];
$link = mysql_connect( "localhost", "database-username", "database-password");
mysql_select_db("database-name", $link);
$currencyquery = mysql_query("SELECT currency FROM users WHERE username = '$unames'", $link);
while ($row = mysql_fetch_array($currencyquery)) {
$currencyamount = $row['currency'];
}
if ($currencyamount<250){
$_SESSION["ability"]= 'zero';
echo $_SESSION["ability"];
}
elseif ($currencyamount<1000) {
$_SESSION["ability"]= 'one';
echo $_SESSION["ability"];
}
elseif ($currencyamount<2500) {
$_SESSION["ability"]= 'two';
echo $_SESSION["ability"];
}
else {
$_SESSION["ability"]= 'three';
echo $_SESSION["ability"];
}
?>
I then have the jquery file listening to this php file, for its echos, which will if the user has an ability of 1 allow him to get an account with 250 currencies, if he has an ability of 2: 1000 currencies, if he has an ability of 3: 2500 currencies. If he has ability 0, he won't get any account if he tries, it alerts him to refresh and if he tries to get two accounts or more without refreshing (Did this because I wanted to unset the session when the page loads again then set them because the abilities may change) The script also deletes each account the user got from the database.
$(document).ready(function () {
var ability = 'zero';
var click = 0;
$.ajax({url: "ability.php"}).done(function( html ) {
ability = html
});
$('#currency2500').click(function(){
if (click==0){
if (ability != 'zero') {
function show_account() {
$.ajax({
type: "POST",
url: "select1.php",
data:{action:"showroom"},
success: function (data) {
$('#accountinfo').html(data);
}
});
}
show_account();
click = click + 1;
}
} else if(ability == 'zero') {
alert("You dont have the required amount of currencies.");
} else {
alert('Refresh the page');
}
});
$('#currency250').click(function(){
if(click==0){
if (ability != 'zero') {
var id=$(this).data("id3");
$.ajax({
url:"delete1.php",
method:"POST",
data:{id:id},
dataType:"text",
success:function(data){
show_account();
}
});
}
} else if(ability == 'zero') {
alert("You dont have the required amount of currencies.");
}
});
$('#currency1000').click(function(){
if(click==0){
if (ability != 'zero' && ability != 'one') {
function show_account() {
$.ajax({
type: "POST",
url: "select2.php",
data:{action:"showroom"},
success: function (data) {
$('#accountinfo').html(data);
}
});
}
show_account();
click = click + 1;
}
} else if(ability == "zero" || ability == "one") {
alert("You dont have the required amount of currencies.");
} else {
alert('Refresh the page');
}
});
$('#currency1000').click(function(){
if(click==0){
if (ability != 'zero' && ability != 'one') {
var id=$(this).data("id3");
$.ajax({
url:"delete2.php",
method:"POST",
data:{id:id},
dataType:"text",
success:function(data){
show_account();
}
});
}
} else if(ability == "zero" || ability == "one") {
alert("You dont have the required amount of currencies.");
}
});
$('#currency2500').click(function(){
if(click==0){
if (ability == 'three'){
function show_account() {
$.ajax({
type: "POST",
url: "select3.php",
data:{action:"showroom"},
success: function (data) {
$('#accountinfo').html(data);
}
});
}
show_account();
click = click + 1;
}
} else if(ability != 'three') {
alert("You dont have the required amount of currencies.");
} else {
alert('Refresh the page');
}
});
$('#currency2500').click(function(){
if(click==0){
if (ability == 'three'){
var id=$(this).data("id3");
$.ajax({
url:"delete3.php",
method:"POST",
data:{id:id},
dataType:"text",
success:function(data){
show_account();
}
});
}
} else if(ability != 'three') {
alert("You dont have the required amount of currencies.");
}
});
});
Here is the php file that will deliver the account with 250 currencies to the user, there is also the ones which are the same for 1000, 2500 and with just the value 250 changed. if its called by jquery:
<?php
session_start();
$link = mysqli_connect( 'localhost', 'database-username', 'database-password', 'database' );
$action=$_POST["action"];
if($action=="showroom") {
$query="SELECT * FROM tablename LIMIT 1";
$show = mysqli_query($link, $query) or die("Error");
echo "<p id='paragraph' style='font-size:22px;font-weight: bold;'>Here is your 250 currencies account:</p>";
echo "<table style='position:relative;bottom:30px;' border='2px'><tr><td>Email</td><td>id</td></tr>";
while ($row = mysqli_fetch_array($show)) {
echo "<tr><td>" . $row['email'] . "</td><td>" . $row['id'] . "</td></tr>";
}
echo "</table>";
$unames = $_SESSION['username'];
$query2 = "UPDATE users SET currency=currency-250 WHERE username='$unames'";
$update = mysqli_query($link, $query2);
$link = mysql_connect( "localhost", "database-username", "database-password");
mysql_select_db("database", $link);
$currencyquery = mysql_query("SELECT currency FROM users WHERE username = '$unames'", $link);
while ($row = mysql_fetch_array($currencyquery)) {
$currencyvalue = $row['currency'];
}
unset($_SESSION['currencynumber']);
$_SESSION["currencynumber"]=strval($currencyvalue);
}
?>
Then the page which users gets in: ( Only a part from it )
<?PHP
session_start();
if( !isset($_SESSION['username']) ) {
header ("Location: login.html");
}
<div id="accountinfo"></div>
<input type="button" id="currency2500" value="Get 2500 currencies" />
<input type="button" id="currency1000" value="Get 1000 currencies" />
<input type="button" id="currency250" value="Get 250 currencies" />
So: If using firefox: I can refresh 2-4 times until i can't get accounts anymore and my balance will be negative after getting those accounts. Maybe there is a way that if the balance gets negative to cancel the operation and not show anything to the user? Or how can it be solved? I am using sessions to track.
Related
New to php and mysqli. I have a working php / mysqli search page with ajax for a table containing part number, description, price and quantity-in-stock. I can write an alternate SELECT query that limits the results to items with stock > 0.
What I want is to add a checkbox on the form that allows the user to choose between all results, or just results of items in stock (greater than zero).
I have tried to test for stocked using if(isset($_GET['stocked'])) but have no success. What am I missing? Any help is appreciated.
<script type="text/javascript">
$(function() {
$(".search_button").click(function() {
var search_word = $("#search_box").val();
var dataString = 'search_word=' + search_word;
if (search_word == '') {
} else {
$.ajax({
type: "GET",
url: "searchdata.php",
data: dataString,
cache: false,
beforeSend: function(html) {
document.getElementById("insert_search").innerHTML = '';
$("#flash").show();
$("#searchword").show();
$(".searchword").html(search_word);
$("#flash").html('<img src="ajax-loader_2.gif" /> Loading Results...');
},
success: function(html) {
$("#insert_search").show();
$("#insert_search").append(html);
$("#flash").hide();
}
});
}
return false;
});
});
</script>
<form method="get" action="">
<input type="checkbox" name="stocked" value="Yes"><label> Display in-stock items only</label>
<input type="text" name="search" id="search_box" class='search_box'/>
<input type="submit" value="Search" class="search_button" />
</form>
<?php
include('dbconnect.php');
if (isset($_GET['search_word'])) {
$search_word = $_GET['search_word']; //get value sent from search form
$min_length = 2; //2 character minimum for search
if (strlen($search_word) >= $min_length) { // if query length is more than or equal to minimum length, then
$search_word = htmlspecialchars($search_word); //change characters used in html to their equivalents
$search_word_new = mysqli_escape_string($conn,$search_word); //prevent SQL injection
$search_word_fix = str_replace(" ","%",$search_word_new);
// $raw_results = mysqli_query($conn,"SELECT * FROM stock WHERE partnumber LIKE '$search_word_fix%' AND availability > 0 ORDER BY partnumber LIMIT 10"); //in stock
$raw_results = mysqli_query($conn,"SELECT * FROM stock WHERE partnumber LIKE '$search_word_fix%' ORDER BY partnumber LIMIT 10"); //all
if(mysqli_num_rows($raw_results) > 0) { //one or more rows are returned
while($row = mysqli_fetch_array($raw_results)) { //put table data into array and loop while valid
echo "<hr class='gryhr'><br>{$row['partnumber']}<br>";
echo "<p>".$row['description']."<br>".
"List price $".$row['listprice']."<br>".
"In stock: ".$row['availability']."</p><br>";
}
echo "<hr>Total Results: " .mysqli_affected_rows($conn);
}
else { //no matching rows found
echo '<div>No Results</div>';
}
}
else { // if query length less than minimum
echo "Enter minimum of ".$min_length." characters";
}
}
mysqli_close($conn);
?>
Looks like your not sending the checkbox value to your PHP code at all ... You could do something like this:
var dataString = $('#myForm').serializeObject();
$('#myForm input[type=checkbox]').each(function() { dataString[this.name] = this.checked; });
You will have to modify yout script a little thought.
add id myForm to your form element and change the name of your search imput to search_word.
in a nutt shell it would look like
-- EDIT -- full code would look like this
<?php
// If form submited
include('dbconnect.php');
if (isset($_POST['search_word'])) {
$search_word = $_POST['search_word']; //get value sent from search form
$min_length = 2; //2 character minimum for search
if (strlen($search_word) >= $min_length) { // if query length is more than or equal to minimum length, then
$search_word = htmlspecialchars($search_word); //change characters used in html to their equivalents
$search_word_new = mysqli_escape_string($conn,$search_word); //prevent SQL injection
$search_word_fix = str_replace(" ","%",$search_word_new);
// $raw_results = mysqli_query($conn,"SELECT * FROM stock WHERE partnumber LIKE '$search_word_fix%' AND availability > 0 ORDER BY partnumber LIMIT 10"); //in stock
if (isset($_POST['stocked'])){ $stocked = " and stocked > 0";}
$raw_results=mysqli_query($conn,"SELECT * FROM stock WHERE partnumber LIKE '$search_word_fix%' $stocked ORDER BY partnumber LIMIT 10"); //all
if(mysqli_num_rows($raw_results) > 0) { //one or more rows are returned
while($row = mysqli_fetch_array($raw_results)) { //put table data into array and loop while valid
echo "<hr class='gryhr'><br>{$row['partnumber']}<br>";
echo "<p>".$row['description']."<br>".
"List price $".$row['listprice']."<br>".
"In stock: ".$row['availability']."</p><br>";
}
echo "<hr>Total Results: " .mysqli_affected_rows($conn);
}
else { //no matching rows found
echo '<div>No Results</div>';
}
}
else { // if query length less than minimum
echo "Enter minimum of ".$min_length." characters";
}
}
mysqli_close($conn);
?>
as for your view part
<script type="text/javascript">
$(document).ready( function() { // Wait until document is fully parsed
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$("#myForm").on('submit', function(e){
e.preventDefault();
var dataString = $('#myForm').serializeObject();
$('#myForm input[type=checkbox]').each(function() { dataString[this.name] = this.checked; });
if (dataString['search_word'] != '') {
$.ajax({
type: "POST",
url: "searchdata.php",
data: dataString,
cache: false,
beforeSend: function(html) {
// ...
},
success: function(html) {
$("#insert_search").show();
$("#insert_search").append(html);
$("#flash").hide();
}
});
}
return false;
});
});
</script>
<form id="myForm" action="" method="post">
<input type="checkbox" name="stocked" value="Yes"><label> Display in-stock items only</label>
<input type="text" name="search_word" id="search_box" class='search_box'/>
<input type="submit" value="Search" class="search_button" />
</form>
The code you had was not working because you where sending the data using the form and you where also sending the data using ajax. You need to choose one or the other. Not both. In the above, I am sending it by ajax call and preventing the default form submit. I am also sending using POST instead of GET.
i have a pretty basic voting system i have implemented on my site. using the following ajax when a user clicks on the link there vote is added to the database and the vote is updated +1.
this all works fine but i would like to check if the user is logged in before allowing them to vote if there not display an error pop up or redirect to the login page (eventually i will display a lightbox popup asking for them to login or register.
<script type="text/javascript">
$(document).ready(function() {
$(".voteup a").click(function() {
var ID = <?php echo $moviedetails['id'] ?>
//$("#vote").text();
var rating = <?php echo $vote['vote_up'] ?>
var queryString = 'id=' + ID + '&vote=' + rating;
$("#voteup").text (rating + 1);
$.ajax({
type: "POST",
url: "vote_up.php",
data: queryString,
cache: false,
success: function(html) {
$("#votethanks").html('Thanks');
$("#votethanks").slideDown(200).delay(2000).fadeOut(2000);
}
});
});
});
</script>
and vote_up.php
<?php
require_once("header.php");
$data = $_POST['id'];
$updatevote = "UPDATE `vote` SET `vote_up` = vote_up +1 WHERE `movie_id` = '$data'";
mysqli_query($con, $updatevote);
?>
i have tried
if (!(isset($_SESSION['sess_user_id']) && $_SESSION['sess_user_id'] != '')) {
echo "<script>alert('Please login.')</script>";
}
else { //then the javascript
but it just checks the users logged in on page load, if there not it displays the please login error, but i need it to do this onclick of the javascript.
any help appreciated
thanks
lee
You can consider doing the check with PHP in the vote_up.php and check the response in your ajax. Something like this:
$.ajax({
type: "POST",
url: "vote_up.php",
data: queryString,
cache: false,
success: function(result) {
if (result.error) {
alert(result.msg);
} else {
$("#votethanks").html(result.msg);
$("#votethanks").slideDown(200).delay(2000).fadeOut(2000);
}
}
});
in your vote_up.php:
<?php
if (!(isset($_SESSION['sess_user_id']) && $_SESSION['sess_user_id'] != '')) {
// User is not logged in!
$result = array(
'error' => true,
'msg' => 'Please login first!'
);
} else {
// write the needed code to save the vote to db here
$result = array(
'error' => false,
'msg' => 'Thanks!'
);
}
// Return JSON to ajax call
header('Content-type: application/json');
echo json_encode($result);
Why not use your PHP to insert into a authenticated variable, just as you do with vote and ID?
For example:
var authenticated = <?php !(isset($_SESSION['sess_user_id']) && $_SESSION['sess_user_id'] != '') ?>
Note: Completely untested. I just copied and pasted the php code from your "I have tried..."
Does this help?
Add a boolean. Every time the user clicks on the voting, send an ajax call to check if the user is logged in.
$(document).ready(function()
{
$(".voteup a").click(function()
{
var the_user_is_logged_in;
the_user_is_logged_in = checkLoggedIn();
if the_user_is_logged_in{
// do ajax call
}
else{
alert('Please log in!')
}
}
}
function checkLoggedIn(){
$.get('getsession.php', function (data) {
return data;
});
And in getsession.php you should write
<?php
session_start();
print json_encode($_SESSION);
I didn't try the code, but it should work.
This is what worked for me in the end. I am only sharing this to help someone who my encounter the same problem and end up with a migraine.
The ajax script:
<script type="text/javascript">
function review_likes ( addresscommentid )
{ $.ajax( { type : "POST",
async : false,
data : { "txt_sessionid" : addresscommentid },
url : "functions/review_likes.php",
beforeSend: function() {
// checking if user is logged in with beforeSend
<?php if (!(isset($_SESSION['signed_in_uid']) &&
$_SESSION['signed_in_uid']
!= '')) { ?>
$(window.location.href = 'admin/index-signin.php');
<?php } ?>
},
success : function ( sessionid )
{
$('#reviewlikes').removeClass('like-action');
$('#reviewlikes').load(document.URL + ' #reviewlikes');
},
error : function ( xhr )
{
alert( "You are not Logged in" );
}
});
return false;
}
</script>
On the review_likes.php page header:
<?php
$kj_authorizedUsers = "";
$kj_restrictGoTo = "../admin/index.php";
if (!((isset($_SESSION['kj_username'])) &&
(isAuthorized("",$kj_authorizedUsers,
$_SESSION['kj_username'], $_SESSION['kj_authorized'])))) {
$kj_qsChar = "?";
$kj_referrer = $_SERVER['PHP_SELF'];
if (strpos($kj_restrictGoTo, "?")) $kj_qsChar = "&";
if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0)
$kj_referrer .= "?" . $_SERVER['QUERY_STRING'];
$kj_restrictGoTo = $kj_restrictGoTo. $kj_qsChar . "accesscheck=" .
urlencode($MM_referrer);
header("Location: ". $kj_restrictGoTo);
exit;
}
?>
The above code is a bit overkill, but it helps to get the current URL and redirect the user to the requesting page after successful login.
There are many posts that are made by users, I want each post (or div in this case) to display the background color green or grey depending on the user status (logged in or not).
What I am trying to achieve is while idling on the page, you should see a user going online without refreshing the page
status.php
if (logged_in() === true){
$res8 = mysql_query("SELECT * FROM `users` WHERE status=1 LIMIT 1");
if(mysql_num_rows($res8) > 0){
while($row8 = mysql_fetch_assoc($res8)){
if ($row8['status'] === "1") {
echo "online";
}
}
}
}else {
echo "offline";
}
Main page
$res8 = mysql_query("SELECT * FROM `users` WHERE user_id='".$user_id."' LIMIT 1");
if(mysql_num_rows($res8) > 0){
while($row8 = mysql_fetch_assoc($res8)){
?>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function(){
$.ajax({
url: 'status.php',
datatype:"application/json",
type: 'GET',
success: function(data) {
if (data === "online") {
$('.status').css({background: '#40A547'});
} else {
$('.status').css({background: '#7f8c8d'});
}
}
});
}, 5000);
});
</script>
<?php
}
}
}
echo '<div class="status">TEST</div></a></div>';
This code changes the background color of all the divs but I want it to only target the divs that correspond to the user that logged in (the creator of the post).
Not sure how to make the div have the dynamic styling using ajax.
Any help is much appreciated!
You can use the id user from the database to achieve this. Then add an id to the div corresponding to the user id. For instance :
Ajax Request in success :
$('.status #user'+ dataId).css({background: '#7f8c8d'});
In your HTML :
echo '<div class="status" id="user1">TEST</div></a></div>';
Edit
Your Main page (your AJAX request)
$.ajax({
url: 'status.php',
dataType: "json",
type: 'GET',
success: function(data) {
if (data.message === "online")
{
$('.status #user'+ data.userId).css({background: '#40A547'});
} else // data.message === "offline"
{
$('.status #user'+ data.userId).css({background: '#7f8c8d'});
}
}
});
//...
// HTML looks like...
echo '<div class="status" id="user1">TEST</div></a></div>';
echo '<div class="status" id="user2">TEST2</div></a></div>';
status.php
You set the dataType of your ajax request that you want return Json but it's unclea, your your status.php add the header content-type to json.
<?php
header('Content-Type: application/json'); // So add this
//...
$array = array(); // New variable which would be return as json
if (logged_in() === true) // Your online part
{
$res8 = mysql_query("SELECT * FROM `users` WHERE status=1 LIMIT 1");
if(mysql_num_rows($res8) > 0){
while($row8 = mysql_fetch_assoc($res8)){
if ($row8['status'] === "1") {
$array['message'] = 'online';
$array['userId'] = $row8['user_id']; // Here is the userId (adapt following your code)
}
}
}
}// Your offline part
else {
$array['message'] = 'offline';
}
echo json_encode($array);
I cannot get this script work. I try to warn if login that user entered is available. But I cannot manage this script to work:
$( "#myRegForm" ).submit(function( event ) {
var errors = false;
var userAvi = true;
var loginInput = $('#login').val();
if( loginInput == ""){
$("#errorArea").text('LOGIN CANNOT BE EMPTY!');
$("#errorArea").fadeOut('15000', function() { });
$("#errorArea").fadeIn('15000', function() { });
errors = true;
}
else if(loginInput.length < 5 ){
$("#errorArea").text('LOGIN MUST BE AT LEAST 5 CHARACTERS!');
$("#errorArea").fadeOut('15000', function() { });
$("#errorArea").fadeIn('15000', function() { });
errors = true;
}
else if (loginInput.length >=5) {
$.post('checkLogin.php', {login2: loginInput}, function(result) {
if(result == "0") {
alert("this");
}
else {
alert("that");
}
});
}
if (errors==true) {
return false;
}
});
Everything works fine until loginInput.length >=5 else block. So I assume there is a problem with getting answer from PHP file, but I cannot handle it, though I tried many different ways. Here is checkLogin.php's file (note that jQuery script and PHP file are in the same folder):
<?php
include ("bd.php");
$login2 = mysql_real_escape_string($_POST['login2']);
$result = mysql_query("SELECT login FROM users WHERE login='$login2'");
if(mysql_num_rows($result)>0){
//and we send 0 to the ajax request
echo 0;
}
else{
//else if it's not bigger then 0, then it's available '
//and we send 1 to the ajax request
echo 1;
}
?>
<?php
include ("bd.php");
$login2 = mysql_real_escape_string($_POST['login2']);
$result = mysql_query("SELECT login FROM users WHERE login='$login2'");
if(mysql_num_rows($result)>0){
//and we send 0 to the ajax request
echo "0"; // for you to use if(if(result == "0") you should send a string
} else {
//else if it's not bigger then 0, then it's available '
//and we send 1 to the ajax request
echo "1";
}
?>
You're literally sending the string 'loginInput'.
change
$.post('checkLogin.php', {login2: 'loginInput'}, function(result) {
to
$.post('checkLogin.php', {login2: loginInput}, function(result) {
Edit
I would just comment out everything except the following for now and see if that at least works
$.post('checkLogin.php', {login2: 'loginInput'}, function(result) { // put loginInput back in quotes
alert('#'+result+'#'); // # to check for whitespace
});
I wrote some ajax validation for email check by verifying the availability using php the ajax script just displays whether email is available or not?
<script type="text/javascript">
$(document).ready(function()
{
$("#email_id").change(function(){
var email = $("#email_id").val();
var regdata = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if(!(regdata).test($("#email_id").val()))
{
$("#email_id").css('border','1px solid red');
$("#email_id").focus();
$("#status").html("enter the valid emailid!");
return false;
}
else{
$("#email").css('border','1px solid #7F9DB9');
$("#email_id").html('Checking Email Availability...');
$.ajax({
type: "POST",
url: "fresherreg_email_avail.php",
data:"q="+ email,
success: function(server_response){
$("#status").ajaxComplete(function(event,request){
if(server_response == '0')
{
$("#status").html('Email Available');
}
else if(server_response == '1')
{
$("#status").html('Email Not Available');
}
});
}
});
}
});
});
</script>
and my php availability check code is
<?php
include_once("include_dao.php");
$q = $_REQUEST['q'];
if($q != "")
{
$row=DAOFactory::getTblFreshersRegistrationDAO()->queryByEmailId($q);
$num = count($row);
if($num > 0)
{
echo "1";
}
else
{
echo "0";
}
}
else
{
echo "Email Id should not be empty";
}
?>
what i need is?
it should show an alert using script until he choose a new mail id
It can be done this way . I will edit your code and add the required thing .
In the javascript/jquery part:
<script type="text/javascript">
$(document).ready(function()
{
$("#email_id").change(function(){
var email = $("#email_id").val();
var regdata = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if(!(regdata).test($("#email_id").val()))
{
$("#email_id").css('border','1px solid red');
$("#email_id").focus();
$("#status").html("enter the valid emailid!");
return false;
}
else{
$("#email").css('border','1px solid #7F9DB9');
$("#email_id").html('Checking Email Availability...');
$.ajax({
type: "POST",
url: "fresherreg_email_avail.php",
data:"q="+ email,
success: function(server_response){
if(server_response == '0')
{
$("#status").append("<font color='green'>email available</font>");
}
else if(server_response == '1')
{
$("#status").append("<font color='red'>email already exits</font>");
}
else
{
$("#status").append("<font color='red'>"+server_response+"</font>");
}
}
});
}
});
});
</script>
Now in your php script .
<?php
include_once("include_dao.php");
$q = $_REQUEST['q'];
if($q != "")
{
$row=DAOFactory::getTblFreshersRegistrationDAO()->queryByEmailId($q);
$num = count($row);
if($num > 0)
{
echo "1";
}
else
{
echo "0";
}
}
else
{
echo "Email Id should not be empty";
}
?>
<script type="text/javascript">
$(document).ready(function(){
$('#submit');
var emaildone = false;
var myRegForm = $("#registration"),email = $("#email_id"), status = $("#status");
myRegForm.submit(function(){
if(!emaildone)
{
alert("Email Id Already Exists!!! So Please Try Another Email Id");
email.attr("value","");
email.focus();
return false;
}
});
email.blur(function(){
$.ajax({
type: "POST",
data: "q="+$(this).attr("value"),
url: "fresherreg_email_avail.php",
beforeSend: function(){
status.html('<img src="images/loader.gif" align="absmiddle"><font color="blue">Checking Email Availability...</font>');
},
success: function(data){
if(data == "invalid")
{
emaildone = false;
status.html("<font color='red'>Inavlid Email!! Please Select a Vaild Email</font>");
}
else if(data != "0")
{
emaildone = false;
status.html('<img src="images/not_available.png" align="absmiddle"><font color="red">Email Already Exist</font>');
}
else
{
emaildone = true;
status.html('<img src="images/available.png" align="absmiddle"> <font color="green">Email Available</font>');
}
}
});
});
});
</script>
Change script to this.