I couldnt figure out whats wrong with my code but if I am calling ajax with the following code:
ajax.js:
function ajaxObj(meth, url){
var x = new XMLHttpRequest();
x.open(meth, url, true);
x.setRequestHeader("Content-type", "application/x-www_form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
signup.php
function checkusername(){
var u = _("username").value;
if( u != ""){
_("usernamestatus").innerHTML = "checking...";
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function(){
if(ajaxReturn(ajax) == true){
_("usernamestatus").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+u);
}
}
The PHP code I am calling is the following in signup.php:
<?php
//ajax calls usernamecheck
if(isset($_POST["usernamecheck"])){
include_once("php_includes/db_conx.php");
$username = preg_replace('#[^a-z0-9]#i', '', $_POST['usernamecheck']);
$sql = "SELECT id FROM users WHERE username = '$username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$uname_check = mysqli_num_rows($query);
if(strlen($username) < 3 || strlen($username) > 16) {
echo '<strong style = "color:#F00;">3 - 16 characters please</strong>';
exit();
}
if(is_numeric($username[0])){
echo '<strong style = "color:#F00;">Username must begin with a letter!</strong>';
exit();
}
if($uname_check < 1){
echo '<strong style = "color:#09900;">' . $username . ' is OK</strong>';
exit();
} else {
echo '<strong style = "color:#F00;">' . $username . ' is taken</strong>';
exit();
}
}
?>
As you can see, it is just a check for the username in SignUp form.
The function _(x) is getting the Element by ID.
I get the full HTML code as response and not the echo.
If I use the following:
<?php
//ajax calls usernamecheck
if(isset($_POST["usernamecheck"])){
echo 'test';
}
then it returns test + full html.
What I am doing wrong?
x-www_form-urlencodedis not a proper content type, it should bex-www-form-urlencoded