javascript - How to decode encodeURIComponent in PHP without integers turning into strings
Get the solution ↓↓↓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 ifneedle.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 ALLneedleValues
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?
Answer
Solution:
In JavaScript you have to use JSON.stringify:
query += "&needleValue=" + encodeURIComponent(JSON.stringify(needle.value));
Then in PHP decode it:
$needleValue = json_decode($_REQUEST['needleValue']);
I'm not sure if this works, but you can try it.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: git was not found in your path, skipping source download
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.