5 Replies - 5540 Views - Last Post: 09 January 2011 - 08:15 AM Rate Topic: -----

#1 eZACKe  Icon User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,278
  • Joined: 01-June 09

Checking if a user exists Ajax call

Posted 07 January 2011 - 08:39 PM

I'm trying to make an Ajax call whenever a user takes focus off of a username text field. The problem is it doesn't seem the Ajax call is every occurring. As far as I can tell, the function in which the Ajax call resides isn't even being called.

I have two programs that play a role here:
  • znsignup.php -> Includes Javascript and PHP + a Form
  • zncheckuser.php -> The url the Ajax sends it's request too


I realize that how I have my Javascript, PHP, and some HTML all in one program is not optimal, but this is a very early design. It will be changed eventually.

Here's my code:
znsignup.php
<?php // Page that allows users to join the network
include_once 'znheader.php';// used to include the basic header that is on every page, and to use any functions we may need from znfunctions.php

// Javascript block for Ajax -> Displaying a message if a username is not available
echo <<<_END
<script>
function checkUser(user)
{
	if(user.value == '')// if the value property of the username field equals ''....
	{
		document.getElementById('info').innerHTML = '';// pass '' to the span
		return;
	}
	
	params = "user=" + user.value;// what we will send to the server
	request = new ajaxRequest();// create a new ajaxRequest object
	
	// Ajax call will go to zncheckuser.php which reports whether the username is available
	request.open("POST", "zncheckuser.php", true);// use the POST method, with the target url being zncheckuser.php, and request is handled asycnhronously
	request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");// next 3 lines set up headers to let server know a POST request is coming
	request.setRequestHeader("Content-length", params.length);
	request.setRequestHeader("Connection", "close");
	
	request.onreadystatechange = function()
	{
		if(this.readyState == 4)
		{
			if(this.status == 200)
			{	
				if(this.responseText != null)
				{	
					document.getElementById('info').innerHTML = this.responseText;// the response to the Ajax call is  returned to the span
				}
				else alert("Ajax error: No data received");
			}
			else alert("Ajax error: " + this.statusText);
		}
	}
	
	request.send(params);
}
	
