Search code examples
javascriptphpsessionxmlhttprequest

xhr.send and php session value - correct syntax?


What is correct syntax for sending php session data please with xhr.send, my javascript is knowledge is limited I have set the value like this:

var csrf_token_value = '<?php echo $_SESSION['csrf_token']; ?>';

This sets the csrf_token_vale correctly

Not sure correct syntax for xhr.send, the following does not output the session value it just outputs 'csrf_token_value'

xhr.send("csrf_token=" + csrf_token_value);

Thanks


Solution

  • It depends on your request method. If you are using GET, then you'd have to place the token as a query string param in the open() function:

    xhr.open("GET", "/myendpoint?csrf_token=" + csrf_token_value);
    

    ... before you send it.

    If you are using POST then you will need a FormData Object:

    data = new FormData;
    data.set("csrf_token", csrf_token_value);
    

    And then send that with your request:

    xhr.send(form);