vendredi 29 mai 2015

Ajax call onSubmit not working

I have a log-in form. Before do the log-in I would like to make sure that username and password are true.. I am trying to achieve this with ajax, but so far it is not working..

in my form I am calling the function check_user onSubmit. This is my code.

    function check_user(e){
        var username = $('#username').val();
        var password = $('#password').val();

        if(username.length>1 && password.length>1){
        e.preventDefault(); // I added this but still it is not working
        alert('alive'); // this is working          

                jQuery.ajax({
                    type : "POST",
                    url : "check_user.php",
                    data : 'username=' + username +"&password=" + password,
                    cache : false,
                    success : function(response) {
                        if (response == 1) {
                        return true;                    
                        } else {        
                        $('#username').css('border', '2px red solid');
                        document.getElementById("username").placeholder = "Wrong username or password";
                        $('#password').css('border', '2px red solid');
                        document.getElementById("password").placeholder = "Wrong username or password";                     
                        return false;                   
                        }
                    }
                });     
        }else{
//this is working
            $('#username').css('border', '2px red solid');
            document.getElementById("username").placeholder = "Wrong username or password";
            $('#password').css('border', '2px red solid');
            document.getElementById("password").placeholder = "Wrong username or password";
            return false;   
        }
    }

In my PHP file check_user.php I have also this code:

$fp = fopen("debug.txt", "a") or die("Couldn't open log file for writing.");
        fwrite($fp, PHP_EOL ."inside");
        fflush($fp);
        fclose($fp);

No debug.txt is created so I assume that the ajax call never happens..

I use the same ajax code when doing the registration to check if the username or email already exists in the database, and the ajax there is working ok. In my example the ajax call never happens and it goes straight to the action="login.php"

Aucun commentaire:

Enregistrer un commentaire