Skip to content Skip to sidebar Skip to footer

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. T

Solution 1:

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:

data%5Baction%5D=update%2Bfile&data%5Barrays%5D%5B0%5D%5B%5D=2020-12-28&data%5Barrays%5D%5B0%5D%5B%5D=23%3A20%3A56&data%5Barrays%5D%5B0%5D%5B%5D=Trying+from+ztest&data%5Barrays%5D%5B0%5D%5B%5D=9.jpg

...which is these parameters:

data[action]: update+filedata[arrays][0][]: 2020-12-28data[arrays][0][]: 23:20:56data[arrays][0][]: Tryingfromztestdata[arrays][0][]: 9.jpg

You can replicate that with a URLSearchParams object like this:

var toPostObj = new URLSearchParams();
toPostObj.append("data[action]", "update+file");
toPostObj.append("data[arrays][0][]", "2020-12-28");
toPostObj.append("data[arrays][0][]", "23:20:56");
toPostObj.append("data[arrays][0][]", "Trying from ztest");
toPostObj.append("data[arrays][0][]", "9.jpg");
fetch("foo", {
    method: "POST",
    body: toPostObj
})
// ...

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

Solution 2:

I think you'd have the best experience using this:

fetch("toMariaDB.php", { 
    method: "POST", 
    body: JSON.stringify(toPostObj),
    headers: {
        "Content-type": "application/json",
    },
}) 

And doing json_decode on the PHP side.

If you want to exactly replicate what jQuery does, you'll have to look into the network tab as it can differ... but most likely it's using application/x-www-form-urlencoded as the content type. Best way to replicate that is to populate a FormData object which is still quite a hassle when you have arrays, especially nested arrays.

Post a Comment for "How Do I Get Fetch() To Post Data The Same Way As Jquery Does?"