In my Javascript code, I form my query like so:
let query = "needleKey=" + encodeURIComponent(needle.key)
query += "&needleValue=" + encodeURIComponent(needle.value);
query += "&newData=" + encodeURIComponent(JSON.stringify(newData));
fetch(API, {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded', // <-- Specifying the Content-Type
}),
body: query
})
.then(handleErrors)
.then(response => {
resolve(response.text());
})
.catch(err => {
console.error("ERR: Error fetching " + API + query + "\n" + err);
reject(err);
});
I collect this on the back end with the PHP code:
if (isset($_REQUEST['needleKey']) && isset($_REQUEST['needleValue'])) {
$needleKey = $_REQUEST['needleKey'];
$needleValue = $_REQUEST['needleValue'];
$filter = [$needleKey => $needleValue];
} else {
echo "ERR: No needle passed to DB server.";
return;
}
My issue is that if needle.value
in the javascript code is a integer (ie: 1234
) it ends up as the string '1234'
in the PHP code. I have tried converting the string to an int in PHP (and it works) but I don't want to blindly convert ALL needleValues
to integers because I have occasion where I want to be able to pass a number as a string.
I tried adding rawurldecode to the php code to no success. I've also tried a few different ways of forming the query in javascript, to no avail.
How can I pass a number from javascript to PHP and have it stay a number?