1

I'm making a simple login test and the code returns the json response when the fields are empty,but not when the login fails or succeds, like:

  • Empty Fields - OK
  • Login Succeded - nope
  • Login failed - nope

Request:

var loader = $('#trabalhando');
$(function() {
    $('form').submit(function(e) {


        loader.fadeIn("slow");
        e.preventDefault();


        $.ajax({
            url: 'login.php',
            data: $(this).serialize(),
            method: 'post',
            dataType: 'JSON',
            success: function(data){
                loader.fadeOut("slow");
                console.log(data);
                alert(data.resp);
            },
            error: function(data) {
                alert(':(');
                loader.fadeOut("slow");
                console.log(data);
            }
        });

    });
});

Response:

<?php
header('Content-Type: application/json');
if (isset($_POST['cpf']) && isset($_POST['pass']) && $_POST['cpf'] != "" && $_POST['pass'] != "") { 

    $cpf = $_POST['cpf'];
    $passw = sha1(strrev(md5($_POST['pass'])));

    include 'config.php';

        $sql = "SELECT * FROM users WHERE cpf = :cp AND passwd = :pw";
        $chec = $db->prepare($sql);
        $chec->bindParam('cp', $cpf, PDO::PARAM_STR);
        $chec->bindParam('pw', $passw, PDO::PARAM_STR);
        $chec->execute();

        if ($chec->rowCount() > 0) {

            echo json_encode(array('resp' => 'nice'));

        } else {
            echo json_encode(array('resp' => 'nope'));
        }   

} else {
    echo json_encode(array('resp' => 'fields'));
}

?>

Edit: updated the code

1
  • Check in browser dev tools, network panel, what the request gets answered with, and what the status code is. Commented Aug 25, 2017 at 11:13

2 Answers 2

2

You are not binding your parameters properly, so you probably have a PDO error that you're not handling. Change:

$chec->bindParam('cp', $cpf, PDO::PARAM_STR);
$chec->bindParam('pw', $passw, PDO::PARAM_STR);

To:

// notice the colon : in front of var names, so it matches the placeholders!
$chec->bindParam(':cp', $cpf, PDO::PARAM_STR);
$chec->bindParam(':pw', $passw, PDO::PARAM_STR);

In general, database, file and remote server operations (FTP, HTTP, SSH...) are very finicky so when you rely on these, always error check! You should factor out your queries into a specialized function that does proper error checking.

/**
 * @param PDO $db       The PDO object with which to perform queries
 * @param string $sql   raw SQL (eg: "select * from t where a = :param" )
 * @param array $params Array of parameter names and values eg: [':param' => 'value']
 * @param string $error Will be filled with the error details if the DB operations fail
 * @return false|PDOStatement FALSE on error, or the statement on success
 */
function query(PDO $db, $sql, array $params, &$error){
    try{ 
        // error check every step!
        if(!$stmt = $db->prepare($sql)) throw new Exception($db->errorInfo()[2]);           
        if(!$stmt->execute($params)) throw new Exception($stmt->errorInfo()[2]);

        return $stmt; // return the $stmt for further processing
    }catch (Exception $e){
        $error = $e->getMessage();
        return false;
    }
}

Now you can perform your queries much more simply:

$stmt = query($db, $sql, $params, $error);

// decide what to do on failure
if(!$stmt) die($error);

// now it's safe to use $stmt to fetch results, count rows...

Update

You said:

the fail is exactaly the same as the success, loader out and alert, but this time with a sad face on the alert

That's expected. success in the Ajax call just means that the server responded normally. It doesn't say anything about what is inside the json string. If you want to trigger the error Ajax callback, your server will need to set an error HTTP response code like this:

http_response_code(401);
echo json_encode(array('resp' => 'nope'));

Update 2

To find out the details of the error triggered by the Ajax call, modify the callback and examine the results:

error: function(jqXHR, textStatus, errorThrown){
          console.log('textStatus: ' + textStatus);
          console.log('errorThrown: ' + errorThrown);
        }

Maybe your server is sending other content along with the JSON that is corrupting the output. Try closing the buffer at the top of your script, and exiting immediately with your echo:

<?php
ob_end_clean(); // at top of script

//try echoing this way
die(json_encode(array('resp' => 'nice')));
die(json_encode(array('resp' => 'nope')));
Sign up to request clarification or add additional context in comments.

11 Comments

I removed the ajax call and added the action on the form, and in the login.php page, everything is right, it shows the nope and the nice responses,the ajax just dont get them back, any idea?
@tlckpl what do you see in browser dev tools if you do console.log(data) in the success() handler?
it calls the error method that I added mins ago: Object {readyState: 4, responseText: "{"resp":"nope"}", status: 200, statusText: "OK"}
@tlckpl I don't know what's wrong. If the code you're working on is different from what's on this page, I can't really be helpful to you
the fail is exactaly the same as the success, loader out and alert, but this time with a sad face on the alert
|
1

It would seem like there is either a problem in your config.php file, or with your sql statement

try putting your code into a try catch, and then returning the error as json:

<?php
header('Content-Type: application/json');
if (isset($_POST['cpf']) && isset($_POST['pass']) && $_POST['cpf'] != "" && $_POST['pass'] != "")
{ 

   $cpf = $_POST['cpf'];
   $passw = sha1(strrev(md5($_POST['pass'])));
   try
   {
       include 'config.php';

      $sql = "SELECT * FROM users WHERE cpf = :cp AND passwd = :pw";
      $chec = $db->prepare($sql);
      $chec->bindParam(':cp', $cpf, PDO::PARAM_STR);
      $chec->bindParam(':pw', $passw, PDO::PARAM_STR);
      $chec->execute();
      if ($chec->rowCount() > 0)
      {
          echo json_encode(array('resp' => 'nice'));
      }
      else
      {
          echo json_encode(array('resp' => 'nope'));
      }
   }
   catch(Exception $e)
   {
        echo json_encode($e->getMessage());
   }   

} 
else
{
    echo json_encode(array('resp' => 'fields'));
}

?>

Edit: incorporates @BeetleJuice's fix

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.