Hi I am adding dynamic validation to a form on my webpage to stop unnecessary page reloads. The form is for registring an account, and I want to be able to check if the username that the user selects is already taken, however as far as I know I can only retrieve data from mysql in php. How should I go about this?
2 Answers
Use PHP to load a list of existing users into an array when the registration page loads and then use that array to do the Javascript validation.
5 Comments
w4etwetewtwet
Oh yeah, I suppose that would work. However as the names are the users email there would be an issue with people being able to view users email addresses in the source code.
zajd
You would not be able to view the list of email addresses. PHP doesn't send anything to the end-user other than what you specify. In other words, unless you're directly outputting that array to JS/HTML/CSS it won't display on the page for the user.
w4etwetewtwet
But if the array is being used by js surely I would be outputting js.
zajd
Well, you would, but it's going to look like
var doesExist = "<?php userNameExists(<call to pull text from username field>); ?>"; You might want to read up on AJAX and how it works, as it's going to be handy for this sort of thing.w4etwetewtwet
just went and had a quick look at some ajax docs, as I've never used it before, that is exactly what I needed, thanks!
you can using ajax. this is function in php:
function check_registration() {
if ($_POST['val']) {
$query = "select user from member where user = '" . $_POST['val'] . "'";
$row = $this->countRow($query);
if ($row > 0) {
echo "user has been taken";
}
}
}
and this is ajax that u can put in html
<script>
$(document).ready(function(){
$('#input1').keyup(function(){
var values = $('#input1').val();
var dataString = 'val='+ values;
$.ajax
({
type: "POST",
url: "http://localhost/authentication/check",
data: dataString,
cache: false,
success: function(html)
{
$("#error1").html(html);
}
});
});
});
</script>