Results 1 to 9 of 9

Thread: PHP with AJAX Problem

  1. #1

    Thread Starter
    Fanatic Member bharanidharanit's Avatar
    Join Date
    Oct 2008
    Location
    India
    Posts
    673

    PHP with AJAX Problem

    Hi,
    In my application i am checking for the existing username with AJAX, I used this coding, when the user submits the form it starts checking. It will display message if the username already exists, Now if the username already exists means the form must not return, it must show the message again when the user again submits the form. Any ideas??
    Javascript
    Code:
    function exists_username(field)
    {
    	field = field.value;
    	var url = "functions/main.php?ud="+ field;
    	if(XMLHttpRequestObject) 
        {
    	  var obj = document.getElementById("v1"); 
          XMLHttpRequestObject.open("GET", url); 
          XMLHttpRequestObject.onreadystatechange = function() 
          { 
            if (XMLHttpRequestObject.readyState == 4 && 
              XMLHttpRequestObject.status == 200) 
              { 
    			obj.innerHTML = XMLHttpRequestObject.responseText;
              } 
          } 
          XMLHttpRequestObject.send(null); 
        }
    }
    PHP Function
    Code:
    function checkusername($ud)
    {
    	require_once('dbconnect.php');
    	$query = "SELECT username
    			  FROM users
    			  WHERE username='$ud';";
    	$result = mysqli_query($dbconn,$query);
    	$userdata = mysqli_fetch_array($result,MYSQL_ASSOC);
    	if($ud = $userdata['username'])
    	{echo "Username Already Exists";}	
    }

  2. #2
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: PHP with AJAX Problem

    first of all, your PHP function is written incorrectly. in your if statement, you're assigning $ud to $userdata['username']; you should be checking if $ud is equal to $userdata['username'] instead. better still, you don't need to fetch anything from the query you have -- if a result is returned (mysql_num_rows(), or mysqli_num_rows()) at all, the name is taken. you need only check if the return of that function is above 0.

    anyway, code (especially functions) without context doesn't help anyone. you're not stating the problem (what doesn't work?), and you're not giving us the way that you're calling your javascript function.

  3. #3
    Frenzied Member
    Join Date
    Apr 2009
    Location
    CA, USA
    Posts
    1,516

    Re: PHP with AJAX Problem

    Not sure if there's any benefit to using mysqli_ functions if you're not taking advantage of what they do differently as opposed to mysql_ functions.

    But you go straight from querying to using data from the result, without checking to see if you even got a result to begin with. You don't even need to do the data comparison - MySQL already did that for you; the fact that you got a result (or didn't) is proof enough.
    Code:
    $result = mysqli_query($dbconn,$query);
    if(!mysqli_num_rows($result)){
      echo "Username Already Exists";
    }
    As for your Javascript, if you're calling exists_username() on the form submit event, then you have to return false to the form if you get "Username Already Exists" from your PHP page:
    Code:
    if (XMLHttpRequestObject.readyState == 4 && 
    XMLHttpRequestObject.status == 200) 
    {
      if(XMLHttpRequestObject.responseText == "Username Already Exists"){
        obj.innerHTML = XMLHttpRequestObject.responseText;
        return false;
      }
    }
    That would work if you have the form set up something like:
    Code:
    <form onsubmit="return exists_username(whateverField);">
    Edit: I try to refresh a thread before submitting a reply, in case someone else got in while I was typing, but somehow kows keeps evading me...

  4. #4

    Thread Starter
    Fanatic Member bharanidharanit's Avatar
    Join Date
    Oct 2008
    Location
    India
    Posts
    673

    Re: PHP with AJAX Problem

    Not sure if there's any benefit to using mysqli_ functions if you're not taking advantage of what they do differently as opposed to mysql_ functions.
    I read in a book, that it is an improved version of mysql. Also i think there must be some benefit being its an advanced version.
    Thankyou for your coding. But even when it return false the form is getting submitted.
    Javascript
    Code:
    function exists_username(field)
    {
    	field = field.value;
    	var url = "functions/main.php?ur=1&ud="+ field;
    	if(XMLHttpRequestObject) 
        {
    	  var obj = document.getElementById("v1"); 
          XMLHttpRequestObject.open("GET", url); 
          XMLHttpRequestObject.onreadystatechange = function() 
          { 
            if (XMLHttpRequestObject.readyState == 4 && 
              XMLHttpRequestObject.status == 200) 
              { 
    	       if(XMLHttpRequestObject.responseText == "Username Already Exists")
    			{
        			obj.innerHTML = XMLHttpRequestObject.responseText;
        			return false;
     			}
              } 
          } 
          XMLHttpRequestObject.send(null); 
        }
    }
    Code:
    function validate_register(frm)
    {
     	with(frm) //here i am using many fields to be validated and so i am using this validation
     	{
    	 	if(exists_username(username)==false)
    	 	{username.focus(); return false;}
     	}
    }
    PHP Function
    Code:
    function checkusername($ud)
    {
    	require_once('dbconnect.php');
    	$query = "SELECT username
    			  FROM users
    			  WHERE username='$ud';";
    	$result = mysqli_query($dbconn,$query);
    	if(!mysqli_num_rows($result))
    	{
      		echo "Username Already Exists";
    	}
    }
    Code:
    <form method="post" action="functions.php" name="frm_register" onsubmit="return validate_register(this)">

  5. #5
    PowerPoster
    Join Date
    Sep 2003
    Location
    Edmonton, AB, Canada
    Posts
    2,629

    Re: PHP with AJAX Problem

    the benefits given from the mysqli extension are mostly related to the fact that it supports parameterised queries; this is something that helps prevent SQL injection. what you're doing with mysqli_query does not benefit from anything at all. just because you have a newer version of something doesn't mean anything is different

    finally, what I said in my original post was that if mysql_num_rows() returns anything above 0, the username is taken. what you seemed to take this as is if it didn't return anything, the username is taken. you need to get rid of the not ("!") operator in your if statement now. maybe you're not understanding what your query is actually doing? your query is going to the database and looking for any usernames that have the username being submitted on your form right now. if any result comes back from this, then the name is already taken. mysql_num_rows() will count the number of results returned. if it returns a 0, that means there are no users in your database using the username. if it returns above 0, then at least one person (and since it's unique, hopefully only one person) is using that username.

    I'll leave the javascripting to Samba! I've got to go play more Mass Effect 2.

  6. #6

    Thread Starter
    Fanatic Member bharanidharanit's Avatar
    Join Date
    Oct 2008
    Location
    India
    Posts
    673

    Re: PHP with AJAX Problem

    Hi,
    I tried this return method, before you suggested, but not working and so i posted here
    thankyou.

  7. #7
    Frenzied Member
    Join Date
    Apr 2009
    Location
    CA, USA
    Posts
    1,516

    Re: PHP with AJAX Problem

    I'll leave the javascripting to Samba!
    But... Eternal Sonata awaits! It's been so long since my last conventional JRPG and this one's the musical fantasy of the dying composer Chopin!!... Hm, mayhaps the latter explains the former (they do get silly sometimes...). Ahem.

    Let's see, you never actually created a XMLHttpRequest object (and you don't have alternative set up for IE). You might need to set the third parameter on open() to false, or else the request is asynchronous which you likely don't want here. Don't know why you'd send "null" for send().
    Code:
    function exists_username(field){
    	field = field.value;
    	var url = "functions/main.php?ur=1&ud="+ field;
    	if(window.XMLHttpRequest){
    	  var obj = document.getElementById("v1"); 
    	  XMLHttpRequestObject = new XMLHttpRequest();
        XMLHttpRequestObject.open("GET", url, false); 
        XMLHttpRequestObject.onreadystatechange = function(){ 
          if (XMLHttpRequestObject.readyState == 4 && 
            XMLHttpRequestObject.status == 200){ 
             if(XMLHttpRequestObject.responseText == "Username Already Exists"){
              obj.innerHTML = XMLHttpRequestObject.responseText;
              return false;
              }
            } 
        } 
        XMLHttpRequestObject.send(""); 
      }
    }
    And on the validate_register() function, I hope you've left out some code that populates the variable "username" with what you expect it to be; with only the code you've posted here, username should be undefined.

  8. #8

    Thread Starter
    Fanatic Member bharanidharanit's Avatar
    Join Date
    Oct 2008
    Location
    India
    Posts
    673

    Re: PHP with AJAX Problem

    Hi thankyou,
    I worked on that code, but that also doesn't works,
    I debugged that code using alert, the code doesnot coming to the second if part, so i placed the second if part(also with else), after the first if part instead of the nested if. This time at whatever conditions(==,!=), the code only considering the else part but not if part, after once the first if part gets executed.
    This is my code
    Code:
    function exists_username(field)
    {
    	field=field.value;
    	var url = "functions/main.php?ur=2&ud="+ field;
    	if(XMLHttpRequestObject) 
        {
    	  var obj = document.getElementById("v4"); 
          XMLHttpRequestObject.open("GET", url,false); 
          XMLHttpRequestObject.onreadystatechange = function() 
          { 
            if (XMLHttpRequestObject.readyState == 4 && 
              XMLHttpRequestObject.status == 200) 
              { 
              var txt=XMLHttpRequestObject.responseText;
              } 
             if(txt == "Username Already Exists")
    			{
              		obj.innerHTML = txt;
             	 	return false;
             	 	alert("if part");
             	}
             	else
             	{
    	         	alert("else part");
    	         	return true;
             	} 
          } 
          XMLHttpRequestObject.send(""); 
        }
    }
    Let's see, you never actually created a XMLHttpRequest object (and you don't have alternative set up for IE).
    sorry i forgot to upload that code
    Code:
    if (window.XMLHttpRequest) 
    {
      	XMLHttpRequestObject = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) 
    {
    	XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
    }
    And on the validate_register() function, I hope you've left out some code that populates the variable "username" with what you expect it to be; with only the code you've posted here, username should be undefined.
    SambaNeko is offline Rate this post
    Add to SambaNeko's Reputation Report Post Reply With Quote
    I am using with(field) here, field here is the form name, so when i specify "username" here, it will take the username field from the form and pass it to the function.
    This works for me.
    Code:
    function validate_register(frm)
    {
     	with(frm) //here i am using many fields to be validated and so i am using this validation
     	{
    	 	if(exists_username(username)==false)
    	 	{username.focus(); return false;}
     	}
    }

  9. #9
    Frenzied Member
    Join Date
    Apr 2009
    Location
    CA, USA
    Posts
    1,516

    Re: PHP with AJAX Problem

    I am using with(field) here, field here is the form name, so when i specify "username" here, it will take the username field from the form and pass it to the function.
    This works for me.
    You're right, my mistake.

    For the exists_username() function, It looks like you didn't put in the stuff I added in my previous post... You can't check "if(XMLHttpRequestObject)" because XMLHttpRequestObject is a var you create later in your script... and you're still not creating it, actually. You have the right code, you just need to put it in the right place:
    Code:
    function exists_username(field)
    {
      field=field.value;
      var url = "functions/main.php?ur=2&ud="+ field;
      
      if (window.XMLHttpRequest) 
      {
        XMLHttpRequestObject = new XMLHttpRequest();
      }
      else if (window.ActiveXObject) 
      {
        XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
      }  
      
      if(XMLHttpRequestObject) 
      {
        var obj = document.getElementById("v4"); 
        XMLHttpRequestObject.open("GET", url,false); 
        XMLHttpRequestObject.send("");
        var txt=XMLHttpRequestObject.responseText; 
        if(txt == "Username Already Exists")
        {
          obj.innerHTML = txt;
          return false;
          alert("if part");
        }
        else
        {
          alert("else part");
          return true;
        }
        
      }
    }
    Also, as I've corrected above, there is no "onreadystatechange" if your XMLHttpRequest is not asynchronous (if you set the third parameter in open() to false). The script won't proceed until there is a response, so you don't need to explicitly check for one.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width