简体   繁体   中英

Best practice for sending JSON to php with keeping field types

Obviously, if I send JSON data to php using an AJAX post or get request I will end up only receiving string data type in the php $_POST variable.

What is best practice for sending JSON fields but keeping their data types? My idea would be to send the whole JSON in one $_POST field, and then decoding it one more time.

So in JavaScript instead of:

$.post('test.php', {"stringparm":"a string","numparm": 66,"boolparm":true)}, function (result) ... 

I would use:

params = '{"stringparm":"a string","numparm": 66,"boolparm":true)}';
$.post('test.php', {'params': params}, function (result) { 
....
}

And in php I would:

$params = json.decode($_POST['params']);

or is there a better way?

My recommendation would be to send them as a query string using Fetch or Axios, you can use Ajax as well and it should send the various datatypes properly, and then parse the query string in PHP like this.

parse_str($_SERVER['QUERY_STRING'], $data);
$data = (object) $data;

I'm sure you know what your standard query string looks like

https://example.com/?user_id=value&someotherdata=value etc...

Once you have the $data object you can access the values with the arrow -> operator.

$user_id = $data->user_id

Here is a script I use to create a query string from a provided object.

  prepareQuerystring(url, paramsObject, isParamsObjectUsed, phpMethod = '') {
if (url !== '') {
  let postUrl = `${url}${phpMethod}`;
  if (isParamsObjectUsed) {
    postUrl += `?`;
    let it = 0;
    let len = Object.keys(paramsObject).length
    for (let i in paramsObject) {
      if (it === len - 1) {
        postUrl = postUrl + [i] + '=' + paramsObject[i];
      } else {
        postUrl = postUrl + [i] + '=' + paramsObject[i] + '&';
      }
      it++;
    }
    return postUrl;
  } else {
    postUrl = `${url}${phpMethod}/`;
    return postUrl;
  }
} else {
  let postUrl = `${window.location.href}${phpMethod}/`;
  if (isParamsObjectUsed) {
    postUrl += `?`;
    let it = 0;
    let len = Object.keys(paramsObject).length
    for (let i in paramsObject) {
      if (it === len - 1) {
        postUrl = postUrl + [i] + '=' + paramsObject[i];
      } else {
        postUrl = postUrl + [i] + '=' + paramsObject[i] + '&';
      }
      it++;
    }
    return postUrl;
  } else {
    postUrl = `${window.location.href}${phpMethod}/`;
    return postUrl;
  }
}

}

The url argument is your base url ( https://example.com )

The paramObject is your JSON object which is just an object in Javascript.

  {
    user_id: 1,
    someotherdata: 'shoe'
  }

The PHP method argument is there to call a specific method in php, it simply gets appended after the base url, my API lets me make calls this way, yours might not so you can just leave that as an empty string ''.

And the isParamsObjectUsed is a boolean, if you pass an object in the second argument then this will be true, I honestly can't recall ever setting it to false so may need to refactor and remove that eventually.

Heres an example of how to use it.

      let url = prepareQuerystring(
        https://example.com/,
        {
          user_id: 1,
          someotherdata: 'shoe',
          someBool: true
        },
        true
      )

You will have reference to all the parameters as their data type in PHP using this method. I use Axios to send http requests but this also works with Ajax and Fetch, I'd recommend using Fetch or Axios. Mostly because I can't remember how I got it working with Ajax, I typically use Fetch or Axios.

Using Fetch

fetch(url, { method: "POST" })

Hope this helps point you in the right direction. Let me know if you have any questions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM