Search code examples
phpjqueryajaxajaxformjquery-ajaxq

Ajax does not execute success function


I have a jquery ajax function that submits form data to a php file where its checked against a database and returns the response. But my success function isn't being executed, instead the response is returned through the error function.

Following is my login.js code:

$(document).ready(function(){
    $("form#loginForm").submit(function() { // loginForm is submitted
        var username = $('#username').attr('value'); // get username
        var password = $('#password').attr('value'); // get password

    if (username && password) { // values are not empty
        $.ajax({
            type: "POST",
            url: "url", // URL of the Php script
            contentType: "application/json; charset=utf-8",
            dataType: "json", //expected from server in response
            // send username and password to the Php script
            data: "username=" + username + "&password=" + password,


            error: function(XMLHttpRequest, textStatus, errorThrown) { // script call was *not* successful
                $('div#loginResult').text("responseText: " + XMLHttpRequest.responseText
                + ", textStatus: " + textStatus
                + ", errorThrown: " + errorThrown);
                $('div#loginResult').addClass("error");
            },

            success: function(data){ //script was successful, data contains response from mysql database
                if (data.error) { // login was not successful
                    $('div#loginResult').text("data.error: " + data.error);
                    $('div#loginResult').addClass("error");
                } // if
                else { // login was successful
                    $('form#loginForm').hide();
                    $('div#loginResult').text("data.success: " + data.success);
                    $('div#loginResult').addClass("success");
                } //else
            } // success
        }); // ajax
    } // if
    else {
        $('div#loginResult').text("enter username and password");
        $('div#loginResult').addClass("error");
    } // else
    $('div#loginResult').fadeIn();
    return false;
});
});

This is my Login.php code:

 <?php



$username = $_POST["username"];
$password = $_POST["password"];


$dbhost = '*****';
$dbuser = '*****';
$dbpass = '*****';
$conn = mysql_connect($dbhost, $dbuser, $dbpass); // connect to server
if(! $conn )
{
    die('Could not connect: ' . mysql_error());
}

echo 'Connected to database successfully,';

mysql_select_db('sl493',$conn); //pick sl493 database


$result = mysql_query("SELECT *
        FROM metauser
        WHERE metauser.username = '$username'
        AND metauser.password = '$password'") or die(mysql_error()); //select data from metauser table

$row = mysql_fetch_assoc($result);

if($row['username'] == $username) //If username and password not accepted
{$result = 'true login';
 $arr = array('success' => "login is successful");
 echo json_encode($arr);}

else //if username and password are not accepted
{$result = 'login failed';
 $arr = array('error' => "username or password is wrong");
 echo json_encode($arr);}

?>

Right now I get the following response regardless if i type correct or incorrect credentials:

responseText: Connected to database successfully,{"success":"login is successful"} , textStatus: parsererror, errorThrown: Invalid JSON: Connected to database successfully,{"success":"login is successful"} https://i.sstatic.net/4xynj.jpg

It returns "Connected to database successfully" which means it goes successfully to login.php but it also returns responseText which is part of ajax:error, where it shouldn't be going since function is executed successful.HALP ?


Solution

  • I figured what was wrong:

    1. First I specified ContentType as json while i was sending it as a string so i had to change that.

    2. Second I used the Is_set andis_empty function for $_POST to make sure i was getting the POST fields.

    3. Finally the return ajax variable data for reason wouldn't display it by key, so data.success is undefined but data returns all the output from the php file.

    I am still trying to figure out why i can't access the returned JSON by key. Please let me know if you have any suggestions, I don't to create another question. Following is the working code:

    $(document).ready(function(){
        $("form#loginForm").submit(function() {
    
        // loginForm is submitted
            var username = $('#username').attr('value'); // get username
            var password = $('#password').attr('value'); // get password
            console.log(username + password) ;
    
            if (username && password) { // values are not empty
                $.ajax({
                    type: "POST",
                    url: "https://xxx/login.php", // URL of the Php script
                    contentType: "application/x-www-form-urlencoded; charset=utf-8",
    
                    dataType: "application/json", //expected from server in response
                    // send username and password to the Php script
                    //data: "username=" + username + "&password=" + password,
                    data:'username='+ username+'&password='+ password,
    
                    error: function(XMLHttpRequest, textStatus, errorThrown) { // script call was *not* successful
                        $('div#loginResult').text("responseText: " + XMLHttpRequest.responseText
                        + ", textStatus: " + textStatus
                        + ", errorThrown: " + errorThrown);
                        $('div#loginResult').addClass("error");
                    },
    
                    success: function(data){
    
    
                        $('form#loginForm').hide();
                        $('div#loginResult').text("Login: " + data );
                        $('div#loginResult').addClass("success");
                                                                    }
    
    
                });
            }
            else {
                $('div#loginResult').text("enter username and password");
                $('div#loginResult').addClass("error");
            } // else
            $('div#loginResult').fadeIn();
            return false;
        });
    })
    

    ;

    Login.php

    <?php
    
    if (isset($_POST["username"]) && !empty($_POST["username"])) {
        $username = $_POST["username"];}
    
    if (isset($_POST["password"]) && !empty($_POST["password"])) {
        $password = $_POST["password"];}
    
    $dbhost = 'xxx';
    $dbuser = 'xxxxxx';
    $dbpass = 'xxxxxxxx';
    $conn = mysql_connect($dbhost, $dbuser, $dbpass); // connect to server
    if(! $conn )
    {
        die('Could not connect: ' . mysql_error());
    }
    mysql_select_db('sl493',$conn);
    
    $query = mysql_query("SELECT *FROM metauser WHERE metauser.username = '$username'AND metauser.password = '$password'") or die(mysql_error()); //select data from metauser table
    $row = mysql_fetch_assoc($query);
    
    
    if($row['username'] == $username)
    {
            if($row['usertype']== 'student')
                  { $type = 'student'; }
                        else{ $type = 'admin'; }
    
        //$arr = array('result' => 'loginOK', 'usertype' => $type);
    
        $associativeArray = array();
        $associativeArray ['result'] = 'success';
        $associativeArray ['usertype'] = $type;
    
        //$arr = '{"success":"login is successful"}';
        //echo $type;
        echo json_encode($associativeArray); }
    
    
    else
    {$arr = '{"error":"username or password is wrong"}';
        echo json_encode($arr);}
    
    ?>