I'm totally noob in jQuery and become desperate to get it to work.
This is the html:
<form method="post" enctype="multipart/form-data">
<input id="pic "type="file" name="file" onchange="javascript:this.form.submit();">
</form>
jQuery:
$("#pic").change(function() {
var file_data = $('#pic').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data)
alert(form_data);
$.ajax({
url: 'doupload.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(dat){
alert('it works maybe');
}
});
});
So I just want to send the file to doupload.php and catch it there with ($_FILES['file']['tmp_name'])
But it's not working (ofc) and I don't find anything which is working either google nor stack...
I use this lilbary: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
<input id="pic "type="file" name="file" onchange="javascript:this.form.submit();">
You have "type="file"
Change it to type="file"
Also, if you have the ajax sending on change via "$("#pic").change(function() { then you SHOULD NOT have onchange="javascript:this.form.submit();" as well, as it will submit the form while the ajax is still sending, causing possible timing issues (such as the ajax call not completing)
As far as I can tell, you should not have a submit event at all, as the data is already submitted via an ajax call.
Related
For past few days i have been struggling to submit a form with jQuery and AJAX. The problem i'm facing is to upload the image in the form field.
My form is something like this:
<form action="#" method="GET" role="form" enctype="multipart/form-data">
<input type="text" placeholder="Name" name="name">
<input type="file" name="img" multiple>
<button type="submit">Submit </button>
</form>
and my jQuery script for getting the form value is something like this:
$("form").submit(function (event) {
$.dataArray = $(this).serializeArray(); // array of form data
console.log($.dataArray);
event.preventDefault();
});
But this returns all the field values except image one, in case of image is return null.
How do I store in the dataarray?
I want to store so I can send the value to the server through the AJAX.
For uploading single image its like this
<html>
<head>
<meta charset="UTF-8">
<title>AJAX image upload with, jQuery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
$('#upload').on('click', function () {
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'http://localhost/ci/index.php/welcome/upload', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the server
},
error: function (response) {
$('#msg').html(response); // display error response from the server
}
});
});
});
</script>
</head>
<body>
<p id="msg"></p>
<input type="file" id="file" name="file" multiple />
<button id="upload">Upload</button>
</body>
</html>
For multiple images u will have to loop its kinda different
I have found a similar question, hope it will help you.
Upload image using jquery
Another option to consider is to use some sort of jQuery plugin to upload images like Cloudinary and include it in your HTML pages :
<script src='jquery.min.js' type='text/javascript'></script>
<script src='jquery.cloudinary.js' type='text/javascript'></script>
and then include all required jQuery files:
<script src='jquery.min.js' type='text/javascript'></script>
<script src='jquery.ui.widget.js' type='text/javascript'></script>
<script src='jquery.iframe-transport.js' type='text/javascript'></script>
<script src='jquery.fileupload.js' type='text/javascript'></script>
<script src='jquery.cloudinary.js' type='text/javascript'></script>
try this code, it's work for me.
$("form").submit(function (event) {
var form_data = new FormData($(this));
$.ajax({
url : url,
type : 'POST',
data : form_data,
processData: false, // tell jQuery not to process the data
contentType: false,
success : function(resp){
}
});
});
Try this code. using formData()
$("form").submit(function (event) {
var formData = new FormData($(this));
$.ajax({
url: url,
type: 'POST',
data: formData,
async: false,
success: function (data) {
//success callback
},
cache: false,
contentType: false,
processData: false
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="GET" role="form" enctype="multipart/form-data">
<input type="text" placeholder="Name" name="name">
<input type="file" name="img" multiple>
<button type="submit">Submit </button>
</form>
serialize() method not able to post file data.
For sending file using ajax use FormData instead of serializing
HTML5 introduces FormData to allow developers to build forms objects dynamically, and then to send this form object via AJAX.
your Html
<form action="upload_image.php" id="form_img" method="GET" role="form" enctype="multipart/form-data">
<input type="text" placeholder="Name" name="name">
<input type="file" name="img" multiple>
<button type="submit">Submit </button>
</form>
AJAX call
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#form_img").submit(function(e){
e.preventDefault();
var formData = new FormData($("#form_img")[0]);
$.ajax({
url : $("#form_img").attr('action'),
type : 'POST',
data : formData,
contentType : false,
processData : false,
success: function(resp) {
console.log(resp);
}
});
});
});
</script>
upload_image.php
print_r($_FILES) //check you get file data or not
Try this way.Hope it will help you
Please check the follow the code, which i am using to upload image.
$.ajax({
url: UPLOADURL, // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this),// Data sent to server, a set of key/value pairs representing form fields and values
contentType: false,// The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
cache: false,// To unable request pages to be cached
processData:false,// To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
success: function(data)// A function to be called if request succeeds
{
data = JSON.parse(data);
console.log(data);
if(data.status == "Success"){
attachmentListing();
//$("#mailerMessage").html(data.data.mailStatus);
//$("#mailerMessage").fadeIn();
setTimeout(function () {
$("#mailerMessage").fadeOut();
},5000);
}else{
toastr.warning(data.status);
}
$("#ajaxloader").addClass("hideajaxLoader");
},
error: function (jqXHR, errdata, errorThrown) {
log("error");
$("#ajaxloader").addClass("hideajaxLoader");
}
});
I have multiple forms to send data to a database. One is created inside a loop and one is outside the loop. I have used AJAX to send that data to the database.
In the form who outside the loop, the AJAX works correctly and sends data to the database without refreshing the page. However in the forms inside the loop I can only send the data once. The second time the page is refreshed.
This is the first form outside the loop:
<!-- main from for post data out the loop -->
<form id="PostFormData" method="post" enctype="multipart/form-data">
<input type="file" name="image[]">
<input type="text" name="Post">
<button>done</button>
</form>
This is the AJAX code for this form
$("form#PostFormdata").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: 'Post/sendPost.php',
type: 'POST',
data: formData,
success: function(data) {
document.getElementById("ajaxPost").innerHTML = data;
},
cache: false,
contentType: false,
processData: false
});
});
This is the second form inside the loop
<!-- form inside the loop for comment data -->
<?php for ($i = 0; $i < 1000; $i++) { ?>
<form id="CommentFormData" method="post" enctype="multipart/form-data">
<input type="file" name="commentImage">
<input type="text" name="commentValue">
<button>done</button>
</form>
<?php } ?>
This is the AJAX code for the looped forms
$("form#CommentFormData").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: 'Post/sendComment.php',
type: 'POST',
data: formData,
success: function(data) {
document.getElementById("InsidePost").innerHTML = data;
},
cache: false,
contentType: false,
processData: false
});
});
The issue with the forms you generate in the loop is that they all have the same id. This value must be unique. As such the event handler is only bound to the first one and all others do not use the AJAX logic you provide.
To fix this, use a common class on all the forms - including the form outside of your PHP loop. That way all forms in the page will use the same handler and your JS will be more succinct. Try this:
$("form.comment-form-data").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: 'Post/sendComment.php',
type: 'POST',
data: formData,
success: function(data) {
$("#InsidePost").html(data);
},
cache: false,
contentType: false,
processData: false
});
});
<!-- form inside the loop for comment data -->
<?php for ($i = 0; $i < 1000; $i++) { ?>
<form class="comment-form-data" method="post" enctype="multipart/form-data">
<input type="file" name="commentImage">
<input type="text" name="commentValue">
<button>done</button>
</form>
<?php } ?>
Also, as an aside, I assume that you're only adding 1000 form elements to the DOM for testing, as that is really not something you should be doing, at all.
I have studied a lot of answers in stackOverflow but haven't figured out the simplest way of uploading an image from a form. I am trying to figure out a way to upload an image using Ajax. Although the form, PHP and Ajax coding is huge, I am giving you the important parts. When I click the submit button, error message is shown, viz undefined index.
HTML
<form method="post" enctype="multipart/form-data">
<tr>
<th>Image</th>
<td><input type="file" name="image" id="img"></td>
</tr>
</form>
Ajax
$(document).on('click','#sub_prod',function(event){
event.preventDefault();
$.ajax({
url:"product_add_back.php",
method:"post",
data:$('form').serialize(),
dataType:"html",
success:function(strMsg){
$("#prod_add").html(strMsg).show().fadeOut(3000);
}
})
})
PHP
$image_name=$_FILES["image"]["name"];
echo $image_name;
die();
$().serialize() will not include $_FILES content, so you need to use FormData object
$(document).on('click','#sub_prod',function(event){
event.preventDefault();
var formdata = new FormData($('form')[0]);
$.ajax({
url: "product_add_back.php",
method: "post",
data: formData,
processData: false,
contentType: false,
success: function(strMsg){}
});
});
Please note that you pass 3 params: data: formData, processData: false and contentType: false
I am attempting to create an upload document which will upload a profile picture. I am having trouble capturing the data from the changePicture form which only has an input for the images and a submit. I have never used the FormData object to date, so I am still learning around this. Any guidance would be useful.
See my HTML
<form id="changePicture" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="name">Update Your Profile Picture</label>
<input type="file" id="profilePic" class="form-control" name="profilePic">
<input type="hidden" value="<?php echo $id; ?>" name="id">
</div>
<button type="submit" id="updateProfileBtn" class="btn btn-success float-right">Upload Image</button>
</form>
Here is my AJAX code:
function updateProfilePic(){
$("#changePicture").on("submit", function(e) {
e.preventDefault();
$("#spinner").show();
setTimeout(function(){
$.ajax({
url: "../ajax/admin/updateProfilePic.php",
type: "POST",
data: new FormData(this),
cache: false,
contentType: false,
processData: false,
success: function(result){
$("#spinner").hide();
$("#changePicture").append(result);
setTimeout(function(){
$("#changePicture").slideDown();
}, 1500);
}
});
}, 3000);
});
}
The PHP file at this moment only echos out "Working" to see it accesses the page alright, which it does. However, when I attempt to locate the file through a variable nothing has been sent and returns undefined index.
this will be undefined because it's inside ajax's scope
Try:
me = this;
$.ajax({
url: "../ajax/admin/updateProfilePic.php",
type: "POST",
data: new FormData(me),
...
As, for me, when using ajax I always prefer to base64encode the image and pass it as a JSON to PHP but i guess that's a personal preference...
Why are you wrapping your AJAX call in a
setTimeout(function() {..})
?
By doing this, you cannot simply write new FormData(this), because the this context does not refer to the form that you are looking for.
Try executing the code without the timeout, or try storing the form data in a global variable
Edit: Example added:
var myFormData;
function updateProfilePic(){
$("#changePicture").on("submit", function(e) {
e.preventDefault();
$("#spinner").show();
myFormData = new FormData(this);
setTimeout(function(){
$.ajax({
url: "../ajax/admin/updateProfilePic.php",
type: "POST",
data: myFormData,
....
I have no idea how to implement this, let me try to explain
I have a form that open inside a bootstrap modal frame in my layout, in this form i have 2 fields
<input type="file" name="photoimg" id="photoimg" value="" />
<input type="hidden" name="consulta" value="5">
I need to submit this to my url with the value 5 for 'consulta' so the script can read and do the proper things with the file,
BUT
I need to do this without refreshing the opened modal, in other words, using ajax to submit the file (for further cropping)
i have this script that do the submit, what i'm doing wrong here?
<script type="text/javascript">
function enviaimagem(){
$.ajax({
type: "POST",
data: { consulta:5 },
dataType: 'html',
url: "<?=JURI::ROOT()?>ajax.html",
//dataType: "html",
success: function(result){
$("#corpo_modal").html('');
$("#corpo_modal").html(result);
},
beforeSend: function(){
$("#corpo_modal").html('');
$("#corpo_modal").css({display:"none"});
$('#ajaxloadergeneric').css({display:"block"});
},
complete: function(msg){
$('#ajaxloadergeneric').css({display:"none"});
$("#corpo_modal").css({display:"block"});
}
});
}
</script>
File upload through AJAX is supported through FormData object:
https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects
, however it is not supported by all/old browsers( especially IE < 10)