1

How to send a PHP request to another user through Ajax?

For example, if user A presses the button, user B and nobody else has instant popup telling them about it. In my application, I'm using $_SESSION to declare a logged user and I'm using my own written login system built from scratch.

I just want PHP to send request to specific user with some data.

5
  • 3
    AJAX requests are sent from the browser to the server, not the other direction. If the server needs to send to the browser, you need to make a permanent connection using WebSockets. Or you could use periodic polling with AJAX. Commented May 19, 2016 at 20:23
  • @Barmar I was thinking about periodic polling, but it didn't seem professional. Commented May 19, 2016 at 20:24
  • 2
    @Barmar What barman is saying. If you are going the web socket route take a look into NodeJS and socket.io . Also there is no such thing as a PHP request what you referring to is a http request. Commented May 19, 2016 at 20:24
  • @Maantje Wonderful, that's what I was looking for. Thanks! Commented May 19, 2016 at 20:26
  • Look at server side js. It replaces the need for setinterval and it basically pushes requests from the server Commented May 19, 2016 at 20:30

1 Answer 1

1

As Barmar said, WebSockets is the de facto standard to handle continuous polling scenarios.

However, if your application does not need to be updated in real time and you will never have over a certain amount of users, you could use a JavaScript timer to load the resulting XML from an AJAX transaction and update the page via the DOM. Be conscious of how difficult it is to scale continuously polling applications.

Should you opt to go with continuously polling AJAX, an expected design would be along these lines:

  1. User A posts data to a PHP program on the server.
  2. The PHP program saves the user's action into a 'cache' table in a database.
  3. User B's client eventually makes an AJAX request to the server.
  4. Any items in the 'cache' table that contain that user's user ID ($_SESSION['user_id'] or something to that effect) will be returned to user B's client.
  5. User B's client alerts them that a message was received.

Keep in mind that even if you only poll every 30 seconds, with enough users you could end up DDoS-ing your own server while polling for messages.


Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.