简体   繁体   中英

AJAX request not returning data

I am trying to run a script in the background of my PHP pages that will check if new messages have been added to the database and notify the user.

I used AJAX to call a file with the code and the setTimeout() to call it every 10 seconds.

The problem is that the ajax is not returning any data. I tried just putting "return: 1;" but i still get an blank alert box.

PHP:

require('connect.php');
require_once("inc/init.php");

$check_Mail_footer = $con->prepare("SELECT * FROM mail WHERE `to` = ? AND `deleted` = ? AND `read` = ?");
$check_Mail_footer->execute(array($user_id,0,0)); 
$result = $check_Mail_footer->fetch(PDO::FETCH_OBJ); 

return array($result->from, $result->message_id);

Javascript:

        function checkNewMail(){

        $.ajax({
              url: 'newMessageCheck.php',
              success: function(info) 
              {
                  alert(info);

              }, error: function()
              {
                  alert('something went wrong');
              }
        });

        }


        setTimeout( checkNewMail() ,10000);

You need to echo out the data you want to return to Javascript - you can't return it

For your array, you probably want to json_encode it first so write:-

echo json_encode(array($result->from, $result->message_id));

to replace:-

return array($result->from, $result->message_id);

and then change your $.ajax call to automatically parse the JSON

$.ajax({
          type: "GET",
          url: 'newMessageCheck.php',
          dataType:'json',
          success: function(info) 
          {
              alert(info[0]);

          }, error: function()
          {
              alert('something went wrong');
          }
    });

In your PHP script, use this method:

$json = array(
  'from'       => $result->from,
  'message_id' => $result->message_id
);

$jsonstr = json_encode( $json );
echo $jsonstr;

And in the javascript function, you can access this way:

$.ajax({
  type: "GET",
  url: 'newMessageCheck.php',
  dataType:'json',
  success: function(info) {
    alert(info.from + "," + info.message_id);
  }
});

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