Skip to content
Advertisement

How to pass an image file thru jquery $.ajax() correctly?

I am trying to upload an image and passing the userID and file through ajax to the PHP file profileSettings.inc.php. However it succeed in running the php file, but the data was not passed through. When I ran print_r($_POST);, in the php file it returned an empty array.

JavaScript

Form:

JavaScript

profileSettings.inc.php:

JavaScript

?>

Anyone knows what I am doing wrong in passing the data through ajax. Thanks in advance!

UPDATED: As suggested to use FormData, I updated the javascript code as followed:

JavaScript

Feb 03 2021 UPDATE: When using formData, $_FILES['file'] doesn’t exist, but $_POST['file'] does and [file] is undefined. How do I pass the file so I can grab the data using $_FILES['file'] in php server side?

Advertisement

Answer

just use data : new FormData(this) and it will automatically pass all the values alongside $_POST and $_FILES

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