Check if username exist, then i want to update - php

I have a code that checks if the username is available if you want to change. But now I saw that if you update something else such as your password, you can assume to save as the user name already exists.
Listed below are the code I use, as you see, I have tried to think of something but did not go well at all.
PHP
$sql = "Select * FROM table WHERE Slug = '$slug' AND ID ='$id' LIMIT 1";
$query = mysql_query($sql);
if(mysql_num_rows($query)>0){
echo 'true';
}else{
$e_sql = "Select * FROM table WHERE Slug = '$slug'";
$e_query = mysql_query($e_sql);
if(mysql_num_rows($e_query)>0){
echo 'false';
}else{
echo 'false';
}
}
Jquery/Javascript
var response;
$.validator.addMethod(
"uniqueUserName",
function(value, element) {
$.ajax({
type: "POST",
url: "User.php",
data: {
'slug': value,
'id': <?php echo $id; ?>
},
dataType:"html",
success: function(msg)
{ console.log(msg);
response = ( msg == 'true' ) ? true : false;
}
});
return response;
},
"This Name is already used!"
);
$("#addSurvey").validate({
rules: {
name: {
required: true,
uniqueUserName: true
},
}
});

Basically problem is in your $.ajax request.
As you know $.ajax by default perform an asynchronous HTTP (Ajax) request.
Easiest solution for you is to make request synchronous.
To make request synchronous you should set option async: false - in this case code will be executed linearly and you will get return response; only when ajax request is completed.
So basically change part of ajax call to:
$.ajax({
type: "POST",
url: "User.php",
async: false,
data: {
'slug': value,
'id': <?php echo $id; ?>
},
dataType:"html",
success: function(msg){
response = msg === 'true';
}
});
May be useful:
jQuery.ajax() Documentation

set
response = (( msg == 'true' ) ? true : false);

Related

Get variable value from PHP in AJAX

I'm trying to catch a PHP variable in AJAX, but I'm not having much luck.
myCode.php
<?php
//myFunction that will return a status
if(myFunction() === true){
$status = "success";
}else{
$status = "failure";
}
?>
In my HTML, I have the following:
<script>
function initiate_delete() {
$.ajax({
url: '{$modulelink}&action=delete',
type: "post", //request type,
dataType: 'json',
data: {
type: 'test'
}
});
}
</script>
Is there any way to have AJAX wait for the PHP to execute and then get $status when I execute initiate_delete?
Thanks in advance.
Change code to
<?php
//myFunction that will return a status
if(myFunction() === true){
$status = "success";
}else{
$status = "failure";
}
echo $status
or short it to
echo myFunction() ? "success" : "failure";
To wait for an answer - you can execute the request asynchronously, and get the result in the .done() callback
$.ajax({
url: $(this).attr('href'),
type: 'POST',
fail: function(){
//do something
},
done: function(m){
/// do something else
}
});
Your PHP needs to return the value. If you want to keep the dataType Json (suggested) you just need to json_encode your output.
So the PHP becomes:
<?php
$type=$_POST['type'];
//myFunction that will return a status
if(myFunction() === true){
$status = "success";
}else{
$status = "failure";
}
echo json_encode('status'=>$status);
?>
Then you need to tell Ajax what to do with the answer received using .done()
So your Ajax will become:
$.ajax({
url: '{$modulelink}&action=delete',
type: "post", //request type,
dataType: 'json',
data: { type: 'test'}
}).done(function(data){
console.log(data.status);
});
Now you can do what you want with status but only in the .done() function. The rest of your js will be executed without waiting for ajax to return a value since it is asyncronous. So add here all the logic like dom manipulation and so on depending on this response.
Obviously you can have more data returned by php in the json and acccess them by key as done for status.

Getting a different code outcome on different servers

