I just started with Ajax and also tried to find a solution for this.
Here is the problem:
I upload a .csv to a server. This works just fine. But after the upload “success” in the ajax call won’t respond. Neither does complete or error. It shows nothing. Not even an empty alert. Just nothing. I also didn’t find anything in the logs.
When I click the upload button without chosing a file to upload I get a response from success…
Here is the code:
upload.php
<?php
header('Content-type: application/json');
$target_dir = 'uploads/';
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$response[] ='';
if(move_uploaded_file($_FILES["file"]["tmp_name"],$target_file))
{
//$response['message'] = "File was uploaded!";
$response['message'] = csvToJson($target_file);
}
else
{
$response['message'] = 'Sorry, there was an error uploading your file.';
}
echo json_encode($response);
function csvToJson($file)
{
// open csv file
if (!($fp = fopen($file, 'r'))) {
die("Can't open file...");
}
//read csv headers
$key = fgetcsv($fp,"1024",";");
// parse csv rows into array
$json = array();
while ($row = fgetcsv($fp,"1024",";")) {
$json[] = array_combine($key, $row);
}
// release file handle
fclose($fp);
// encode array to json
return $json;
}
?>
upload.js
$(document).ready(function(e)
{
// Submit form data via Ajax
$("#form").on('submit', function(e)
{
var form_data = new FormData($(this)[0]);
$.ajax({
type: 'POST',
url: 'upload.php',
data: form_data,
contentType: false,
cache: false,
processData:false,
success: function(response)
{
//var json = $.parseJSON(response)
alert(response);
},
error: function(error){
console.log("Error:");
console.log(error);
},
complete: function(response){
alert(response);
}
});
});
});
the form in index.php
<form id=form enctype="multipart/form-data">
<input type="file" name="file" id="file">
<input type="submit" value="Upload Excel" name="submit">
</form>
In the end I want a json back with the content of the uploaded file. But right now there is zero output if the file is uploaded.
Thanks for any advice!