check username exists using ajax - php

I use this code to check username exists in database before or not. code works good and shows available or taken username. now i want to submit button should be disable when user select username that was taken befor and enable when username available . please guide me how.
$(document).ready(function() {
$('#username').keyup(function() {
$.post('adm/chk_uname_avail.php', {
uname : changeuser.username.value
}, function(result){
$('#available').html(result);
})
})
})

I'm using the old $.ajax function and make sure you have a data keyed taken (as example) with boolean type on adm/chk_uname_avail.php and notice that you should return JSON data type from it.
Example of adm/chk_uname_avail.php
<?php
//return response as JSON
header('Content-type:application/json;charset=utf-8');
....
....
....
$data['taken'] = true; //show this response to ajax
echo json_encode($data);
?>
Ajax
$(document).ready(function() {
$('#username').on('keyup', function() {
$.ajax({
type: 'POST',
url: 'adm/chk_uname_avail.php',
data: {uname : changeuser.username.value},
success: function(result) {
var $btn = $('#submiButton');
if (result.taken) {
$btn.prop('disabled', true);
} else {
$btn.prop('disabled', false);
}
//As #Mikey notice, You can just use this as simply as
//$('#submiButton').prop('disabled', result.taken);
}
});
});
});

Use .attr() method of jQuery to make the submit disabled on certain condition.
So you can update your jQuery like this,
$.post('adm/chk_uname_avail.php', {
uname : changeuser.username.value
}, function(result){
$('#available').html(result);
if(/* CHECK FOR CERTAIN CONDITION */) {
$('#submit_btn').attr('disabled','disabled');
}
});
To remove the disabled attribute you can use removeAttr() method of jQuery. Like this,
$('#submit_btn').removeAttr('disabled');
http://api.jquery.com/attr/
https://api.jquery.com/removeAttr/

Related

How to send data from one page to another and upon success show a modal

This is my page from where I want to send data to dashboard/fpass.php page and upon success show a modal.
<script>
$(document).ready(function () {
$('#fmodal').click(function () {
$.ajax({
type: "POST",
url: "dashboard/fpass.php",
data: { name: "fpass" }
})
success: function(data) {
$("#myModal").modal();
}
});
});
</script>
And here is my next page where I want to get my data and send a mail.
<?php
if(($_POST['name'])=='fpass')
{
/*add sql connection*/
require('../includes/dbconfig.php');
/*get the image file name from the table*/
$sql="select * from admin";
$res=mysqli_query($con,$sql);
$row=mysqli_fetch_array($res);
$email=$row['email'];
$password=$row['password'];
$bemail=$row['bemail'];
$sub="dashboard login password is < ".$password." >";
/*send mail to the sql entry*/
mail($email,"Forget Password Request",$sub,$bemail);
}
?>
Try changing your AJAX:
<script>
$(document).ready(function(){
$('#fmodal').click(function(){
var name = 'fpass';
$.ajax({
type: "POST",
url: "dashboard/fpass.php",
data: { name: name },
success: function(data) {
$("#myModal").modal('show');
}
});
});
});
</script>
Man, the problem that I see is in the receiving code. AJAX needs to get some response from that file, you are not sending anything back, that's why. When you execute the mail() function, if CORRECT, then return true, 1 or any message that you want referring to the successful operation.
Try this:
if (mail($email,"Forget Password Request",$sub,$bemail))
echo true; //or echo 1, something referring to successful execution
else {
/**
* If you want to use the error{} part of the AJAX, you need to send different headers
* header('HTTP/1.1 500 Internal Server Error');
*/
// And then the echo, or just the echo is fine if you want to use it in the success section
echo false; // or echo 0, somtehing referring to a failed execution
}
In the AJAX side, you get the response, and evaluate if is true or false and then you decide what to do.
Hope that can help. J.C!
Your JS code is not valid. Have a look here, to see how $.ajax(...) is used:

how to post a persian statement with spaces in ajax url

I have used ajax as below:
$('.province').on('click', function (e)
{
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
var valueSelected = valueSelected.replace(/ /gi,"%20");
var valueSelected = encodeURIComponent(valueSelected);
//alert(valueSelected);
$.ajax({
type: 'post',
encoding:"UTF-8",
url: "<?php echo base_url();?>Search/cities_of_province/"+valueSelected,
data: '',
contentType: "charset=utf-8",
success: function (result) {
//alert(result);
$('.city').html(result);
return false;
}
});
return false;
});
valueSelected in above url is a persion statement with space in it. for example it is استان آذربایجان شرقی.
when it is post to the url, just first part(استان) is recieved.
I aslo removed valueSelected.replace(/ /gi,"%20") and encodeURIComponent(valueSelected) but nothing happend.
what is the solution?
I faced no issue like that.. I used no encodeURIComponent no encoding:"UTF-8" no contentType: "charset=utf-8"
Nothing needed. And it works simply perfect. I tested it with following code
I have Html
<input id='yourInputId' value='استان آذربایجان شرقی' />
JavaScript
<script>
var valueSelected = $('#yourInputId').val();
//before ajax request
alert(valueSelected ); // it gives me here =>استان آذربایجان شرقی
//before making ajax reuest plz confirm you get above value correctly here
alert(<?php echo base_url();?>); //it must be valid as well
$.ajax
({
type: "POST",
url: "<?php echo base_url();?>Search/cities_of_province", //should be valid
data: { province : valueSelected },
success: function (result) {
alert(result); //it gives => استان آذربایجان شرقی
},
error:function(a)
{
alert(a.responseText);
}
});
</script>
PHP
<?php
if(isset($_POST['province']))
$v = $_POST['province'];
else
$v = 'Province value not provided from client side';
echo $v;
?>
So it looks like you are using a select input here. If that is the case, you should use alphanumeric/ASCII value key in your options and not the human readable labels. That might look like:
<option value="some_ascii_key">استان آذربایجان شرقی</option>
You can then have a reliable key to use in your AJAX request.
I also think your request should be a GET and not a POST since you are just reading values from API rather than trying to create/update records via API.
Putting it all together, you might have something like this:
// note values for each property/ley may not be important here
// as they are not really needed to validate that the province key
// in option value has not been modified by client,
// which is really what you are using this for.
// If you need to have option label text available in
// javascript you can store that here as shown.
var provinceConfiguration = {
'key1': 'استان آذربایجان شرق';
'key2': 'some other Persian string';
// and so on...
}
$('.province').on('click', function (e)
{
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
// perhaps validate that value provided is amongst expected keys
// this used the provinceConfiguration object proposed in this example
if(typeof provinceConfiguration[valueSelected] === 'undefined') {
console.log('Unexpected province key passed');
e.stopPropagation();
return false;
}
// probably can drop this line if defined keys do not need encoding
var valueSelected = encodeURIComponent(valueSelected);
// since you can use default GET setting you can use this shorthand
$.get(
'<?php echo base_url();>Search/cities_of_province/' +
valueSelected,
function(result) {
// console.log(result);
$('.city').html(result);
return false;
}
);
/*
Or more verbose option
$.ajax({
type: 'GET',
// not valid setting key -> encoding:"UTF-8",
url: '<?php echo base_url();>Search/cities_of_province/' + valueSelected,
// default is fine here so not needed -> contentType: "charset=utf-8",
success: function (result) {
// console.log(result);
$('.city').html(result);
return false;
}
});
*/
return false;
});
Note that you should be using console.log() to debug code rather than alert(), as alert actually blocks code execution and may make some debugging more problematic as your debugging mechanism changes how your code executes. This can problem can be exacerbated when debugging asynchronous code.
Your server-side code would obviously need to be updated to understand the province keys as well.
Please take a look at this javascript library. That can be of help to you.
Fix Persian zero-width non-joiner(Replace spaces by half-space)
import { halfSpace } from "persian-tools2";
halfSpace("نمی ‌خواهی درخت ها را ببینیم؟") // "نمی‌خواهی درخت‌ها را ببینیم؟"
Fix Persian characters in URL.
import { isPersian, toPersianChars } from "persian-tools2";
URLfix(
"https://fa.wikipedia.org/wiki/%D9%85%D8%AF%DB%8C%D8%A7%D9%88%DB%8C%DA%A9%DB%8C:Gadget-Extra-Editbuttons-botworks.js",
); // "https://fa.wikipedia.org/wiki/مدیاویکی:Gadget-Extra-Editbuttons-botworks.js"
URLfix("https://en.wikipedia.org/wiki/Persian_alphabet"); // "https://en.wikipedia.org/wiki/Persian_alphabet",
URLfix("Sample Text"); // "Sample Text"

Using Ajax to generate an alert box

