Jquery and ajax, my function for username checking? - php

I have written this ajax request for username checking...
function check_username() {
var username = $("#username").val();
$('.loading').fadeIn().delay(100);
$.post("ajax.php", {
username: $('#username').val(),
}, function (response) {
$('.error, .success').hide();
setTimeout(function () {
$('.loading').hide();
finishAjax('username', response);
}, 1000);
});
return false;
}
function finishAjax(id, response) {
$('#' + id).after(response).fadeIn(1000);
}
It all works fine just a couple of questions,
Can this code be improved in any way, this is the first ever one I have wrote so I wouldn't know.
Is there a way to make this a function for all my ajax requests rather than just username checking, so it can be used for email checking and such too. I am not sure on how to make a function like that would I have to pass variables on my onblur event which is attached to my form, at the minute it looks like this.
Is there a way to stop the ajax from running if the same error is there as previous, ie, string length should be over 3, so someone inputs AJ, and the error message 'must be over 3 characters' comes up, it the user then triggers the onblur event again, with the value of AJ, or CG, then the same error comes up, triggering a script that is useless and using memory.
Is there a way to make the ajax request with every character the user enters?
My ajax php is as follows...
<?php
require('dbc.php');
if (isset($_REQUEST['username'])) {
$q = $dbc -> prepare("SELECT username FROM accounts WHERE username = ?");
$q -> execute(array($_REQUEST['username']));
if (strlen($_REQUEST['username']) < 3) {
echo '<div class="error">Has to be at least 3 characters</div>';
}
elseif ($q -> rowCount() > 0) {
echo '<div class="error">Username already taken</div>';
}
else {
echo '<div class="success">Username available</div>';
}
}
?>

To answer 1 & 2. I would turn it into a plugin and do something along these lines.
$.fn.checkValid = function(options)
{
var response = function(response) {
var setClass = '';
var $span = $(this).data('checkValidTip');
if ($span)
{
$span.remove();
}
if (response === undefined) return;
setClass = (response.valid ? 'valid' : 'invalid');
var $span = $('<span>' + response.msg + '</span>');
$(this)
.data('checkValidTip', $span)
.after($span);
$span.hide()
.fadeIn(1000)[0]
.className = setClass;
};
var ajaxOptions = {
type: 'GET',
url: 'ajax.php',
success: response,
dataType: 'json'
};
this.each(function() {
var that = this;
var ajaxRequest = ajaxOptions;
ajaxRequest.data = {};
ajaxRequest.data[options.key] = this.value;
ajaxRequest.context = that
$.ajax(ajaxRequest);
});
};
Usage
$('#username, #email').blur(function() {
$(this).checkValid({ key: this.id });
});
PHP changes
You should make your PHP function return a JSON, instead of HTML i.e.
<?php
// Do your sql statements here, decide if input is valid or not
$arr = array('valid' => $is_valid,
'msg' => $error_or_good_msg
);
echo json_encode($arr);
/* For example will output:
{
"valid": "false",
"msg": "<b>Error: Must be at least 2 characters</b>"
}
Which can be read directly as response.valid
or response.msg from within response() function
*/
To answer question 3: short answer is no. For this to work, you should have basic validation in JS. The best option would be to use a plugin that uses objects for validation parameters, that way you can output your validation requirements dynamically from your database, from within PHP using json_encode i.e. your output format would be:
var validations = {
username: {
min_chars: 4,
max_chars: 10,
valid_chars: 'qwertyuiopasdfghjklzxcvbnm_-'
},
email: {
regex: /./ //your magic regex here
}
};
jsFiddle
http://jsfiddle.net/sqZfp/2/
To answer 4, just change the event as above from .blur to .keyup should do the trick.

Related

PHP value not being caught by AJAX

I have some code that sends a variable (pin) to php via AJAX the database is then queried and if a result is found the php echo's a value of 1. Everything is working fine, except that the Ajax does not recognise the value returned by the php.
Here is my code
$(document).ready(function () {
$("form.submit").submit(function () {
var pin = $(this).find("[name='pin']").val();
// ...
$.ajax({
type: "POST",
url: "http://www.example.com/pin.php",
data: {
pin : pin,
},
success: function (response) {
if (response == "1") {
$("#responsecontainer").html(response);
window.location.href = "home.html?user=" + user;
// Functions
} else { // Login failed
alert("LOGIN FAILED");
}
}
});
this.reset();
return false;
});
});
And here is my PHP code, I know that the code below returns a value of 1. When Ajax is triggered it returns a value that generates a login fail message. Is there a way to see what Ajax is sending, if i swap out the ajax and directly submit the for to the server it also returns a 1 on the php echo.
$pin = $_GET["pin"];
$db = new PDO("mysql:host=localhost;dbname=xxxxx;charset=utf8", "xxxx", "xxxx");
$count = $db->query("SELECT count(1) FROM users WHERE pin='$pin'")->fetchColumn();
echo $count;
It's recommended to return JSON data as result for an ajax request.
So try this :
Edit: I've updated the php code to make the sql query with PDO prepare() method taking into account #Dominik's commentary
$pin = $_POST['pin'];
$db = new PDO('mysql:host=localhost;dbname=xxxxx;charset=utf8', 'xxxx', 'xxxx');
$stmt = $pdo->prepare('SELECT count(1) FROM users WHERE pin = :pin');
$stmt->execute(array('pin' => $pin));
return json_encode([
"count" => $stmt->fetchColumn()
]);
And in your ajax success callback :
...
success: function(response) {
var count = JSON.parse(response).count;
if (count == "1") {
$("#responsecontainer").html(response);
window.location.href = "home.html?user="+ user;
} else {// Login failed
alert("LOGIN FAILED");
}
},
error: function(error) {
...
}
Hope it's helps you :)

select2 on success retrieve newly created tag id

In select2 I have tags loaded by AJAX, if the tag is not found in the db then the user has the option to create a new one. The issue is that the new tag is listed in the select2 box as a term and not as the id (what select to wants - especially becomes a problem when loading the tags again if the user wants to update since only the term and not the id is stored in the db). How can I, on success of adding the term, make it so that select2 recieves the ID and submits the ID instead of the tag name/term?
$(document).ready(function() {
var lastResults = [];
$("#project_tags").select2({
multiple: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "framework/helpers/tags.php",
dataType: "json",
data: function(term) {
return {
term: term
};
},
results: function(data) {
return {
results: data
};
}
},
createSearchChoice: function(term) {
var text = term + (lastResults.some(function(r) {
return r.text == term
}) ? "" : " (new)");
return {
id: term,
text: text
};
},
});
$('#project_tags').on("change", function(e) {
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag " + e.added.id + "?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
$.ajax({
url: 'framework/helpers/tags.php',
data: {
action: 'add',
term: e.added.id
},
success: function(data) {
},
error: function() {
alert("error");
}
});
} else {
console.log("Removing the tag");
var selectedTags = $("#project_tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index, 1);
if (selectedTags.length == 0) {
$("#project_tags").select2("val", "");
} else {
$("#project_tags").select2("val", selectedTags);
}
}
}
}
});
});
Heres part of the switch that does the adding
case 'add':
if (isset($_GET['term'])) {
$new_tag = escape($_GET['term']);
if (Nemesis::insert('tags', 'tag_id, tag_content', "NULL, '{$new_tag}'")) {
// we need to send back the ID for the newly created tag
$search = Nemesis::select('tag_id', 'tags', "tag_content = '{$new_tag}'");
list($tag_id) = $search->fetch_row();
echo $tag_id;
} else {
echo 'Failure';
}
exit();
}
break;
UPDATE: I've done a bit of digging, and what confuses me is that the select2 input does not seem to store the associated ID for the tag/term (see below). I know I could change the attribute with the success callback, but I don't know what to change!
As you have said, you can replace that value, and that is what my solution does. If you search the Element Inspector of Chrome, you will see, bellow the Select2 field, an input with the id project_tags and the height of 1.
The weird thing is that the element inspector of Chrome does not show you the values of the input, as you can see below:
However, you do a console.log($("#project_tags").val()) the input has values (as you see in the image).
So, you can simply replace the text of the new option by the id, inside the success function of the ajax call placed within the $('#project_tags').on("change") function. The ajax call will be something like:
$.ajax({
url: 'framework/helpers/tags.php',
data: {
action: 'add',
term: e.added.id
},
success: function(tag_id) {
var new_val = $("#project_tags")
.val()
.replace(e.added.id, tag_id);
$("#project_tags").val(new_val);
},
error: function() {
alert("error");
}
});
Please be aware that this solution is not bullet proof. For example, if you have a tag with the value 1 selected, and the user inserts the text 1, this will cause problems.
Maybe a better option would be replace everything at the right of the last comma. However, even this might have cause some problems, if you allow the user to create a tag with a comma.
Let me know if you need any more information.

Call PHP file in JavaScript Function for Updating MYSQL Table?

I want to integrate a Java script Slot Machine game into my script.
You can see demo here ; http://odhyan.com/slot/
And also git hub is here ; https://github.com/odhyan/slot you can see all JS files here.
I created a Point Coloumn in User Table that people can play the game with this Point.
I think this JS Function in slot.js checking if user won the game or lose.
function printResult() {
var res;
if(win[a.pos] === win[b.pos] && win[a.pos] === win[c.pos]) {
res = "You Win!";
} else {
res = "You Lose";
}
$('#result').html(res);
}
So i want to add +100 Point if user won the bet.
I made this PHP codes Uptading points For userid "1".
<?php
mysql_connect ("localhost","username","password") or die (mysql_error());
mysql_select_db('slot_machine');
$pointsql = mysql_query("SELECT * FROM user WHERE userid = 1");
while ($row = mysql_fetch_array($pointsql))
{
$row['point'] +=100;
$addpoint = mysql_query("UPDATE user SET point = '{$row['point']}' WHERE userid = 1");
}
?>
So how can i call or excute this PHP Codes in JavaScript function if user Win?
You'll need to trigger a network request from your javascript code to execute your php script server side. Using jQuery's $.ajax() function is an extremely common way to do this abstracting away various browser differences.
function printResult() {
var res;
if(win[a.pos] === win[b.pos] && win[a.pos] === win[c.pos]) {
res = "You Win!";
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.ajax( "path/to/your.php" )
.done(function() { alert("success"); })
.fail(function() { alert("error"); })
.always(function() { alert("complete"); });
} else {
res = "You Lose";
}
$('#result').html(res);
}
You can use jQuery's $.post() function to trigger an asynchronous request to your PHP file.
function printResult() {
var res;
if(win[a.pos] === win[b.pos] && win[a.pos] === win[c.pos]) {
res = "You Win!";
// Here's the line you need.
$.post('score.php', {userid: 1}, function(data) {
alert("Score saved.");
});
} else {
res = "You Lose";
}
$('#result').html(res);
}
This will send POST data to score.php, or whichever file you want to send the data to. The PHP file can then access the userid sent to it by checking the value of $_POST['userid'].
As mentioned in the documentation, $.post() is a shortcut for jQuery's $.ajax() function that is simplified and has some of its options pre-set. The third argument in $.post() is a callback function, and the variable data will contain whatever is echoed out or printed from score.php by the time it's done executing. So, you could use alert(data) instead, to see what score.php printed out. This is useful for troubleshooting and error handling.
try this
$(document).ready(function(){
setInterval(function() {
$.get("databaseUpdated.php");//or what ever your php file name is with corrct path
return false;
}, 1000);
});
hope this will help you use it in your function
function printResult() {
var res;
if(win[a.pos] === win[b.pos] && win[a.pos] === win[c.pos]) {
// if
setInterval(function() {
$.get("databaseUpdated.php");//or what ever your php file name is with corrct path
return false;
}, 1000);
} else {
res = "You Lose";
}
$('#result').html(res);
}

livevalidation.js custom username check function

