سؤال

I'm trying to make a basic chat system for myself and a friend. It is very simple, however, the ajax is confusing me immensely. I use ajax to request a php page, which I set a username in, and the last time I downloaded a chat. However, I don't know how to read what the php pages echos. I've checked online, but there are so many variations, it left me more confused. Can anyone give me some guidance please?

Scripts.js (with jQuery already linked)

// on document ready + called every second

 $.ajax({
            url: 'download.php',
            type: 'REQUEST',
            datatype: 'json',
            data: ({
                last_downloaded: latestTimestamp,
                username: username
            }),
            success: function (data) {
                console.log(data.message[0].time);
                // Uncaught TypeError: Cannot read property '0' of undefined 
                // how do I get the time from the json?
                // {"message":{"chat":"Hello, world!","time":"2014-05-09 17:32:00,"username":"Josue"},"message":{"chat":"This is my second message.","time":"2014-05-09 17:32:05,"username":"Josue"}}

            }
        });

            latestTimestamp = data.message[0].time;
            downloadingTimer = setTimeout(actuate, timeoutValues[currentTimeoutIndex]);

    }

download.php

this is what my php page echos as a normal string (now properly formatted JSON):

[
   {
      "chat":"Hello, world!",
      "time":"2014-05-09 17:32:00",
       "username":"Josue"
   },
   {
      "chat":"This is my second message.",
      "time":"2014-05-09 17:32:05",
      "username":"Josue"
   }
]

I have header("Content-Type: application/json"); at the top of my page. I am doing something wrong?

هل كانت مفيدة؟

المحلول

Your JSON response is improperly formatted. The comma following the datestamp is inside the quote, instead of outside of it:

      "time":"2014-05-09 17:32:00,"      username":"Josue"
   },

In addition, you should be using square braces to represent an array of messages. Your JSON should look like this:

{ "message": [
   {
      "chat":"Hello, world!",
      "time":"2014-05-09 17:32:00",
       "username":"Josue"
   },
   {
      "chat":"This is my second message.",
      "time":"2014-05-09 17:32:05",
      "username":"Josue"
   }
]
}

You can use the json_encode() function to convert a PHP array or object into a JSON string:

<?php
    $my_arr = array("message" => array());
    $my_arr["message"][] = array("chat" => "Hello, World!", "time" => "2014-05-09 17:32:05", "username" => "Josue");

    echo json_encode($my_arr);
?>

نصائح أخرى

i think its failing because message is not an array. message is an object, so if you have more messages redesign how you are sending them. Your php script should put the messages in a json array , so you can get the first with the 0-index

Two things wrong with this.

One, your JSON is not formatted correctly. "time":"2014-05-09 17:32:00," username":"Josue" Should be "time":"2014-05-09 17:32:00", "username":"Josue". You would probably have seen this in your browser's error console.

Two, you need to put your messages in an array. Otherwise you're just overwriting your message property with each new message, so your front-end will end up with only the lowest message in your php file.

PHP should echo this:

{
    messages: [
        {
            "chat":"Hello, world!",
            "time":"2014-05-09 17:32:00",
            "username":"Josue"
        },
        {
            "chat":"Second message",
            "time":"2014-05-09 17:32:00",
            "username":"Josue"
        }
    ]
}

And then in your JS, your array will be data.messages, with the messages being data.messages[0] and data.messages[1], respectively.

After reformatting your JSON, you might also try to parse the JSON string into a javascript object as well.

var parsed_data = $.parseJSON(data);
// extract data here parsed_data[key]
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top