I want to pop up an alert box after checking whether some data is stored in the database. If stored, it will alert saved, else not saved.
This is my ajax function:
AjaxRequest.POST(
{
'url':'GroupsHandler.php'
,'onSuccess':function(creategroupajax){ alert('Saved!'); }
,'onError':function(creategroupajax){ alert('not saved');}
}
);
but now it show AjaxRequest is undefined.
How can I fix this?
This of course is possible using Ajax.
Consider the below sample code for the same.
Ajax call :
$.ajax({
url: 'ajax/example.php',
success: function(data) {
if(data == "success")
alert('Data saved.');
}
});
example.php's code
<?php
$bool_is_data_saved = false;
#Database processing logic here i.e
#$bool_is_data_saved is set here in the database processing logic
if($bool_is_data_saved) {
echo "success";
}
exit;
?>
function Ajax(data_location){
var xml;
try {
xml = new XMLHttpRequest();
} catch (err){
try {
xml = new ActiveXObject("Msxml2.XMLHTTP");
} catch (error){
try {
xml = new ActiveXObject("Microsoft.XMLHTTP");
} catch (error1){
//
}
}
}
xml.onreadystatechange = function(){
if(xml.readyState == 4 && xml.status == 200){
alert("data available");
}
}
xml.open("GET", data_location, true);
xml.send(null);
}
window.onload = function(){
Ajax("data_file_location");
}
You can create an addtitional table with date(time) of last update database and check if this date is later. You can use standard setInterval function for it.
This is possible using ajax. Use jQuery.ajax/pos/get to call the php script that saves the data or just checks if the data was saved previously (depends on how you need it exactly) and then use the succes/failure callbacks to handle its response and display an alert if you get the correct response.
Below code based on jQuery.
Try it
$.ajax({
type: 'POST',
url: 'http://kyleschaeffer.com/feed/',
data: { postVar1: 'theValue1', postVar2: 'theValue2' },
beforeSend:function(){
// this is where we append a loading image
$('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
},
success:function(data){
// successful request; do something with the data
$('#ajax-panel').empty();
$(data).find('item').each(function(i){
$('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
});
},
error:function(){
// failed request; give feedback to user
$('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
use the ajax to call the script and check values in the database through the script. If
data present echo success else not.lets look an example of it.
Assuming databasename = db
Assuming tablename = tb
Assuming tableColumn = data
Assuming server = localhost
Ajax:
$.ajax({
url: 'GroupsHandler.php',
success:function(data){
if(data=="saved")
{
alert("success");
}
}
});
Now in the myphpscript.php :
<?php
$Query = "select data from table";
$con = mysql_connect("localhost","user","pwd"); //connect to server
mysql_select_db("db", $con); //select the appropriate database
$data=mysql_query($Query); //process query and retrieve data
mysql_close($con); //close connection
if(!$empty(mysql_fetch_array($data))
{
echo "saved";
}
else
{
echo " not saved ";
}
?>
EDIT:
You must also include jquery file to make this type of ajax request.Include this at the top of your ajax call page.
<script src='ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js' type='text/javascript'></script>
First, decide whether to use POST or GET (I recommend POST) to pass AJAX data. Make a php file (ajax.php) such that it echos true or false after checking whether some data is stored in the database. You may test with a variable $your_variable = "some_data_to_check"; having a data inside and once you are finished, you may replace it with $your_variable = $_POST["ajaxdata"];.
Then in your page, set up AJAX using jQuery plugin like:
var your_data_variable = "data_to_send";
$.ajax({
type: "POST",
url: "ajax.php",
data: 'ajaxdata=' + your_data_variable,
success: function(result){
if(result == "true"){
alert("saved");
}else{
alert("not saved");
}
}
You may have a look at jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery.

Using Ajax to generate an alert box after checking whether some data are stored in database [duplicate]

I want to pop up an alert box after checking whether some data is stored in the database. If stored, it will alert saved, else not saved.
This is my ajax function:
AjaxRequest.POST(
{
'url':'GroupsHandler.php'
,'onSuccess':function(creategroupajax){ alert('Saved!'); }
,'onError':function(creategroupajax){ alert('not saved');}
}
);
but now it show AjaxRequest is undefined.
How can I fix this?
This of course is possible using Ajax.
Consider the below sample code for the same.
Ajax call :
$.ajax({
url: 'ajax/example.php',
success: function(data) {
if(data == "success")
alert('Data saved.');
}
});
example.php's code
<?php
$bool_is_data_saved = false;
#Database processing logic here i.e
#$bool_is_data_saved is set here in the database processing logic
if($bool_is_data_saved) {
echo "success";
}
exit;
?>
function Ajax(data_location){
var xml;
try {
xml = new XMLHttpRequest();
} catch (err){
try {
xml = new ActiveXObject("Msxml2.XMLHTTP");
} catch (error){
try {
xml = new ActiveXObject("Microsoft.XMLHTTP");
} catch (error1){
//
}
}
}
xml.onreadystatechange = function(){
if(xml.readyState == 4 && xml.status == 200){
alert("data available");
}
}
xml.open("GET", data_location, true);
xml.send(null);
}
window.onload = function(){
Ajax("data_file_location");
}
You can create an addtitional table with date(time) of last update database and check if this date is later. You can use standard setInterval function for it.
This is possible using ajax. Use jQuery.ajax/pos/get to call the php script that saves the data or just checks if the data was saved previously (depends on how you need it exactly) and then use the succes/failure callbacks to handle its response and display an alert if you get the correct response.
Below code based on jQuery.
Try it
$.ajax({
type: 'POST',
url: 'http://kyleschaeffer.com/feed/',
data: { postVar1: 'theValue1', postVar2: 'theValue2' },
beforeSend:function(){
// this is where we append a loading image
$('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
},
success:function(data){
// successful request; do something with the data
$('#ajax-panel').empty();
$(data).find('item').each(function(i){
$('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
});
},
error:function(){
// failed request; give feedback to user
$('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
use the ajax to call the script and check values in the database through the script. If
data present echo success else not.lets look an example of it.
Assuming databasename = db
Assuming tablename = tb
Assuming tableColumn = data
Assuming server = localhost
Ajax:
$.ajax({
url: 'GroupsHandler.php',
success:function(data){
if(data=="saved")
{
alert("success");
}
}
});
Now in the myphpscript.php :
<?php
$Query = "select data from table";
$con = mysql_connect("localhost","user","pwd"); //connect to server
mysql_select_db("db", $con); //select the appropriate database
$data=mysql_query($Query); //process query and retrieve data
mysql_close($con); //close connection
if(!$empty(mysql_fetch_array($data))
{
echo "saved";
}
else
{
echo " not saved ";
}
?>
EDIT:
You must also include jquery file to make this type of ajax request.Include this at the top of your ajax call page.
<script src='ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js' type='text/javascript'></script>
First, decide whether to use POST or GET (I recommend POST) to pass AJAX data. Make a php file (ajax.php) such that it echos true or false after checking whether some data is stored in the database. You may test with a variable $your_variable = "some_data_to_check"; having a data inside and once you are finished, you may replace it with $your_variable = $_POST["ajaxdata"];.
Then in your page, set up AJAX using jQuery plugin like:
var your_data_variable = "data_to_send";
$.ajax({
type: "POST",
url: "ajax.php",
data: 'ajaxdata=' + your_data_variable,
success: function(result){
if(result == "true"){
alert("saved");
}else{
alert("not saved");
}
}
You may have a look at jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery.

php validation using jquery and ajax

i have a jquery ajax form.
i have validation at server side for repeated username and email ID.
which works fine without jquery/ajax.
in my php code i have used die() to return if any error occurs. my main problem is at ajax
here is the code
$(document).ready(function () {
$("form#regist").submit(function () {
var str = $("#regist").serialize();
$.ajax({
type: "POST",
url: "submit1.php",
data: $("#regist").serialize(),
success: function () {
$("#loading").append("<h2>you are here</h2>");
}
});
return false;
});
});
The success function works properly. if my data is valid then it is added in the db, if my data is repeated then it is not added in the db. Now what i want to know is how do i return the error from my php file and use it at success event. Thanks in advance..
edit : this is how my php script looks
$query = "SELECT username from userdetails WHERE username = '$username'";
$q = mysql_query($query) or die("error" . mysql_error());
$numrows = mysql_num_rows($q);
if($numrows > 0)
{
die("username already exixt");
//should i put something like this
//$error = "username already exists";
//return $error; --->> i am not sure about this..
}
thanks in advance
Php side:
if($numrows > 0)
{
echo "username already exist";
}
Javascript side:
success: function(msg)
{
if(msg == 'username already exist') alert(msg);
}
But this is so crude, If you plan to develop this further try to read some articles on JSON, so you can use json to communicate to server side. And also you should try to use some default error controlling, like return an array with php:
echo json_encode(array('error' => true, 'notice' => 'username exists'));
Then on the javascript side (jquery), use json ajax request and always check if error variable is true or not, if it is maybe you can use a default function for error controlling.
Hope this helped.
In the function definition which you have done like:
success: function(){
introduce a parameter like: success: function(retVal){
Now in the function you can check for the value of retVal.
Say, you return from your PHP script, "successful" for success case and "this email exists" for failure.
Now you can directly compare this here and do whatever you want to, like:
if(retVal == 'this email exists')
{
window.alert('please re-enter the email, this record exists!');
}
and so on...
Hope this helps.
$(document).ready(function () {
$("form#regist").submit(function () {
var str = $("#regist").serialize();
$.ajax({
type: "POST",
url: "submit1.php",
data: $("#regist").serialize(),
success: function (msg) {
alert(msg);
}
});
return false;
});
});
Here from server side send the message and show it, how i have shown it :)

Categories