This is updated based on an answer, but i still have a problem.
var dataString = $("#acc_form").serialize();
var action = $("#acc_form").attr('action');
$.ajax({
type: "POST",
dataType:"JSON",
url: action,
data: dataString,
success: function(res){
if(res.status === 'error'){
console.log('Error!!!');
} else{
console.log('Success!!!');
}
}
});
Here is where i do the check, and also where i am confused. my else statement looks wrong.
$desired_email = strip_tags(#$_POST['email']);
$email_exist_check = mysqli_query($connect, "SELECT * FROM accounts WHERE email='$desired_email'") or die(mysql_error());
$email_exist = mysqli_num_rows($email_exist_check);
if ($email_exist == 0) {
//performs insert query
} else {
header('Content-type: application/json');
$res['status'] = 'error';
echo json_encode($res);
}
Any help is greatly appreciated. I am new to jQuery and ajax and using json
Because you've returned a json array, even check email is invalid. You need to process the response data in success of ajax function. The error callback only works when server return status code on header (it isn't status in response data), i called it is Solution 1. In Solution 2, i solve it by return a header in PHP code.
Solution 1: Solve it on client (javascript)
//...
success: function(res){
// Use json parse method to parse the response data if it is string.
// If you have been to set dataType: 'json', it's ok. Can ignore this comment & code.
// res = JSON.parse(res);
status = res.status;
if(status == 'error'){
//Process the error in here
}
}
//...
Full ajax function example:
$.ajax({
url: 'index.php',
data: {email: 'vuong#gmail.com'},
method: 'POST',
dataType: 'json',
success: function(res){
if(res.status === 'error'){
console.log('Error!!!');
} else{
console.log('Success!!!');
}
}
});
It's work on my workplace!
Solution 2: Solve it on server (php)
// Add it to before `echo` line
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
You only need to choose once in both. Good luck!
Sorry all because my English is not good.

How to handle json response from php?

I'm sending a ajax request to update database records, it test it using html form, its working fine, but when i tried to send ajax request its working, but the response I received is always null. where as on html form its show correct response. I'm using xampp on Windows OS. Kindly guide me in right direction.
<?php
header('Content-type: application/json');
$prov= $_POST['prov'];
$dsn = 'mysql:dbname=db;host=localhost';
$myPDO = new PDO($dsn, 'admin', '1234');
$selectSql = "SELECT abcd FROM xyz WHERE prov='".mysql_real_escape_string($prov)."'";
$selectResult = $myPDO->query($selectSql);
$row = $selectResult->fetch();
$incr=intval($row['votecount'])+1;
$updateSql = "UPDATE vote SET lmno='".$incr."' WHERE prov='".mysql_real_escape_string($prov)."'";
$updateResult = $myPDO->query($updateSql);
if($updateResult !== False)
{
echo json_encode("Done!");
}
else
{
echo json_encode("Try Again!");
}
?>
function increase(id)
{
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
success: function (response) {
},
complete: function (response) {
var obj = jQuery.parseJSON(response);
alert(obj);
}
});
};
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
dataType: 'json',
success: function (response) {
// you should recieve your responce data here
var obj = jQuery.parseJSON(response);
alert(obj);
},
complete: function (response) {
//complete() is called always when the request is complete, no matter the outcome so you should avoid to recieve data in this function
var obj = jQuery.parseJSON(response.responseText);
alert(obj);
}
});
complete and the success function get different data passed in. success gets only the data, complete the whole XMLHttpRequest
First off, in your ajax request, you'll want to set dataType to json to ensure jQuery understands it is receiving json.
Secondly, complete is not passed the data from the ajax request, only success is.
Here is a full working example I put together, which I know works:
test.php (call this page in your web browser)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
// Define the javascript function
function increase(id) {
var post_data = {
'prov': id
}
$.ajax({
'type': 'POST',
'url': 'ajax.php',
'data': post_data,
'dataType': 'json',
'success': function (response, status, jQueryXmlHttpRequest) {
alert('success called for ID ' + id + ', here is the response:');
alert(response);
},
'complete': function(jQueryXmlHttpRequest, status) {
alert('complete called');
}
});
}
// Call the function
increase(1); // Simulate an id which exists
increase(2); // Simulate an id which doesn't exist
</script>
ajax.php
<?php
$id = $_REQUEST['prov'];
if($id == '1') {
$response = 'Done!';
} else {
$response = 'Try again!';
}
print json_encode($response);

how can i create a success back function?