I am sure this is probably something simple that i am not doing. Running livevalidation.js jquery plugin (livevalidation.com). It provides for custom function callbacks. I am trying to check for username availability. The server side is working fine and I am getting the proper responses back in my data var...
Here is my JS:
Validate.Username = function(value, paramsObj) {
var paramsObj = paramsObj || {};
var message = paramsObj.failureMessage || "Username is not available";
var isSuccess = true;
$.post("<?php echo fURL::getDomain(); ?>/ajax/username",
function(data) {
if (data.status === 'notavailable')
{
Validation.fail('oops, not available.');
}
});
};
I am calling it using:
var username = new LiveValidation('username', { validMessage: curr_username + "is available!" });
username.add( Validate.Presence, { failureMessage: "Choose a username" });
username.add( Validate.Username, { failureMessage: "Username is not available." } );
The problem I am getting is:
Uncaught ReferenceError: Validation is not defined
If I put the Validation.fail() outside of my .post() function it works fine. So am pretty sure it is because it's not able to be referenced inside the .post() function.
I've tried using a callback function
if (data.status === 'notavailable')
{
status_not_available();
}
I get the same error.
I realize this is something probably extremely simple, but any help would be appreciated. Thank you in advance.
i am having the same issue.
Ive found the following, http://forum.jquery.com/topic/ajax-return-value-on-success-or-error-with-livevalidation but have not been able to get it working.
BUT YES! At this very moment i made som (crappy) javascript addon that made it behave, i think :)
This is what i use.
function check_avail(name, id, postUrl)
{
var dataVal = name+'='+$(id).val();
var isaccepted = ''
$(id).next('div').remove();
$(id).after("Undersøger om "+name+" er ledigt");
$.ajax({
url: postUrl,
cache: false,
type: 'post',
dataType: 'json',
data: dataVal,
async: false,
success: function(data) {
if( data.success == 'true' )
{
$('#'+name+'-availability').remove();
//return false;
isaccepted = false;
}
if( data.success == 'false' )
{
$('#'+name+'-availability').remove();
// name.destroy();
isaccepted = true;
}
}
});
if (isaccepted == false) {
return false;
} else{
return true
};
}
And
f1.add( Validate.Custom, { against: function() {
return check_avail( 'brugernavn', '#ft001', 'usernamecheck.asp' );
}, failureMessage: 'Brugernavnet er optaget' } );
Hope it helps you :)
The json query you can read about on the link in the begining :)
(I am not at all skilled at javascript, and the "isaccepted" solution could problalby be made a lot better)
try to change it from Validation.fail to Validate.fail
try wrapping it in another function and try putting your validateStatus(status) function both inside and outside your Validate.Username function. example below is inside
Validate.Username = function(value, paramsObj) {
var paramsObj = paramsObj || {};
var message = paramsObj.failureMessage || "Username is not available";
var isSuccess = true;
$.post("<?php echo fURL::getDomain(); ?>/ajax/username",
function(data) {
validateStatus(data.status);
});
function validateStatus(status){
if (status === 'notavailable'){
Validate.fail("not available");
}
}
};

jQuery Validation Plugin

I really was trying to avoid asking this question. I have seen quite a few posts on SO regarding this plugin but they still didn't quite get it for me. Right now I have a new account registration form and I'm trying to write a custom method for validating a unique username. I would like to think that the following should work:
$.validator.addMethod(
"uniqueUsername",
function(value, element) {
$.post(
"http://" + location.host + "/scripts/ajax/check_username.php",
{
username: value
},
function(response) {
if(response == 'true') {
return true;
} else {
return false;
}
}
);
},
"This username is already taken."
);
Unfortunately it seems like the plugin moves on regardless of the callback function. I found someone suggest doing something like the following:
var result = false;
$.validator.addMethod(
"uniqueUsername",
function(value, element) {
$.post(
"http://" + location.host + "/scripts/ajax/check_username.php",
{
username: value
},
function(response) {
if(response == 'true') {
result = true;
} else {
result = false;
}
}
);
return result;
},
"This username is already taken."
);
But it seems to have a delay since it stores the value, then on the next event will set whatever the value is. What do you guys recommend?
Since this is an asynchronous check, there needs to be more around it (you can't return a value from a function like this, it'll always be false in your case). The built-in method is remote, used like this:
$("form").validate({
rules: {
username: {
remote: {
url: "http://" + location.host + "/scripts/ajax/check_username.php",
type: "post"
}
}
}
});
This will POST a username: valueofElement since the rule is for the element named username. Your server-side script should return true if the validation should pass, false otherwise...so false if the user name is already taken.
You can read more about the remote option here, including how to pass additional data arguments if needed.
js code
username: {
required: true,
minlength: 5,
remote: '/userExists'
},
Php code to check if exist and return messages
public function userExists()
{
$user = User::all()->lists('username');
if (in_array(Input::get('username'), $user)) {
return Response::json(Input::get('username').' is already taken');
} else {
return Response::json(Input::get('username').' Username is available');
}
}

Categories