简体   繁体   中英

How to open jQuery dialog message spontaneously (according to db change)?

I know how to call jQuery dialogbox. First I will design my dialog box and I will call as

$('#dialogbox').dialog('open');

usually I call dialog box at page load or at any event like button click etc.

But my scenario is like this. My client send an emergency message , that I will get in server (A web application). The message may come at any time. when message comes I store it in DB. Here I have to pop up on server application. For that I plan to use jQuery dialog. The message may come at any time, I mean message may come in server when http://localhost:8080/ITS/Login.html page is open or it come on when http://localhost:8080/ITS/BusDetail.html is open so I have show the popup if it comes login.html and also BusDetails.html like this so many html, JSP pages are there . So how can I call jquery dialog for this kind of scenario. Please help me in this.

Why not make a request to the server when the page loads via ajax asking if it needs to display the modal. So whenever the page is refreshed you find out if the modal needs to display or not.

You have 2 options, or you are making a timed ping from your client. Means that every X seconds, you will need to send a request to the server for checking if any rows were updated. Or, you will need WebSocket in here.

The first option , is to have a setInterval:

 function checkDatabase(){
     $.ajax({url: "http://wwww.myserver.com/getDBcheck", success: function(result){
    $('#dialogbox').dialog('open');
  }});
    var myVar = setInterval(checkDatabase, 1000)

This will poll the server each 1 second (or more if you want), to see if there is a new message.

You can check more about WebSockets here .

The second option :

For WebSockets, your server should support WS.

In your Javascript code client , you should initiated the WebSocket handshake like this :

    // Create WebSocket connection.
const socket = new WebSocket('ws://localhost:8080');
// Connection opened
socket.addEventListener('open', function (event) {
    socket.send('Hello Server!');
});
// Listen for messages
socket.addEventListener('message', function (event) {
    console.log('Message from server ', event.data);
    $('#dialogbox').dialog('open');
});

Note: the WebSocket URL should be the address of your WS server + the port you have set in your server.

Here an example of how to implement WebSocket with JSP +TOMCAT 7 https://www.programering.com/a/MDO4cDMwATE.html

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