Upload with jQuery

Asked

Viewed 248 times

0

I have this code:

$(document).ready(function(e) {
   
	$("form").on("submit", function() {

		 $.post ("upload.php", {
			 
			 fotos : $("input[type=file]")
			 
		 }, function(retorno){
           
				alert(retorno)	 
		   }
		  );

		  return false;
		
	});
	
});
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<form 
  method="post" 
  enctype="multipart/form-data" >
    <input type="file" id="imagens" name="imagens[]" multiple /> <br />
    <input type="submit" value="Enviar" />
</form>

upload.php

<?php

  print_r($_FILES);

?>

That one code has 2 problems:

To) Latch, loose and then makes Reload and does not stop at the return false

B) How to send the file field to the jQuery but with all the images selected? Note: as it is, only the information of the first image selected in the array jQuery.

1 answer

1

Solution:

  $(document).ready(function(e) {
	 
	  $("form").on("submit", function() {

		var formData = new FormData(this); 
		
		$.ajax({
			url: "upload.php",
			type: 'POST',
			data: formData,
			beforeSend: function() {			   
			},
			success: function (data) {
			},
			cache: false,
			contentType: false,
			processData: false
		});
		
		return false;
		  
	  });
	  
  });
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<form 
  method="post"
  enctype="multipart/form-data" >
    <input type="file" id="imagens" name="imagens[]" multiple /> <br />
    <input type="submit" value="Enviar" />
</form>

upload.php

  print "<pre>";
  print_r($_FILES);
  print "</pre>";  
  • I was going to reply that the $.post is for reading and not for sending :D

  • VDD. It was my mistake. But here is the orientation for someone!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.