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.
Related
I'm newby with jquery and have a problem with dealing multiple multipart forms on same page. I'm trying to add some data to mysql via php also uploading mp3 files at same time. Each form uses samename+PHPID. There is no problem with first form but im not getting file data when i use other forms. Can anyone help me?
JS:
$(".msc_send_button").click(function(e) { // changed
var a = this.id; // Button id
var form = $('#'+a).parents('form').attr('id'); // Get buttons parent form id
e.preventDefault();
var formData = new FormData($('#'+form)[0]); // Form Data
$.ajax({
url: '/formposts',
type: 'POST',
cache: false,
contentType: false,
processData: false,
data: formData,
beforeSend: function(){
// change submit button value text
$('#'+a).html('Sending...');
},
success: function(data) {
if(data) {
// Message
$('#info').html(data);
//Button Reset
$('#'+a).html('Send');
}
},
error: function(e){
alert(e);
}
});
return false;
});
PHP Form:
<form name="music-form" id="music-form<?php echo $cont['id']; ?>" enctype="multipart/form-data" novalidate>
<input type="text" name="songno" id="songno" value="<?php echo $cont['song_no']; ?>">
<input type="file" id="mp3" name="mp3" class="inputfile" accept="audio/*" multiple>
<button type="submit" class="msc_send_button" id="msc_send_button<?php echo $cont['id']; ?>">Send</button>
</form>
I think you should change your jquery selector. I didn't see your html codes but you may have created nested forms. Maybe you can use closest('from') instead of parents('form')
$(".msc_send_button").click(function(e) { // changed
var buttonEl = $(this);
var form = buttonEl.closest('form');
e.preventDefault();
var formData = new FormData(form[0]); // Form Data
$.ajax({
url: '/formposts',
type: 'POST',
cache: false,
contentType: false,
processData: false,
data: formData,
beforeSend: function(){
// change submit button value text
buttonEl.html('Sending...');
},
success: function(data) {
if(data) {
// Message
$('#info').html(data);
//Button Reset
buttonEl.html('Send');
}
},
error: function(e){
alert(e);
}
});
return 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,
....
In jQuery, when a function got success a form getting build. Now when I submit this form it gives all data except inputType='file'. I can't get it why this is happening
here is my jQuery code when form is creating
content += '<form method="POST" action="'+formURL+'" id="data" enctype="multipart/form-data">'+
'<input type="text" name="album_id" value="'+id+'">'+
'<input type="text" name="user_id" value="'+user_id+'">'+
'<input type="file" name="image" id="image_upload">'+
'<input type="submit" value="Submit">'+
'</form>';
Here form is getting submit
$("form#data").submit(function() {
var formData = new FormData($(this)[0]);
$.post($(this).attr("action"), formData, function(data) {
console.log(data);
});
return false;
});
I am sending this form data in a controller in cakephp.
In controller I get only input field data with text type only. But I need file type too.
please use jquery.form.js for file upload.
http://malsup.com/jquery/form/
<form method="POST" action="'+formURL+'" id="data" enctype="multipart/form-data" onsubmit="return submit_form();" >
function submit_form(){
$('#data').ajaxSubmit({
method:'post',
dataType:'json',
success: function(resp){
}
});
return false;
}
You can change jquery function like this
$("form#data").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: $(this).attr("action"),
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
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.
I have a file upload form:
<form class="uploadFile" name="uploadFile" method="post" action="process/uploadBuildImages.php" enctype="multipart/form-data">
<div class="uploadImageButton">Upload Image</div>
<input type="file" id="fileUpload" class="fileUpload" name="picture">
</form>
I am posting this form via ajax and formData like so:
var form = $('.uploadFile')[0];
var formData = new FormData(form);
The issue is that I have this same form output up to 4 times on the same page. I am making a CMS with blog posts and the upload image form is in each of the blog posts.
How can I target and post only from the currently posted form? I know its along the lines of using 'this.form etc but always struggle with .next / closest etc. Will look more into it soon.
If I only have one instance of this form on the page then it works fine, but otherwise I get a no file chosen error.
Thanks!
For reference, full JS:
$(document).ready(function(){
$('.uploadFile').submit(function(){
var form = $('.uploadFile')[0];
var formData = new FormData(form);
$.ajax({
type: "POST",
url: "process/uploadBuildImages.php",
data: formData,
dataType: "json",
contentType: false,
processData: false,
success: function(response){
// actions
}
}
});
}):
And there is at least 4 of the same div structures on the page which follow the same format as:
<div class="blogtest" id="'.$postID.'">
<div class="text">
<div class="postoverlay"></div>
<div class="buildtext" id="'.$postTextID.'">'.$convertedtext.'</div>
<form class="uploadFile" name="uploadFile" style="display:$showUploadForm;" method="post" action="process/uploadBuildImages.php" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="30000000" />
<div class="uploadImageButton">Upload Image</div>
<input type="file" id="fileUpload" class="fileUpload" name="picture">
</form>
<form class="updatepost" id="'.$postContentID.'" method="post">
<div class="editor">
<textarea name="muffin" id="'.$ckEID.'" class="ckeditor">'.$textFiltered.'</textarea>
</div>
</form>
</div>
</div>
Echoing the same diagnosis I have made in my comments, you lack context in your function call — your code basically submits the form data in all forms with the class .uploadFile regardless of which one is submitted:
var form = $('.uploadFile')[0]; // Problematic line
You should use $(this) to give it context upon the firing of the submit context, so that you only submit the form data from the form where the event originated from, and not all forms with the class instead. Therefore, you substitute:
var form = $('uploadFile')[0];
with:
// Alternative 1
var form = $(this)[0];
// Alternative 2
var form = this;
In other words:
$(document).ready(function(){
$('.uploadFile').submit(function(){
var form = this; // Fixed line
var formData = new FormData(form);
$.ajax({
type: "POST",
url: "process/uploadBuildImages.php",
data: formData,
dataType: "json",
contentType: false,
processData: false,
success: function(response){
// actions
}
}
});
});
You can learn more what $(this) does in jQuery here and here.