1

I use ajax to check if the user name is registered or not , here in this case i dont want to submit the form when the ajax result is false (ie,if username exists).

 $(document).ready(function(){  
  $('#name').change(function(){  
       var name = $('#name').val();  
       if(name != '')  
       {  
            $.ajax({  
                 url:"<?php echo site_url().'/login_controller/check_name_avalibility' ?>",  
                 method:"POST",  
                 data:{name:name},  
                 success:function(data){  
                      $('#name_result').html(data);  
                 }  
            });  
       }  
  });  });
Sooraj S
  • 145
  • 1
  • 9
  • you can get the concept from here https://stackoverflow.com/questions/8664486/javascript-code-to-stop-form-submission – Vipin Kumar Dec 18 '17 at 09:44
  • Need complete code of java script, very short information this is. I would recommend use JQuery Validator plugin to handle validation. – Anup Yadav Dec 18 '17 at 09:44
  • actually i am checking this from the database. – Sooraj S Dec 18 '17 at 09:45
  • Add your php script too – Ikhlak S. Dec 18 '17 at 09:48
  • @SoorajS jQuery validator as mentioned by Anup supports "remote" validation sources like you're trying to achieve. And then it integrates it all nicely with the form submission process. – ADyson Dec 18 '17 at 10:06
  • actually iam trying to learn how to write the code , so if i use plugin it is not helpfull for me thats why .... – Sooraj S Dec 18 '17 at 10:10

1 Answers1

0

Return true or false from your PHP script:

$result = mysqli_query("SELECT * FROM users WHERE username = $username", $conn);
if($founduser = $mysqli_fetch_assoc($result)){
  echo 1;
}else{
  echo 0;
}

Note: This script is open to SQLInjection. Use prepared statements instead.

Your front end Ajax would look like:

$('#name').change(function(){  
       var name = $('#name').val();  
       if(name != '')  
       {  
            $.ajax({  
                 url:"<?php echo site_url().'/login_controller/check_name_avalibility' ?>",  
                 method:"POST",  
                 data:{name:name},  
                 success:function(data){  
                      if(data = 1){
                        // username found
                        $('#name_result').html(data);
                      }else{
                        // submit form
                      }
                 }  
            });  
       }  
  }); 
Ikhlak S.
  • 8,578
  • 10
  • 57
  • 77