0

in the axios docs, it shows that you can POST an object directly through the data parameter, thusly:

axios({
  method: 'post',
  url: 'someHandler.php',
  data: {
    id: 200,
    sox: 'blue'
})

what i want to know is if you can PASS AN OBJECT into that data parameter:

myObj = {
  id: 200,
  sox: 'blue'
}
axios({
  method: 'post',
  url: 'someHandler.php',
  data: myObj
)

the above DOESN'T WORK, though it seems to me it should seeing as it's going to be JSON-encoded anyway. i've searched the docs, but can't find anything that answers this question.

i know that i can append myObj to a formData and pass it that way, but i want to know if i'm overlooking a simpler way.

WhiteRau
  • 818
  • 14
  • 32
  • 1
    Looks right to me. How do you know it _"doesn't work"_? – Phil Jan 20 '21 at 23:39
  • because the `$_POST` array in the PHP handler comes up empty every time. but, i hear ya: it looks solid. – WhiteRau Jan 20 '21 at 23:41
  • does it work without the object assignment? i mean does the first snippet work? – dardardardar Jan 20 '21 at 23:43
  • yep. works just fine. my issue is i'm passing a large JSON object into it, so i'm not interested in manually entering the data. nor can i, as it comes in from other functions. – WhiteRau Jan 20 '21 at 23:45
  • @WhiteRau — "because the $_POST array in the PHP handler comes up empty every time" — PHP doesn't support populating `$_POST` with JSON – Quentin Jan 20 '21 at 23:46
  • 2
    You're posting JSON though so neither example above will populate PHP's `$_POST` variable. For that, you want `$json = file_get_contents("php://input");` – Phil Jan 20 '21 at 23:46
  • For the post data to be read via `$_POST`, you will need to use `FormData()`. The only way to read the object you're posting in your code is via `"php://input"` as aptly pointed out by @Phil. – codemonkey Jan 20 '21 at 23:54
  • okay. that's what i wanted to know. the JSON is sent by axios. i'm just passing an object into axios. perhaps i wasn't clear there. the JSON is going to the PHP handler via axios. the function is just passing objects to axios. – WhiteRau Jan 21 '21 at 00:01

0 Answers0