I am attempting to upload a file to a server from a bootstrap modal window, using ajax.
The modal html is
<div class="modal-body">
<div>
<form class="form" role="form" id="attachform" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<button type="submit" class="btn btn-primary">Upload</button>
</form>
</div>
</div>
The Javascript
$("#attachform").on('submit',function(event){
event.preventDefault();
var postData = new FormData($("#attachform")[0]);
console.log(postData);
$.ajax({
url: "attachment.php",
type: "POST",
data: data,
processData: false, // tell jQuery not to process the data
contentType: false
}).done(function(msg) {
console.log(msg);
$('#myAttachModal').modal('hide');
});
});
});
The PHP server code
print_r($_POST);
print_r($_FILES);
I am not seeing anything in the $_FILES array when I run this.
Any suggestions?
Change the data value in your Ajax post to postData. postData contains the form data.
Change this section
data: data,
To
data: postData,//this contains the form data
You just need to change the data : data kew value inside the
$.ajax({
data : postData,
});
$.ajax({
url: "attachment.php",
type: "POST",
data: postData,
processData: false, // tell jQuery not to process the data
contentType: false
}).done(function(msg) {
console.log(msg);
$('#myAttachModal').modal('hide');
});
});
});
Related
I need to pass two different datas using ajax.
I've got this:
$('#sendcover').on('click',function(){
$.ajax({
type: "POST",
url: "{{ url('articles_changecover') }}",
data: new FormData($('#test')[0]),
processData: false,
contentType: false,
success: function (data) {
alert(data);
}
});
});
<form name="test" id="test" method="post" enctype="multipart/form-data">
<input type="text" value="{{article.id}}" name="id" />
<input type="file" name="cover">
<button id="sendcover" type="submit" class="saveData">Save</button>
</form>
I need to pass two var's with data:
id and cover
id - sends {{article.id}}
cover - sends image
(and on the backend side it's uploading img and converting it - but it's already done by someone else)
Could somebody help me how to do it properly? I've never did such thing, and I can't find any working answer. :(
You could send it as an splitted up object like
data: {
myId: id,
myCover: cover
}
but currently you send the whole form that actually should look like
$('form#test').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type: "POST",
url: "{{ url('articles_changecover') }}",
data: formData
processData: false,
contentType: false,
success: function (data) {
alert(data);
}
});
});
And viewing the source looks fine to send...at least for me ^^
below is my html form
<form id='add'>
<input type="text" name="title">
<textarea id="usingckeditor" name="content"></textarea>
<input type="file" name="file">
<button id="save">save</button>
</form>
and here is my javascript
$("#save").on('submit',(function(e) {
$.ajax({
url: "blog/saveblog.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
}
});
})
i'm using new FormData() to send data to saveblog.php, and saveblog.php working to upload image and get value of $_POST['title'], but $_POST['content'] is empty
how FormData to get content of textarea(that using ckeditor)?
Buttons don't have submit events, you have to bind the submit event to the form, also you have to prevent the form from submitting since you're using ajax to post the data.
CKEditor manages its own content so it's not in the textarea, you can get it by calling getData() on the CKEditor instance
<form id='add'>
<input type="text" name="title">
<textarea id="usingckeditor"></textarea>
<!-- remove name attribute so it will not pollute form data object -->
<input type="file" name="file">
<button id="save">save</button>
</form>
$("#add").on('submit',(function(e) {// attach form to submit event
e.preventDefault(); //prevent the form from submitting
var data = new FormData(this);
//add the content
data.append('content', CKEDITOR.instances['usingckeditor'].getData());
$.ajax({
url: "blog/saveblog.php",
type: "POST",
data: data,
contentType: false,
cache: false,
processData:false,
success: function(data){
}
});
})
You might use:
$(form).trigger('form-pre-serialize');
And then create new FormData()
Add this before ajax call:
var data = new FormData([form]);
data.append('[textarea_name]', CKEDITOR.instances['textarea_id'].getData());
I have a really simple HTML page with an image upload form as follows:
<form id="file_data">
<input type='file' id='image_uploaded' accept='image'/>
<input type='submit' id="upload_image"/>
</form>
My Javascript:
$(document).ready(function() {
$("form[id='file_data']").submit(function() {
var form_data = new FormData(this);
$.ajax({
url: "upload.php",
type: "POST",
data: form_data,
processData: false,
success: function(data) {
alert(data);
}
});
});
});
upload.php is creating a directory to store images, if the directory does not already exists. Then is supposed to store image in the directory:
<?php
define("IMAGE_DIRECTORY", "images");
//If the directory for images does not exist, create it
if(!is_dir(IMAGE_DIRECTORY)) {
mkdir(IMAGE_DIRECTORY, 0777, true);
}
move_uploaded_file($_FILES["tmp_name"], IMAGE_DIRECTORY . "\\" .basename($_FILES["file"]["name"]));
?>
While the PHP script will create the directory, if it does not already exist, it is not saving any images to the directory. I'm assuming I am not accessing the image correctly from PHP, but the tutorials I've looked at don't explain too much of the details of what is actually going on when an image is sent in an Ajax call to PHP.
Problem you are missing in code:
Html: enctype="multipart/form-data" on form to upload file, also <input type="file" missing name="file"
Php: move_uploaded_file is not correct you are missing ['file'] for tmp_name $_FILES['file']["tmp_name"]
Ajax: dataType:"html" is missing so that your ajax get response as string from server
Update your Html, Php and Ajax code like this:
Html Code:
<form id="file_data" enctype="multipart/form-data" method="post">
<input type='file' name='file' id='image_uploaded' accept='image'/>
<input type='submit' id="upload_image"/>
</form>
Php Code:
<?php
define("IMAGE_DIRECTORY", "images");
//If the directory for images does not exist, create it
if(!is_dir(IMAGE_DIRECTORY)) {
mkdir(IMAGE_DIRECTORY, 0777, true);
}
move_uploaded_file($_FILES['file']["tmp_name"], IMAGE_DIRECTORY . "\\" .basename($_FILES["file"]["name"]));
?>
Ajax Code:
$.ajax({
url: "upload.php",
data : form_data,
type : "POST",
async: false,
cache: false,
contentType: false,
processData: false,
dateType : "html",
success: function(data) {
alert(data);
}
});
I have a form which use to I send using Ajax with jQuery. And like you can see in the title the question is: Why ajax upload file doesn't need enctype="multipart/form-data" in the form tag?
The example something like this:
<html>
<head>
<script>
$("form1").submit(function(event){
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'formprocessing.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
alert(returndata);
}
});
return false;
});
</script>
</head>
<form id="form1">
<input name="image" type="file" />
<input type="submit" value="Submit">
</form>
</html>
You're posting the form content with ajax, so the attributes on the <form> tag are irrelevant. Your own code is basically doing the work that the browser would do if the form were posted implicitly by the browser.
I'm trying to POST the html input file to my PHP file, instead of using the traditional synchronous html forms.
The issue i'm facing is that i'm don't think im POST'ing the input file correctly to my PHP file because my PHP file is saying that its not receiving any POST data.
HTML:
<form id="uploadForm">
Begin by uploading a file (<5mb): <br> <br>
<span class="btn btn-info btn-file" id="buttonColor">
Browse... <span class="glyphicon glyphicon-folder-open"></span><input type="file" id="uploadBrowseBtn" name="uploadBrowseBtn" onchange='$("#upload-file-info").html($(this).val());'>
</span>
<br>
<span class='label label-info' id="upload-file-info">Choose a file.</span>
<br> <br>
<input type="button" class="btn btn-info" id="uploadSubmitBtn" value="Upload">
</form>
JS:
$("#uploadSubmitBtn").click( function() {
var formData = new FormData($('#uploadForm')[0]);
$.ajax({
url: '/upload.php',
data: formData,
async: false,
contentType: false,
processData: false,
cache: false,
type: 'POST',
success: function(data)
{
},
})
});
PHP:
<?php
if(empty($_POST)){
echo true;
}else{
echo false;
}
?>
PHP puts posted files in the _FILE variable:
http://php.net/manual/en/reserved.variables.files.php
So even if the posting jquery part is working correctly, you could not see if a file was received by checking if the _POST variable is empty in PHP.
I'm not very good at jQuery, but this should do what you want.
$( document ).ready(function() {
$('#uploadSubmitBtn').on('click', function() {
var file_data = $('#uploadBrowseBtn').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'upload.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data){
$('#uploadForm').html(data);
}
});
});
});
<form id="uploadForm">
<input type="file" id="uploadBrowseBtn">
<input type="button" id="uploadSubmitBtn" value="Upload">
</form>
<?php
var_dump($_POST); // empty when received a file
var_dump($_FILES); // filled when received a file
?>
This question: jQuery AJAX file upload PHP answers your question, and has a perfect explanation to what it actually does.