$(function() {
$(".follow").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "listen.php",
data: info,
success: function(){}
});
$("#follow"+I).hide(); ///showing the remove button after the data has been entered
$("#remove"+I).show();
return false;
});
});
The PHP file listen.php
<?php session_start();
include_once ('includes/connect.php');
$id = $_POST['id'];
$follower = $_SESSION['user_id'];
$registerlistener = mysql_query("INSERT INTO relationships (leader, listener) VALUES('".$id."', '".$follower."')");
?>
what I want to do is when I click the follow button, I want to check if the data has been entered into the database, before showing the remove button, basically checking on the background.
mysql_query will return TRUE or FALSE. You can echo that from the PHP script, and have the ajax call read it.
listen.php:
<?php session_start();
include_once ('includes/connect.php');
$id = $_POST['id'];
$follower = $_SESSION['user_id'];
$registerlistener = mysql_query("INSERT INTO relationships (leader, listener) VALUES('".$id."', '".$follower."')");
echo json_encode(array('response'=>$registerlistener));
?>
In your JavaScript:
$.ajax({
type: "POST",
url: "listen.php",
data: info,
dataType: 'json',
success: function(data){
if(data.response){
// mysql_query returned TRUE
$("#follow"+I).hide();
$("#remove"+I).show();
}
else{
// FALSE
}
}
});
If you want, you can use the $.post shorthand:
$.post('listen.php', info, function(data){
if(data.response){
// mysql_query returned TRUE
$("#follow"+I).hide();
$("#remove"+I).show();
}
else{
// FALSE
}
}, 'json');
Put the code you want to execute inside your 'success' callback function.
$.ajax({
type: "POST",
url: "listen.php",
data: info,
success: function(){
$("#follow"+I).hide();
$("#remove"+I).show();
}
});
do it like this:
listen.php
<?php session_start();
include_once ('includes/connect.php');
$id = $_POST['id'];
$follower = $_SESSION['user_id'];
if($registerlistener = mysql_query("INSERT INTO relationships (leader, listener) VALUES('".$id."', '".$follower."')")):
echo "true";
else:
echo "false";
endif;
?>
pass parameter in success function, example "msg". whatever was echo'ed in listen.php will be in the msg variable now
success: function(msg){}
if(msg == "true")
{
//do something
}
else
{
//show error message
}
});

jQuery function to check if an email address exists

I have a very limited jQuery experience and I was wondering if you can help me with a function that has to check, with an AJAX request, if an email address exists or not.
Until now I have this piece of code for email checking:
$('input#email').bind('blur', function () {
$.ajax({
url: 'ajax/email.php',
type: 'GET',
data: 'email=' + $('input#email').val(),
cache: false,
success: function (html) {
if (html == 1) alert('Email exists!');
}
});
});
How can I make a function out of this and use it like this:
if (!email_exists($('input#email').val())) {
$('#error_email').text('Email exists').show();
return false;
}
My PHP code looks like this:
$email = ($_GET['email']) ? $_GET['email'] : $_POST['email'];
$query = "SELECT `id` FROM `users` \n"."WHERE `users`.`email` = '".mysql_real_escape_string($email)."'";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
echo '1';
} else {
echo '0';
}
Thank you.
If you really must have an answer returned from the function synchronously, you can use a synchronous XMLHttpRequest instead of the normal asynchronous one (the ‘A’ in AJAX):
function email_exists(email) {
var result= null;
$.ajax({
url: 'ajax/email.php',
data: {email: email},
cache: false,
async: false, // boo!
success: function(data) {
result= data;
}
});
return result=='1';
}
However this is strongly discouraged as it will make the browser hang up whilst it is waiting for the answer, which is quite user-unfriendly.
(nb: also, pass an object to data to let jQuery cope with the formatting for you. Otherwise, you would need to do 'email='+encodeURIComponent(email) explicitly.)
You can't have a function that synchronously returns a value from an asynchronous action, or vice versa (you would need threads or co-routines to do that, and JavaScript has neither). Instead, embrace asynchronous programming and have the result returned to a passed-in callback:
$('#email').bind('change', function() {
check_email($('#email').val(), function(exists) {
if (exists)
$('#error_email').text('Email exists').show();
});
});
function check_email(email, callback) {
$.ajax({
url: 'ajax/email.php',
data: {email: email},
cache: false,
success: function(data) {
callback(data=='1');
}
});
}
You've already made it a "function" by attaching it to the blur event of your input. I would just
success: function(html) {
if (html == 1)
$('#error_email').text('Email exists').show();
else
$('#error_email').hide();
}

Categories