简体   繁体   中英

Ajax not getting JSON value

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

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')));

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM