Skip to content
Advertisement

Sending data alongside FormData as one Object in AJAX

I’m trying to pass a FormData inside a JSON array to an AJAX script:

JavaScript

Then /bin/Admin.php

JavaScript

Which, in turn, finally goes to this (minified) class:

JavaScript

Unfortunately, it seems $_POST gets lost along the way. Adding this in my JS:

JavaScript

which shows my data correctly. I then var_dump($_POST) in bin/Admin.php which shows an empty array.

I changed 'data': formData to 'data': 'hello, world' so I have a feeling FormData doesn’t like being inside a JSON array with other elements?

So how do I send FormData with other elements to my AJAX script? I know I could use:

JavaScript

but that feels like it’s an extra step when it could just been sent as one object to my script.

I also tried using JSON.stringify on formData but again, nothing. Is there a way I can send formData alongside other data as one object without using .append()? Or is that my only option?

Advertisement

Answer

I have a feeling FormData doesn’t like being inside a JSON array with other elements?

Correct. You can’t convert FormData to JSON.

So how do I send FormData with other elements to my AJAX script?

Add the extra data to the FormData.

I know I could use:

JavaScript

Yes, do that.

but that feels like it’s an extra step when it could just been sent as one object to my script.

The FormData object is one object. You just need to add the data to it instead of adding the data to a different object and then trying to add the data from FormData to it.

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