This question already has answers here:
jQuery Ajax File Upload
(27 answers)
Closed 9 years ago.
I've a question about file uploading with Ajax. How to submit file with $.ajax()
without a special js-plugin?:
<form action="javascript:return false;">
<input type="text" id="name" />
<input type="file" id="myfile" />
<input type="button" id="submitbutton" value="submit" />
</form>
This is a jQuery small code:
<script type="text/javascript">
$(document).ready(function() {
$('#submitbutton').click(function() {
$.ajax({
type: 'POST',
dataType: 'json',
enctype: 'multipart/form-data',
url: 'upload.php',
async: false,
data: {
'name': $('#name').val(),
'myfile': $('#myfile').val()
},
success: function(data) {
alert(data.msg);
}
});
});
});
</script>
And upload.php file:
<?php
$name = isset($_POST['name']) ? $_POST['name'] : '';
if (isset($_FILES) && isset($_FILES["file"])) {
$files = $_FILES['file'];
$error = isset($files["error"]) ? $files["error"] : '';
$fname = isset($files["name"]) ? $files["name"] : '';
$type = isset($files["type"]) ? $files["type"] : '';
$size = isset($files["size"]) ? $files["size"] : '';
$tmp_name = isset($files["tmp_name"]) ? $files["tmp_name"] : '';
return array('msg' => "Hello, $name! \nYour file data:\nErr: $error, Name: $fname, Type: $type, Size: $size, Tmp: $tmp_name");
}
echo json_encode(array('msg' => 'create image'));
?>
Other option is using iframe, this is a tutorial for doing this;
Files cannot be uploaded via ajax. You may want to checkout the Form Plugin which does support file uploads: http://jquery.malsup.com/form/
If you expect to get this working cross browser, than you can't do that with AJAX only. (But it is ok for you that this will work not in all browsers, you may take a look how to upload files with XMLHttpRequest and jquery here)
As for me, the best would be to use jQuery Forms plugin.
Another option is to do the same thing that plugin does manually.
It will be something like below:
var ifrm = $("<iframe>", {id:"tmp_upload_frame"}).onload(function() {
// do something when response is returned
}).hide();
$("body").append(ifrm);
$("form").prop("target", "tmp_upload_frame")
.prop("enctype","multipart/form-data")
.submit();
But as for me, Forms plugin is much better as it has an interface very similar to ajax interface and does a lot of dirty work for you (like retrieving response from iframe) for you.
Related
I know that it may be so tricky!
In detail:
on the blog detailing page(blog-single.php/title) I have a subscription form this subscription form is working fine on another page with the same PHP action file and ajax
and blog-single.php/title is also working fine until I did not submit the form
On this page in the starting, I have bellow query
<?php
$query_head="SELECT * FROM blog_post WHERE friendly_url = '{$_GET['url']}' ";
$result_head= $fetchPostData->runBaseQuery($query_head);
foreach ($result_head as $k0 => $v0)
{
//----- some echo
}
?>
and my subscription form code:
<form action="" method="post" class="subscribe_frm" id="subscribe_frm2">
<input type="email" placeholder="Enter email here" name="email" id="subscribe_eml2">
<button type="button" id="subscribe2">Subscribe</button>
</form>
and ajax code is bellow:
$(document).ready(function() {
$("#subscribe2").click( function() {
subscribe_frm_val2 = false;
/*email validation*/
var emailReg2 = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if ($("#subscribe_eml2").val().length <= 0) {
$("#subscribe_eml_Err2").html("Required field");
//console.log("Required");
subscribe_frm_val2 = false;
}
else if(!emailReg2.test($("#subscribe_eml2").val()))
{
$("#subscribe_eml_Err2").html("Enter a valid email");
}
else{
$("#subscribe_eml2").html("");
subscribe_frm_val2 = true;
//console.log("final else");
if(subscribe_frm_val2 == true)
{
console.log("frm true");
var form = $('#subscribe_frm2')[0];
var data = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "updation/subscribe_action.php",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 6000000,
beforeSend: function(){
// Show image container
$("#submition_loader").show();
//alert ("yyy");
},
success: function (data) {
// console.log();
$(document).ajaxStop(function(){
$("#subscribe_eml_Err2").html(data);
});
},
complete:function(data){
// Hide image container
$("#submition_loader").hide();
}
});
}
else{
alert('Please fill all required field !');
}
}
});
});
When I submit my form above the first query is giving a warning like below:
Warning: Invalid argument supplied for foreach() in D:\xamp\htdocs\my\bootstrapfriendly\category.PHP on line 13
and after warning page doing misbehave
I think the error because of URL passing but I am not sure how to solve it
Please help me with solving it.
Thank's
I got the solution
its very simple just converted my relative URL into an absolute URL
I just created a PHP function for base URL
function base_url(){
if(isset($_SERVER['HTTPS'])){
$protocol = ($_SERVER['HTTPS'] != "off") ? "https" : "http";
}
else{
$protocol = 'http';
}
return $protocol . "://" . $_SERVER['HTTP_HOST'];
}
and then using this base URL function inside script like this
$.ajax({
----
url: "<?php echo base_url()?>/updation/subscribe_action.php",
-----
});
I have a form that had a file type input to upload images, but it would always show up the "notice: undefined index" and I saw that the $_FILE was coming empty, but none of the answers that I found online have helped me.
I have a project where after the user registers he has to login and his first page he confirms his data and insert some new ones, one of this new ones is a picture that he can upload, as I said, my initial problem was that the $_FILES was always coming up empty, I searched online and this is a fairly common error but none of the answers have helped me, after a lot of trying I found out what the problem is, but I still have no Idea why, or how to fix it.
At the start of the page that I talked about there's this bit off code here:
if(isset($_SESSION['logado'])){
$dados = $_SESSION['dadosUsu'];
}else{
unset($_SESSION['dadosUsu']);
session_destroy();
header("Location: homeLandingPage.php");
}
to stop unnauthorized people into the page or create a variable with the user data so that it can be used to fill out some of the inputs with the info that the user had already registered.
I found that if I removed this bit off code, the $_FILES global started working and the code runned fine, but if the code was there the problems continued, I have no ideia why this is happening and I couldn't find anything online that talk about a session conflicting with the $_FILES global.
after that there's this bit of ajax:
$(function(){
$('.form').submit(function(){
$.ajax({
url: 'cod_alterarAcc.php',
type: 'POST',
data: $('.form').serialize(),
success: function(data){
if(data != ''){
$('.recebeDados').html(data);
document.getElementById('visor1').value = '<?= $dados['nomeUsu']; ?>';
document.getElementById('visor2').value = '<?= $dados['emailUsu']; ?>';
document.getElementById('visor3').value = '<?= $dados['emailUsu']; ?>';
document.getElementById('visor4').value = '';
document.getElementById('visor5').value = '';
document.getElementById('visor6').value = '';
}
}
});
return false;
});
});
I don't know if it's this but here it's the preview function that is called onChange on the input type file:
function previewImagem() {
var imagem = document.querySelector('input[name=img]').files[0];
var preview = document.querySelector('img[id=dup]');
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (imagem) {
reader.readAsDataURL(imagem);
} else {
preview.src = "";
}
}
here is the form that Im using:
<form enctype="multipart/form-data" class='form' method='post' action='cod_alterarAcc.php'>
<div id="img-perfil">
<img src="imagens/perfil.png" id="dup"/>
<label for="selecao-arquivo" class="selecionar-img">+</label>
<input id="selecao-arquivo" type="file" name="img" class="botao-img" onchange="previewImagem()" />
</div>
<label>Confirme seu nome:</label>
<input type="text" id="visor1" name="nome_usu" value="<?= $dados['nomeUsu']; ?>" />
<label>Altere seu email:</label>
<input type="email" id="visor2" name="email" value="<?= $dados['emailUsu']; ?>" />
<label>Confirme seu email:</label>
<input type="email" id="visor3" name="confirmaEmail" value="<?= $dados['emailUsu']; ?>" />
<label>Sua senha:</label>
<input type="password" id="visor4" name="senha" />
<label>Confirme sua senha:</label>
<input type="password" id="visor5" name="confirmaSenha" />
<label>Insira seu cpf:</label>
<input type="text" id="visor6" name="cpf_usu" />
<div class='recebeDados'></div>
<input type="submit" value="confirmar" />
</form>
on the cod_alterarAcc.php page has some validations using filter_input_array() and then I have this:
$extensao = strtolower(substr($_FILES['img']['name'], -4));
$novo_nome = sha1(time()) . $extensao;
$diretorio = "imgsBanco/";
$ext = strtolower(substr($_FILES['img']['name'], -3));
$tipos = array("png","jpg","gif");
$imagem = $diretorio.$novo_nome;
I have some more validation regarding the other inputs and then this, it's the first time that I use the session in this page:
if (in_array($ext, $tipos)) {
if (move_uploaded_file($_FILES['img']['tmp_name'], $imagem)) {
$codAcesso = $_SESSION['dadosUsu']['codAcesso'];
$codUsu = $_SESSION['dadosUsu']['codUsu'];
$senhaEncript = Bcrypt::hash($infoPost['senha']);
after that I do an update on everything in the database, including the image url which is the $imagem variable, after that I only look at the session one more time to send the user to another page depending on it's user type.
I've also tested for most of the possibilities in here Why would $_FILES be empty when uploading files to PHP? and it didn't worked
Like I said, apparently the only thing that it's messing with the $_FILES it's that part where I use the session on the first page, if someone could help me fix this problem and explain why it's happening in the first place I would appreciate it a lot.
It seems that the default action of the form is conflicting with your AJAX, but if you want to use only AJAX in uploading your file then you want to prevent the default action of the form. Your AJAX request should be look like this.
$('.form').submit(function(e){
e.preventDefault(); // Preventing the default action of the form
var formData = new FormData(this); // So you don't need call serialize()
$.ajax({
url: 'cod_alterarAcc.php',
type: 'POST',
data: formData,
success: function (data) {
if(data != ''){
$('.recebeDados').html(data);
document.getElementById('visor1').value = '<?= $dados['nomeUsu']; ?>';
document.getElementById('visor2').value = '<?= $dados['emailUsu']; ?>';
document.getElementById('visor3').value = '<?= $dados['emailUsu']; ?>';
document.getElementById('visor4').value = '';
document.getElementById('visor5').value = '';
document.getElementById('visor6').value = '';
}
},
cache: false,
contentType: false,
processData: false
});
});
also put your form into FormData and specify your ajax request type.
EDIT
Try to confirm if PHP able to get the data with
print_r($_POST);
print_r($_FILES);
And in your AJAX success function
console.log(data);
EDIT
Forgot to put the parameter e on form.submit
I was wondering if i could get a bit of advice.
Im trying to upload a file using jquery while keeping the user on the same page.
Whatever i try isnt working. I was wondering if someone could have a look and tell me where im going wrong.
My HTML is
<form id="import" enctype="multipart/form-data" action="/ajax/postimport" method="POST">
<div class="form-group">
<input type="file" name="filename" id="filename" />
</div>
<button type="button" id="importSave">Import</button>
</form>
This is my jquery
$("#importSave").click(function()
{
$.ajax({
url: '/ajax/postimport',
type: 'POST',
dataType: 'json',
contentType: false,
processData: false,
data: {file: $(#filename).val()},
success: function(data)
{
alert(data.result)
},
error: function(textStatus, errorThrown)
{
}
});
});
and then my PHP, which is Laravel 4
if (Input::hasFile('filename')) {
$file = Input::file('filename');
$destPath = public_path() . '/uploads/';
$filename = str_random(10) . '_' . $file->getClientOriginalName();
$uploadSuccess = $file->move($destPath, $filename);
}
It is not possible to upload files by just using the jQuery ajax function. You will need to use a FormData object to do this. The problem with Formdata is that it is not supported in all browsers. If you do want to use it, you can always find plenty tutorials like this one.
You can also use a jQuery plugin that does the work for you. :)
It is not possible to do like this. you are just making post ajax request with only one field file: $(#filename).val().
So you need to use ajax upload library like.
There are several alternatives. But I like most are
http://www.plupload.com/
http://www.uploadify.com/
This question already has answers here:
How can I upload files asynchronously with jQuery?
(34 answers)
Closed 9 years ago.
i have made a form that will be send a input type file, in my server side i want to get $_FILES value so i used print_r($_FILES), but in my ajax response i don't get anything value, here my code..
<form id="my_form">
<input type="file" id="image_file" name="image_file"/>
</form>
$('#my_form').submit(function() {
var data = $('#my_form').serialize();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: data,
enctype: 'multipart/form-data',
success: function(response) {
alert(response);
},
});
return false;
});
and here my php code
<?php
$name = $_FILES['image_file']['name']; // get the name of the file
$type = $_FILES['image_file']['type']; // get the type of the file
$size = $_FILES['image_file']['size'];
echo $name;
//or
print_r($_FILES);
?>
please help me ...
thanks..
AjaxFileUpload
Maybe this plugin could help you fix the problem.
The way of this plugin doing is just like the way people did before ajax theory proposed which is using an iframe tag handle all the request without refreshing the page.
Without HTML5,I don't think we can use XMLHttpRequest to upload file.
First of all I'd like to ask that you don't suggest I turn to a jQuery plugin to solve my issue. I'm just not willing to make my app work with a plugin (and it prevents me from learning!)
I have a form with a bunch of fields that I'm passing to my backend via the use of jQuery's $.post() This is what I have as my jQuery function:
$.post(
"/item/edit",
$("#form").serialize(),
function(responseJSON) {
console.log(responseJSON);
},
"html"
);
This is how I opened my form:
<form action="http://localhost/item/edit" method="post" accept-charset="utf-8" class="form-horizontal" enctype="multipart/form-data">
This was auto generated by codeigniter's form_open() method (hence why action="" has a value. Though this shouldn't matter because I don't have a submit button at the end of the form)
Within my #form I have this as my file input: <input type="file" name="pImage" />
When the appropriate button is hit and the $.post() method is called, I have my backend just print the variables like so: print_r($_POST) and within the printed variables the 'pImage' element is missing. I thought that maybe files wouldn't come up as an element in the array so I went ahead and just tried to upload the file using this codeigniter function: $this->upload->do_upload('pImage'); and I get an error: "You did not select a file to upload."
Any idea as to how I can overcome this problem?
You cannot post an image using AJAX, i had to find out here as well PHP jQuery .ajax() file upload server side understanding
Your best bet is to mimic an ajax call using a hidden iframe, the form has to have enctype set to multipart/formdata
Files wont be sent to server side using AJAX
One of the best and simplest JQuery Ajax uploaders from PHP LETTER
all you need is include js in your header normally and Jquery code will be like below
$.ajaxFileUpload({
url:'http://localhost/speedncruise/index.php/snc/upload/do_upload',
secureuri:false,
fileElementId:'file_upload',
dataType: 'json',
data : {
'user_email' : $('#email').val()
},
success: function (data, status) {
// alert(status);
// $('#avatar_img').attr('src','data');
}
,
error: function (data, status, e) {
console.log(e);
}
});
wish this can help you
I can't do this with codeigniter and Ajax, I pass the image to base64 and in the controller I convert into a file again
//the input file type
<input id="imagen" name="imagen" class="tooltip" type="file" value="<?php if(isset($imagen)) echo $imagen; ?>">
//the js
$(document).on('change', '#imagen', function(event) {
readImage(this);
});
function readImage(input) {
var resultado='';
if ( input.files && input.files[0] ) {
var FR= new FileReader();
FR.onload = function(e) {
//console.log(e.target.result);
subirImagen(e.target.result);
};
FR.readAsDataURL( input.files[0] );
}
}
function subirImagen(base64){
console.log('inicia subir imagen');
$.ajax({
url: 'controller/sube_imagen',
type: 'POST',
data: {
imagen: base64,
}
})
.done(function(d) {
console.log(d);
})
.fail(function(f) {
console.log(f);
})
.always(function(a) {
console.log("complete");
});
}
//and the part of de controller
public function sube_imagen(){
$imagen=$this->input->post('imagen');
list($extension,$imagen)=explode(';',$imagen);
list(,$extension)=explode('/', $extension);
list(,$imagen)=explode(',', $imagen);
$imagen = base64_decode($imagen);
$archivo='archivo.'.$extension;
file_put_contents('imagenes/'.$archivo, $imagen);
chmod('imagenes/'.$archivo, 0777); //I use Linux and the permissions are another theme
echo $archivo; //or you can make another thing
}
ps.: sorry for my english n_nU