2
I’m participating in a project but I can’t upload files using ajax.
MODEL
<?php // You need to add server side validation and better error handling here
$data = array();
if(isset($_GET['files']))
{
$error = false;
$files = array();
$uploaddir = $_SERVER['DOCUMENT_ROOT'] . '/SISPESQ/Sispesq/public/uploads/arquivos/';
foreach($_FILES as $file)
{
if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
{
$files[] = $uploaddir .$file['name'];
}
else
{
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
$data = array('success' => 'Form was submitted', 'formData' => $_POST);
}
echo json_encode($data);
?>
As for the AJAX
$(function () {
var form;
$('#arquivo').change(function (event) {
form = new FormData();
form.append('arquivo', event.target.files[0]); // para apenas 1 arquivo
//var name = event.target.files[0].content.name; // para capturar o nome do arquivo com sua extenção
});
$('#btnEnviar').click(function () {
$.ajax({
url: '/SISPESQ/Sispesq/app/actions/inserirEdital.php?arquivo', // Url do lado server que vai receber o arquivo
data: form,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
if(data){
$("#alert").html(data).css({"display": "block"}).addClass('alert alert-success');
} else {
$("#alert").html(data).css({"display": "block"}).addClass('alert alert-danger');
}
},
error: function(data){
$("#alert").html(data).css({"display": "block"}).addClass('alert alert-danger');
}
});
});
});
VIEW
<label>Nome:</label>
<input type="text" id="nome" name="nome" class="form-control" placeholder="Digite aqui o nome do edital" required/>
</div>
<input type="file" id="arquivo" name="arquivo" accept="application/pdf" required/>
<p class="help-block">Selecione o arquivo .pdf</p>
<button type="submit" id="btnEnviar" class="btn btn-primary pull-right">Salvar</button>
In case it comes up error:
I don’t know why you’re doing this...
Welcome, there are several errors in your code, but that in the beginning do not affect the final result, which message appears in the reply of
success:
or oferror:
?– Guilherme Nascimento
Related, related and related Duplicate?
– Avelino
the code is wrong....
– Marcus Daniel
this is the right one... but not the right one..
– Marcus Daniel
There in the answer I put the right model code
– Marcus Daniel
is showing error:
– Marcus Daniel
@Happybr edits your question and posts the right code. Give more information about your question. Where you’re having trouble?
– Avelino
In case I don’t know why this code isn’t working... I could evaluate and see what might be causing it to fail?
– Marcus Daniel