简体   繁体   中英

how to get only one value of returned data from ajax

I have problem to get one value of returned data from ajax call to make a decision. this is my jquery code which call to a php file.

var displayMsg = $.ajax({
    url:"displayMessage.php"    
});
displayMsg.done(function(data){
    // I need to put an if condition in here.
})

this is my "displayMessage.php" file which takes its value from session

<?php 
session_start();
include "classes.php";
$chat = new chat();

$chat->setSenderUserName($_SESSION['userName']);
$chat->setReceiverUserName($_SESSION['receiverUserName']);
$chat->displayMessage();
?>

this file will call the function in the main file, and this is that function

public function displayMessage(){
    include "connection.php";
    $displayMsg = $connection->prepare("select date, senderUserName, message from messages where (senderUserName = ?
    and receiverUserName = ?) or (senderUserName = ? and receiverUserName = ?) order by date desc");
    $displayMsg->bind_param("ssss", $senderUserName, $receiverUserName, $receiverUserName, $senderUserName);

    $senderUserName=$this->getSenderUserName();
    $receiverUserName=$this->getReceiverUserName();

    $displayMsg->execute();
    $displayMsg->store_result();

    $displayMsg->bind_result($messageDate, $senderUserName, $message);
    while($displayMsg->fetch()){
        $this->setSenderUserName($senderUserName);
        $this->setMessage($message); 
        $this->setMessageDate($messageDate);
        ?>
        <span style="color:#00F"> <?php echo $this->getSenderUserName(); ?></span>&nbsp; says: <br />
        <?php echo $this->getMessage(); ?>
        <span class="date"><?php echo $this->getMessageDate(); ?></span><br />
        <?php
    }
}

now I want to access to messageDate value to compare it with the current time in successful part of ajax call (or in done part) but I don't know how. I try some solutions in site which was close to my case but none of them work and I receive Undefined or object Object. like:

$(data).find(".date").html();
$(data).find(".date").text();
$(data).find(".date").val();
$(date['date']);

if you are sure that displayMessage.php returns something in response use this code instead of your jquery code:

var displayMsg = null;
$.ajax({
url:"displayMessage.php",
success:function(data){
   displayMsg  = data;
       displayMsg.done(function(data){
       // I need to put an if condition in here.
       });
} 
});

be sure to check your condition inside success function because ajax may take long to response and jquery does not wait for it and continues to run next commands.

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