Ajax form not working , need some help.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
gautamz07
Forum Contributor
Posts: 331
Joined: Wed May 14, 2014 12:18 pm

Ajax form not working , need some help.

Post by gautamz07 »

Hey guys i have the following html code:

Code: Select all

 <form action="mail/filesend.php" method="POST" accept-charset="utf-8" enctype="multipart/form-data" validate>
            <div class="input-wrpr">
                <input type="file" name="files[]">
            </div>
        	<button type="submit">
        		Send File
        	</button>		
 </form>
and the following PHP code:

Code: Select all

<?php 


if ($_FILES['files']) {

  $total = count($_FILES['files']['name']);
  $data = array();
  $errors = array();

  for($i = 0; $i < $total; $i++) {

    $tmpFilePath = $_FILES['files']['tmp_name'][$i];

    if ($tmpFilePath != "") {
      $newFilePath = "../uploads/" . $_FILES['files']['name'][$i];
      
      if(move_uploaded_file($tmpFilePath, $newFilePath)) {
        echo json_encode(array('success' , 'Yup Done'));
      } else {
        $errors['files'] = 'You need to upload a file';
      }
    }
  }

  $data['success'] = 'Files have been uploaded successfully';
  json_encode($data);

} else {
  
  $errors['files'] = 'You need to upload a file';
  $data['errors'] = $errors;
  json_encode($data);

}

?>
Now when i submit the form without any ajax, it all works just fine , the file gets uploaded to the specified directory and a message a echoed, but now when i add ajax to the equation , like below:

Code: Select all

$(function () {

	let files = null;
	$('input[type="file"]').on('change' , (e) => {
		files = e.target.files;
	});

	$('form').submit(function(e){
		e.stopPropagation();
		e.preventDefault();

		    let data = new FormData();

		    $.each(files, function(key, value){
		        data.append(key, value);
		    });


			$.ajax({
				type: $(this).attr('method'),
				url : $(this).attr('action'),
				data: data,
		        cache: false,
		        dataType: 'json',
		        processData: false, // Don't process the files
		        contentType: false, // Set content type to false as jQuery will tell the server its a query string request
				data : data
			}).done(function(data){
				// console.log(data);
				if (! data.success) {
					// console.log(data.errors);
					/*for(let er in data.errors) {
						console.log(data.errors[er])
					}*/
					console.log(data);
				} else {
					/* else condition fires if form submission is successful ! */
					console.log(data.file);	
				}
			}).fail(function(data){
				console.log(data);	
			});

	});
});
My code does't work i the form is not uploaded , i suspect if ($_FILES['files']) is unable to extract the file and this error gets thrown.

in my console , i get the following under response text in the ajax message:

Code: Select all

<br />↵<b>Notice</b>:  Undefined index: files in <b>C:\xampp\htdocs\parselyJS\mail\filesend.php</b> on line <b>4</b><br />↵
What am i doing wrong here ?

Thank you.
Gautam.
User avatar
gautamz07
Forum Contributor
Posts: 331
Joined: Wed May 14, 2014 12:18 pm

Re: Ajax form not working , need some help.

Post by gautamz07 »

Actually changing my JS code from:

Code: Select all

let data = new FormData();

$.each(files, function(key, value){
     data.append(key, value);
});
To:

Code: Select all

$('form').submit(function(e){
    let data = new FormData(this);
});

Made my code work ! :)
Post Reply