How can I process a multipart form using AJAX?

So, here's my script:

<script>
$('#submit').click(function(event) {
		event.preventDefault();
		
		//if it returns a false, you'll get your error message. If it returns "true," you can then proceed to the rest of your form submission process
		var out = {
		'empID' : $('#empID').val(), 
		'cpID' : $('#cpID').val(), 
		'empName' : $('#empName').val(), 
		'custom_header' : $('#custom_header').val(), 
		'bodyTopColor' : $('#bodyTopColor').val(), 
		'bodyBottomColor' : $('#bodyBottomColor').val(), 
		'spanish_alert_yes' : $('#spanish_alert_yes').val()
		};
		
		$.post('employer_insert_execute.php?stage=phase_one', out, function(data)
		{
			$('.spanish_answer').show();
			$('#spanish_answer_cell').html(data);
		});

	});
</script>

Open in new window


Everything works right up to the point where I'm trying to upload an image file. Here's the way my code looks after successfully inserting a new record:

if($statement->execute())
			{
				
				$last_id = $conn->lastInsertId();
				//return id of record just inserted
				//upload logo and update record
				echo $_FILES['custom_header'];
				
				echo basename($_FILES[$parameters['custom_header']]);
				
				$target = "../Photos/"; 
				$target = $target . basename( $_FILES['custom_header']['name']) ;
				$url = basename($_FILES['custom_header']['name']); 
								 
				if(!move_uploaded_file($_FILES['custom_header']['tmp_name'], $target))
				{				
					return("photo didn't upload");
				}
				else 
				{
				$sql=$conn->prepare("update employers set header_graphic=:url where id=:id");
				$sql->bindParam(':url', $url, PDO::PARAM_STR);
				$sql->bindParam(':id', $last_id, PDO::PARAM_INT);
				
				if($sql->execute())
					{
						return("success");
					}
				}
			}
			else
			{
				return ("fail");
			}

Open in new window


I'm getting as far as "echo $_FILES['custom_header'] and it's apparent that the data that should be there - is not.

Based on what I've found at http://portfolio.planetjon.ca/2014/01/26/submit-file-input-via-ajax-jquery-easy-way/ as well as https://www.mattlunn.me.uk/blog/2012/05/sending-formdata-with-jquery-ajax/, it would seem that AJAX is going to process everything in the same way. So, when you get to a FILE, it struggles.

Here (apparently) is where you're going to use the formData object. Thing is, I don't know what that does or how to implement it.

In plain language, it sounds as thought JQuery is going to serialize incoming form data by default according to a certain way. Hence, when you're trying to upload image files, that $_FILE isn't going to work.

But what does formData do and how do I implement it here:

$('#submit').click(function(event) {
		event.preventDefault();
		
		//if it returns a false, you'll get your error message. If it returns "true," you can then proceed to the rest of your form submission process
		var out = {
		'empID' : $('#empID').val(), 
		'cpID' : $('#cpID').val(), 
		'empName' : $('#empName').val(), 
		'custom_header' : $('#custom_header').val(), 
		'bodyTopColor' : $('#bodyTopColor').val(), 
		'bodyBottomColor' : $('#bodyBottomColor').val(), 
		'spanish_alert_yes' : $('#spanish_alert_yes').val()
		};
		
		$.post('employer_insert_execute.php?stage=phase_one', out, function(data)
		{
			$('.spanish_answer').show();
			$('#spanish_answer_cell').html(data);
		});

	});
</script>

Open in new window


Thanks!
Bruce GustPHP DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
Uploading files with AJAX requires the use of FormData

You can read more about how to use it to upload files here

https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

Give that a go and then post back with how far you got.
0
Slick812Commented:
greetings brucegust , , uploading files in AJAX is a whole different hassle, than just ajaxing up Text segments. As you have seen the usual Ajax for text does not work for any file. The upload a file with "FormData" is a newer method, and as far as I know (not very far) it still may not be supported in a few browsers, especially older versions. You seem to be using the Jquery thing, if so you may look at this page -
     https://www.formget.com/ajax-image-upload-php/

even with a copy and paste code you may have to try several times and change things (DEBUG), Since (to me) this can have more places to not make correct entries in the example code template.
Also as far as I have tried, I could not do a combined TEXT and FILE upload in the same AJAX, so I needed to do separate AJAX calls, one for TEXT and one for FILE. There seem to be some JQuery plug in for AJAX file upload, be be warned, many of these are real old, using old versions of Jquery, AllI can say is Good Luck on this one
0
Slick812Commented:
So Sorry, my memory is flop, I said this -
      "Also as far as I have tried, I could not do a combined TEXT and FILE upload in the same AJAX"

BUT in a memory bump, I looked at a file, and I was remembering an unusual special case problem with a file and text components, and that is not the case here. The  formData can up to server all that's in a <form> and even load separate data parts, and the jquery (if you do all of a <form> elements at once) is not to tough.
0
Julian HansenCommented:
Formdata is supported back to IE10 and all other browsers (https://developer.mozilla.org/en-US/docs/Web/API/FormData)

There are several good AJAX uploaders that are not based on older code DropZone (http://www.dropzonejs.com/) being a popular one.

With FormData it IS possible to submit both file and text data.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Bruce GustPHP DeveloperAuthor Commented:
Thank you, gentlemen!

I re-evaluated the flow of what I'm trying to get done and a conventional posting of the form content is going to work, so the AJAX dynamic is not going to be necessary at this point after all.

However...

Chances are good I will the FormData approach in the not too distant future, so thanks for pointing me in the right direction.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
jQuery

From novice to tech pro — start learning today.