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!
brucegustPHP DeveloperAsked:
Who is Participating?
 
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
 
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
 
brucegustPHP 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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.