Getting undefined after the ajax call

Hi

I am trying to build Ajax & Codeigniter login form. My first objective is if the user enter wrong username or password, to inform him with jquery, without relaoding the page. But after the ajax call, I am getting undefined in the console instead of my error message. Here is the code from the JavaScript (jQuery)


formLogin.on('submit', function(e,errorMessage){

           $.ajax({
            type: 'POST',
            url: 'loginCheck',
            data: $(formLogin).serialize(),
            dataType: 'json',
            success: function(){
                console.log('my message ' + errorMessage);

                }
            });

              e.preventDefault();
       });

And here is the code from the Codeigniter controller.




if .....
// the code that checks for the username and password against the database and user is found....

else {
// user is not found, so populate the error message....

                    $errorMessage = "Wrong Username or Password";
                     echo json_encode($errorMessage);

               // $this->cms($errorMessage);

	        }

In the console log, I am getting the following message:

my message undefined.

Any help will be deeply appreciated.

Regards, zoreli

The problem is where you placed your errorMessage argument:

formLogin.on('submit', function(e[COLOR=#ff0000],errorMessage[/COLOR]){

Whenever you use the $.ajax method all return arguments need to be part of the success(), error() or complete() methods as they are what return the strings from your PHP source, see the below:

formLogin.on('submit', function(e) {
    e.preventDefault();
    
    $.ajax({
        type : 'POST',
        url : 'loginCheck',
        data : $(formLogin).serialize(),
        dataType : 'json',
        success : function(errorMessage) { 
            console.log('my message ' + errorMessage);
        }
    });
});

Hi Chris

Thanks for your help, that did the trick.

Regards, zoreli