Search code examples
javascriptphpajaxcookiesflash-message

Sending flash messages over Ajax (is using cookies good/bad practice ?)


I'd like to send a flash message to show when a request finished. I'd like to put the message directly in PHP, because the logic of which flash message should in my opinion be in the PHP.

My problem is that I send Json data, for example when you GET users/

The JS receives:

[{user:"John","connected":true},{user:"Jane","connected":false},...] // =data

I would like to send the flash Message inside the response, but I don't want to change the Json Output (because it becomes less Developper friendly to send a custom object like {"flash_message":"You are connected","data":data})

So I thought about setting some Cookies that expire in 1 minute, so I can show the flash message when the request is received.

Is this good practice ?


Solution

  • Using cookies is not the best way to go here, because cookies are intended to be persistent data storages, not to send data on a request.

    Custom requests headers are much more appropriated.

    In PHP you can send them like this:

    header("X-flash-message-content: $message");
    

    In JS you can retrieve them like this

    var req = new XMLHttpRequest();
    req.open('GET', document.location, false);
    req.send(null);
    var headers = req.getAllResponseHeaders().toLowerCase();
    console.log(headers);