Sending referrer URL via WordPress AJAX in vanilla JS

Question

Let’s say you have a form. On submit, you coded the page to submit the form data to a given data base, by holding the data in a json object, like so:

myData = {first_value: value1, second_value: value2}

.. and so on, and converting it to a JSON string before then sending it to the server via AJAX. Now, all of this works perfectly, until the moment where I added the code that the
script shall add the page’s referrer link (obtianed with document.referrer) into the object, if it’s not empty, and also send that additional info to the server in that case.

Problem is that, from what I found, WordPress seems to escape JSON strings using wp_slash() before sending them to the server, resulting in for example, sticking to the example above:

myData = "{"first_value": "value1", "second_value": "value2"}"

The problem with this is that, as soon as the a referrer is added into the myData object, the escape slashing of WordPress does not work properly, and the JSON string’s structure breaks (making that for example keys of myData become actual parameter names). When then using json_decode() on the server – side, I get an empty array when I var_dump(). Happens with pretty much any referrer link, and only since I try to do that.

I tried to use stripslashes() on the server – side, but I get the same empty array when I var_dump(). So I guess using wp_unslash() would yield the same, as the error actually occurs on the client-side already. What I mean by that is, in the data sent in the request Header of the XHR, instead of:

myData : "{"first_value": "value1", "ref":"myUrl", "second_value": "value2" }"

I get something that doesn’t even seem to be a valid JSON string to me anymore:

myData : "{"first_value": "value1", "ref":"myUrl
second_value: "value2" }"

so you can see it kind of breaks the JSON structure at the value of the referrer link. How can I avoid this and safely send referrer links in addition to other data in the same JSON? Is there really no way, and I have to separately serialize the referrer string as a separate request parameter?

0
DevelJoe 8 months 2020-11-25T10:10:24-05:00 0 Answers 10 views 0

Leave an answer

Browse
Browse