function ajaxRequest()
{
	try// Non IE Browser?
	{
		var request = new XMLHttpRequest();
	}
	catch(e1)
	{
		try// IE 6+?
		{
			request = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(e2)
		{
			try//IE 5?
			{
				request = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(e3)// there is no Ajax support
			{
				request = false;
			}
		}
	}
	return request;
}

</script>
<h3>Sign Up Form<h3>
_END;

$error = $user = $pass = "";

if(isset($_SESSION['user'])) destorySession();// if the session variable $_SESSION['user'] has been set, destroy it

if(isset($_POST['user']))// if the form has been submitted $POST['user'] will have a value
{
	$user = sanitizeString($_POST['user']);// so if it's been submitted, set $user to the sanitized version of whatever was in the user field
	$pass = sanitizeString($_POST['pass']);// if it's been submitted, set $pass to the sanitized version of whatever was in the user field
	
	// username and password validation
	if($user == "" || $pass == "")// if either of the fields were left blank..
	{
		$error = "Not all fields were entered<br /><br />";// set $error to an error message
	}
	else// if neither of the fields were left blank...
	{
		$query = "SELECT * FROM znmembers WHERE user='$user'";// a query to find a user with the name that was submitted in the form that wasn't blank
		
		if(mysql_num_rows(queryMysql($query)))// call queryMysql to get the results of the above query. If there aren't zero rows the name has been taken
		{
			$error = "That username already exists<br /><br />";// set $error to an $error message
		}
		else// if the username entered wasn't already taken..
		{
			$query = "INSERT INTO znmembers VALUES('$user', '$pass')";// a query to inset the submitted username and password into the znmembers table
			queryMysql($query);// perform the query
			die("<h4>Accout created</h4>You may now Log in.");
		}
	}
}

// create the sign up form
// onblur is called if focus is removed from the field. When submitted $_POST['user'] and $_POST['pass'] will be set and sent to znsignup.php (itself)
// onblur must put the data into $_POST['user'] as well
echo <<<_END
<form method='post' action='znsignup.php'>$error
Username <input type='text' maxlength='16' name='user' value='$user'
	onblur='checkUser(this)'/><span id='info'></span><br />
Password <input type='text' maxlength='16' name='pass' value='$pass' /><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
<input type='submit' value='Signup' />
</form>
_END;
?>



zncheckuser.php
<?php // The Ajax call of znsignup goes here and this looks up if a user is already in the database
include_once 'znfunctions.php';// this isn't a new page so don't need rnheader.php. Just need some functions from znfunctions.php

if(isset($_POST['user']))// if the $_POST variable 'user' has a value...
{
	$user = sanitizeString($_POST['user']);// set $user to the sanitized version of this value
	
	$query = "SELECT * FROM znmember WHERE user='$user'";// a query to select the row where user equals the 'user' value from above
	
	if(mysql_num_rows(queryMysql($query)))// call queryMysql to get the results of the above query. If there aren't zero rows the name has been taken
	{
		echo "<font color=red> ←
					Sorry, already taken</font>";// &larr is a left pointing arrow
	}
	else echo "<font color=reen> ←
					Username available</font>";
}
?>



Everything else in the program is working great.

Note:
I added this:
<script>
function checkUser(user)
{
document.write("HEELLLOO!");
.
.
.


For debugging purposes. It makes sense to me that when onblur is called, this document.write should be displayed immediately. That is the case. When I have this line in there it reloads znsignup.php and it is just a while screen that says HEELLLOO!. If I take this line out though, and I move from the username text field, nothing happens. Ajax is not working.

Thanks for the help!


EDIT: From what I can get out of it from spending a lot of time trying to debug, this isn't working:

request = new ajaxRequest();



Why do I think that? Because I added debugging document.write() calls inside ajaxRequest(), and they don't get printed. I did this:
function ajaxRequest()
{
document.write("helllllo!");
	try// Non IE Browser?
	{
		var request = new XMLHttpRequest();
	}
	catch(e1)
	{
		try// IE 6+?
		{
			request = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(e2)
		{
			try//IE 5?
			{
				request = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(e3)// there is no Ajax support
			{
				document.write("none");
				request = false;
			}
		}
	}
	document.write("success");
	return request;
}



At least one of those document.write()'s should print to the screen correct? Well they're not when I move focus from the username box. Why? Well that's for someone to hopefully help me with :bigsmile:

This post has been edited by eZACKe: 08 January 2011 - 10:30 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Checking if a user exists Ajax call

#2 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3576
  • View blog
  • Posts: 10,441
  • Joined: 08-June 10

Re: Checking if a user exists Ajax call

Posted 08 January 2011 - 05:05 AM

document.write() kills your page when used after the page has loaded. (document.write() then implicictly calls document.open(), which means: "make a new page")

something else I stumbled upon: line #15: there’s a = missing (key value separator), currently you submit "userNameOfUser".
Was This Post Helpful? 0
  • +
  • -

#3 eZACKe  Icon User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,278
  • Joined: 01-June 09

Re: Checking if a user exists Ajax call

Posted 08 January 2011 - 10:30 AM

So you're saying having the document.write()'s in there for debugging is a bad idea?

Well I took them all out anyway.

Also, thanks I also noticed the missing '=' last night, but forgot to edit that in my post.

So with that fixed and all the document.write()'s taken out, ran the program again. Still no Ajax call happening when changing focus.
Was This Post Helpful? 0
  • +
  • -

#4 eZACKe  Icon User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,278
  • Joined: 01-June 09

Re: Checking if a user exists Ajax call

Posted 08 January 2011 - 02:58 PM

No suggestions? :helpsmilie:
Was This Post Helpful? 0
  • +
  • -

#5 no2pencil  Icon User is offline

  • Admiral Fancy Pants
  • member icon

Reputation: 5388
  • View blog
  • Posts: 27,384
  • Joined: 10-May 07

Re: Checking if a user exists Ajax call

Posted 08 January 2011 - 08:15 PM

Please don't bump your topic...

When using ajax, rather than using this :

request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");



I use this :

request.onreadystatechange  = handleServerResponse;
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.send("user=" + user.value);

function handleServerResponse() {
   if (xmlhttp.readyState == 4) {
     if(xmlhttp.status == 200) {
       document.getElementById("message").innerHTML=xmlhttp.responseText; //Update the HTML Form element
     }
     else {
        alert("Error during AJAX call. Please try again");
     }
   }
}



& then where ever I place the div id message, the text updates :

<div id="message" name="message"></div>

Was This Post Helpful? 0
  • +
  • -

#6 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3576
  • View blog
  • Posts: 10,441
  • Joined: 08-June 10

Re: Checking if a user exists Ajax call

Posted 09 January 2011 - 08:15 AM

View PosteZACKe, on 08 January 2011 - 05:30 PM, said:

So you're saying having the document.write()'s in there for debugging is a bad idea?

yes.

for debugging you should rather use console.log() or FireBug (works in FF, and for Safari, Chrome and Opera, there should be at least something similar)
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1