Upload a PHP file in Ajax using onchange

function chkFile(file1) { var file = file1.files[0]; var formData = new FormData(); formData.append('formData', file); $.ajax({ type: "POST", url: "chkFileType.php", contentType: false, processData: false, data: formData, success: function (data) { alert(data); } }); } <form action="" method="post" name="myForm" id="myForm" enctype="multipart/form-data"> <input type="hidden" name="MAX_FILE_SIZE" value="30000" /> Upload Files <input type="file" name="uploadFile" id="uploadFile" onChange="chkFile(this)"/> <input type="submit" name="submitbutt" value="Checkout"> 

chkFileType.php

 <?php print_r($_FILE) ?> 

I want to create a form that, when a user uploads a file, validates the downloaded file before submitting the entire form. I use onChange when the file loads and then passes the formData value to Ajax to call my chkFileType.php to do checks and alert the response.

The function works without errors, but the response from alert(data) ;

I know that I am doing something wrong, but I have no idea which direction to go. Am I doing the right thing?

+5
source share
1 answer

Everything looks great. You did the right thing. But in order to get any response from the ajax call, you have to print the required material in chkFileType.php .

how

 if($ext =="jpg" || $ext == "png"){ echo "Image"; // data in alert will alert as Image } else if(check for txt file){ echo "Text File"; // data in alert will alert as Text File } else if(chck for pdf) { echo "Pdf";// data in alert will alert as Pdf } 

EDIT change this

 var formData = new FormData( $("#formID")[0] ); 

I hope you understand what I wanted to say.

+2
source

Source: https://habr.com/ru/post/1235509/


All Articles