Skip to content
Advertisement

How do I get fetch() to POST data the same way as jQuery does?

I’m trying to remove jQuery from some code. I only use it for POST operations so I want to drop it and use fetch() instead. But I can’t get fetch() to work using the same data. The php file is working OK, it is just not receiving the data

This sets up the test data for both test cases below:

JavaScript

This works using jQuery:

JavaScript

This does not work using fetch():

JavaScript

For debugging purposes, toMariaDB.php writes out a log file of the data it receives and any other messages from toMariaDB.
Running the jQuery code writes this to the log file:

JavaScript

which is what toMariaDB.php expects.
But the fetch() version writes this:

JavaScript

The result for fetch() is the same whether I use

JavaScript

or

JavaScript

I’ve used

JavaScript

since toMariaDB.php returns text and, as I understand it, headers describes what is returned
but just in case I had misunderstood, I tried

JavaScript

as well, but that didn’t work either.

How can I format the body so that it arrives at toMariaDB.php in the same form as with jQuery? I.e.

JavaScript

Thanks for any help.

EDIT

As suggested by @T.J.Crowder, (thanks for pointing me at that) here’s what the Network tab shows as the Request Payload when running with jQuery:

JavaScript

I don’t understand why these don’t show as data[arrays][0][0], etc., but it works.
(It’s a 2D array because toMariaDB.php has to be able to process multiple arrays.)

With fetch(), the Network tab Request Payload shows:

JavaScript

Advertisement

Answer

From the documentation we can see that…

When data is an object, jQuery generates the data string from the object’s key/value pairs unless the processData option is set to false. For example, { a: "bc", d: "e,f" } is converted to the string "a=bc&d=e%2Cf". If the value is an array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below). For example, { a: [1,2] } becomes the string "a%5B%5D=1&a%5B%5D=2" with the default traditional: false setting.

(It doesn’t say so, but it does it recursively.)

Your code is sending an object with a single top-level property called data whose value is your toPostObj, which in turn has properties with string and array values. It ends up sending a POST body that looks like this:

JavaScript

…which is these parameters:

JavaScript

You can replicate that with a URLSearchParams object like this:

JavaScript

URLSearchParams will handle the URI-escaping etc. for you.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement