How can I do an AJAX update, for example, with a Gmail inbox?

I am creating a messaging system and I am currently reloading the contents of a div containing messages every 10 seconds using jQuery .load() , but I have a problem: when I try to make the β€œSelect All” button, Delete Selected, etc. ., When it comes 10 seconds, it reloads the buttons and reloads the messages, so the messages become unavailable due to a reboot.

What I would like to know is how to make it load in new messages, but not reload the entire div. I know that Gmail does not reload the entire div because it works correctly.

This is my JavaScript function that reloads the div and changes the page title (incoming message counter), so it remains updated:

 function title() { setTimeout("document.title = $('#heading').text();", 500); } function ajaxStuff() { setTimeout("$('#heading').load('/employee/message/inbox.php #h1_head'); $('#messages').load('/employee/message/inbox.php #messages_inner');title();ajaxStuff();", 10000); } ajaxStuff(); 

This is how I set up the mailbox:

Inbox screenshot

Basically what I want to do is upload to new posts using AJAX, but somehow not refresh the div. I tried to take a look at the source of Gmail, but there is too much to go through, and they are confused with a bunch of random classes and identifiers.

Note. I searched this on Google for a while and found nothing.

+4
source share
2 answers

When checking for new messages, send the identifier of the most recent message to your request. Then your php will only return everything new that you add to existing data.

  jQuery.ajax({ type: 'get', dataType: 'text', url: "/employee/message/inbox.php", data: { from_user : from_user, to_user: to_user, message_id: message_id, something_else_you_need_to_send: its_value t: Math.random() }, success: function(data, textStatus){ // whatever you need to do with the result returned from php (server) } 

Then in your sql query you

 select * from table where user_id=user_id_from_ajax and message_id > message_id_from_ajax` 

Update

in your php you use

  $from_user = $_REQUEST['from_user']; $to_user = $_REQUEST['to_user']; $message_id = $_REQUEST['message_id']; 
+4
source

In response to the comments:

I do not think the textbook is justified here. Modify the server code to return "new" messages with the class="new" attribute, and then use:

 $.ajax({ url: "/employee/message/inbox.php", success: function(result) { $(result).find(".new").prependTo("#heading"); } }); 

Of course, this code may require some changes according to your environment / return data.

+5
source

All Articles