Search code examples
javascriptphpjqueryajaxcodeigniter-2

What is wrong with this ajax.js code?


This function is intended to check whether or not a user login exists or might be available, but even with an empty user database table the form always displays that it is a duplicate and thus the submit button goes away. What is wrong with the script?

function cre_username() { /// function
    var cre_username = $('#cre_username').val();

    if (cre_username.length > 0) {
      $.post(base_url() + 'ajax/ch_username/' + cre_username, function(data) {
        if (data == 1) {
          $('#ch_user').css('color', 'red');
          $('#ch_user').html(' Already Exists ..!');
          $('#cre_username').css('box-shadow', '0px 0px 5px 1px red');
          $('#cre_pass').slideUp(500);
          $('#cre_cpass').slideUp(500);
          $('#cre_passl').slideUp(500);
          $('#cre_cpassl').slideUp(500);
          $('#cre_user_submit').attr('type', '').slideUp(100);
        } else {
          $('#ch_user').css('color', 'green');
          $('#ch_user').html(' Available');
          $('#cre_username').css('box-shadow', 'none');
          $('#cre_pass').slideDown(500);
          $('#cre_cpass').slideDown(500);
          $('#cre_passl').slideDown(500);
          $('#cre_cpassl').slideDown(500);
          $('#cre_user_submit').attr('type', 'submit').slideDown(500);

        }
      });


Solution

  • As it stands, data == 1 is only checking if there is any sort of data response. It's roughly the same as saying if (data). Chances are, even on failed check, that there is some sort of response.

    Try console.log()ing your data and seeing what the response actually is for a username that you know doesn't exist. Use this response to reform your conditional. Unfortunately, without knowing how exactly your URL/ajax/ch_username route is responding, I can't provide code to demonstrate this.