Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Customising the CMS /

Simple username input check problem - AJAX


Reply


2 Posts   502 Views

Avatar
Johnny9

Community Member, 22 Posts

25 September 2013 at 8:29am

Edited: 25/09/2013 8:34am

Hi, I am trying to make validation of a username field. Checks if exist and if exist, shows "choose another name" via ajax.

But problem is, that no value is passed to variable via Ajax. $_POST['username'] is empty.

So my code in controller:

public function checkuser1(){

      $Params = $this->getURLParams();      
      
if($Params['ID'] == '1'){
         
            if (Director::is_ajax()) {
               
                  $username = $_POST['username']; // Seems that I dont receive any value from input vie ajax

                  $username = mysql_real_escape_string($username);
                  $check_for_username = mysql_query("SELECT ID FROM Member WHERE UserName='$username'");
                  if(mysql_num_rows($check_for_username))
                  {
                     return '1';
                  }
                  else
                  {
                     return '0';
                  }
                  
            }
            else {
               return Director::redirect(Director::baseURL());
            }                   

   }
}

   
public function checkuser(){

      return $this->checkuser1();

}

And JS code:

<script type="text/javascript">

$(document).ready(function(){
$("#Form_RegistrationForm_UserName").change(function(){
$(".container .inner .top .right").html("<img src='ajax-loader.gif' /> checking...");

               var username = $("#Form_RegistrationForm_UserName").val();
               var dataString = 'username='+ username;

                  $.ajax({
                        type:"post",
                        url:"http://localhost/mysite/member/checkuser/1/",
                        data:dataString,
                        success:function(server_response){
                           if(server_response == '0'){
                              $(".container .inner .top .right").html("Username available");
                           }
                           else{
                              $(".container .inner .top .right").html("Username already taken");
                           }
                        }
                      });
      
               });

});

</script>

If anyone knows what is the problem, let me know :) Thanks for any help!

Avatar
Willr

Forum Moderator, 5513 Posts

28 September 2013 at 5:23pm

Try using the web inspector in your web browser, investigate the XHR panel to see what the request is being made (and ensure it contains your post data). I think the jQuery post argument takes an object rather than a string (i.e { 'username': username } rather than username=)