11486 sujets

JavaScript, DOM et API Web HTML5

Bonjour,

Je cherche à uploader une image via un form en html5 validé en ajax avec jquery.

Le code du form :

<form  id="contact_form" method="post" action="php/mail.php"  ENCTYPE="multipart/form-data">
//...
<label id="exampleFileUploadLabel" for="exampleFileUpload" class="ajouter button">Ajouter une<br />pièce jointe (1Mo max.)</label>
<input type="file" id="exampleFileUpload" name="exampleFileUpload" class="show-for-sr" size="1048576"><!--max 1048576 octets = 1 Mo-->
<input type="submit" class="envoyer button" value="Envoyer">
</form>


Le code jquery :

$( "#contact_form" ).submit(function(event) {
event.preventDefault();
var formData = new FormData();// get the form data
	formData = {
		'idDemo_form'	: $('input[name=idDemo_form]').val(),
		'societe_form'	: $('input[name=societe_form]').val(),
		'office_form'	: $('input[name=office_form]').val(),
		'nom_form'		: $('input[name=nom_form]').val(),
		'prenom_form'	: $('input[name=prenom_form]').val(),
		'fonction_form'	: $('input[name=fonction_form]').val(),
		'email_form'	: $('input[name=email_form]').val(),
		'image_nom'		: ($('input[type=file]')[0].files[0]).name,
		'image_size'	: ($('input[type=file]')[0].files[0]).size,
		'image_type'	: ($('input[type=file]')[0].files[0]).type
	};
$.ajax({
		type		: 'POST', // define the type of HTTP verb we want to use (POST for our form)
		url			: 'php/mail.php', // the url where we want to POST
		data		: formData , // our data object
		dataType	: 'json', // what type of data do we expect back from the server
		encode		: true
	})
	// using the done promise callback
	.done(function(data) {
//etc................................................


Le code php :

$errors         = array();      // array to hold validation errors
$data           = array();      // array to pass back data
//par ex pour renvoyer le nom du fichier uploadé au script js qui l'affiche dans la console
$data['errors']  =$_POST['image_nom'];
$data['success'] = false;
$data['message'] =$_POST['image_nom'];
exit;


Tout ca marche très bien sauf que ca n'envoi pas le fichier lui même.

Je ne valide jamais par ajax, et normalement je récupère le fichier dans la variable "$_FILES" en php. Bon, mais là, pas possible.

Un petit coup de main ?
Modifié par fabriceb (12 Aug 2016 - 14:22)
Ben oui, c'est assez évident: tu crées un objet FormData et juste derrière tu écrases la variable avec un autre objet. C'est donc un envoi POST normal que tu fais, sans le fichier.


Conformément à la doc sur cette page:
https://developer.mozilla.org/fr/docs/Web/API/FormData

Soit les données que tu envoies correspondent exactement au formulaire HTML; dans ce cas tu passes juste le HTMLFormElement au constructeur.
Sinon tu ajoutes chaque champ un par un avec la méthode append.
Modifié par QuentinC (12 Aug 2016 - 15:14)
oui, ca y est j'ai compris !!!!! Alléluia !!

Donc en fait :

	var form = $('form').get(0);
	var formData = new FormData(form);// get the form data
	// on envoi formData vers mail.php
	$.ajax({
		type		: 'POST', // define the type of HTTP verb we want to use (POST for our form)
		url		: 'php/mail.php', // the url where we want to POST
		data		: formData, // our data object
		dataType	: 'json', // what type of data do we expect back from the server
		processData: false,
		contentType: false
	})


et apres on récupère tout à fait normalement en php $_POST ou $_FILE ....

En fait j'avais pas tout pigé sur formData.

Merci QuentinC
Modifié par fabriceb (12 Aug 2016 - 16:11)
je cherche a faire un uploader et afficher l'image instatanement apres avoir uploader le fichier sur le serveur
Your jquery file should look like this

[Code] $(document).ready(function (e) {
$("#form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "ajaxupload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend : function()
{
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function(data)
{
if(data=='invalid')
{
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
}
else
{
// view uploaded file.
$("#preview").html(data).fadeIn();
$("#form")[0].reset();
}
},
error: function(e)
{
$("#err").html(e).fadeIn();
}
});
}));
}); [/ code]

In above code using $ajax() method for send data to php also check the success data or error in data sending.

Source: PHP file upload using ajax
Modifié par oliverusselldev (06 Aug 2018 - 15:54)