-1

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?

lowcrawler
  • 6,777
  • 9
  • 37
  • 79
  • 1
    You can't, http(s) is a textual data transfer protocol. You've to cast the string to a number in PHP, in a way or another. – Teemu Feb 23 '21 at 06:54
  • 1
    Your server should know what type a certain parameter is supposed to be and cast them accordingly, which should also serve as input validation. – deceze Feb 23 '21 at 07:25
  • Great point, @deceze. I was trying to build the endpoint to be very generic -- but by limiting it and doing the validation checks, it'll be more secure. – lowcrawler Feb 23 '21 at 16:34

1 Answers1

2

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.

blaumeise20
  • 2,148
  • 8
  • 26