Send file using ajax (JQUERY) - javascript

I am trying to send a image with AJAX.Though I keep on getting this error.
TypeError: 'append' called on an object that does not implement interface FormData.
This is my code:
$(document).ready(function(){
$('#post').on('submit', function(e){
e.preventDefault();
var data = new FormData(this);
$.ajax(
{
url: 'post_ajax/savePost',
type: 'POST',
dataType: false,
contentType: false,
pocessData: false,
data: data,
success: function (resultado) {
console.log(resultado)
}
}
).done(
function(json){
if(json.data){
console.log('Ajax correcto');
}else{
console.log('No se ha podido guardar el post');
}
}
).fail(
function(){
console.log('fallo en ajax');
}
);
});
});
And this is my html form:
<form id="post" enctype='multipart/form-data'>
<textarea id="texto" rows="4" cols="50" placeholder="¿Que esta pasando?"></textarea>
<input type="file" id="media"/>
<input type="submit" value="Submit"/>
</form>
Thanks you!!

I found this answer here:
var formData = new FormData(form[0]);
formData.append('texto', texto);
formData.append('media', archivo);
$.ajax({
url: 'post_ajax/savePost',
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
console.log(data);
}
});
Thanks everyone for all

Related

Uploading Image Using JSON is not Working

Can anyone help my code structure? What's wrong with it?
HTML
<form method="post">
<div class="col-md-4">
<div class="field name-box">
<input class="btn" name="image_file" id="image_file" type="file" style="font-size:15px;width:100%;margin-bottom:2px;" required=""/>
</div>
</div>
</form>
JS
var form_data = new FormData();
$.ajax({
type: "POST",
url: baseUrlAction() + '?btn=add_product_image',
data: form_data,
contentType: false,
cache: false,
processData:false,
success: function(data){
alert("Successfully");
},
error: function(ts){
}
});
AJAX_CONTROLLER
public function add_product_image(){
if(is_array($_FILES)){
if(is_uploaded_file($_FILES['image_file']['tmp_name'])){
$sourcePath = $_FILES['image_file']['tmp_name'];
$targetPath = "product_images/"."sample_img_name".".png";
if(move_uploaded_file($sourcePath,$targetPath)){
// echo '<script>alert("Successfully Save")</script>';
}
}
}
}
But I've been wondering why I will get a success response on my ajax form? even my upload_file doesn't work properly. Can anyone help me?
you need to append data with form_data in your js file and send response
formData.append('image_file', $('#image_file')[0].files[0];);
var form_data = new FormData();
formData.append('image_file', $('#image_file')[0].files[0]);
$.ajax({
type: "POST",
url: baseUrlAction() + '?btn=add_product_image',
data: form_data,
contentType: false,
cache: false,
processData:false,
success: function(data){
alert("Successfully");
},
error: function(){
}
});
pass form Element to FormData
let form = document.getElementById("yourFormId");
var form_data = new FormData(form);

Ajax post FormData and the form

I have this form:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<div class='col-sm-6' style="padding-left:0px;" >
<form action="/main/" method="post" id="my_form" enctype="multipart/form-data">
{% csrf_token %}
<br>
<div> <input type="text" name="description" id="id_description" /> </div>
<div> <input type="file" name="image" id="id_image" /> </div>
<button type="submit" disabled style="display: none" aria-hidden="true"></button>
<input class="btn btn-success" type="submit" name="submit" value="Gem" />
</form>
</div>
This successfully sends the form and it is valid on the server side. But I can´t access the image from the form on the server.
<script>
var frm = $('#my_form');
frm.submit(function (e) {
e.preventDefault(e);
$.ajax({
async: true,
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
console.log("success")
},
error: function(request, status, error) {
console.log("error")
}
});
});
</script>
This solution sends the FormData with the image file, but it does not include the other form data and the form is not valid on the server side:
<script type="text/javascript">
var frm = $('#my_form');
frm.submit(function (e) {
e.preventDefault(e);
var formData = new FormData();
formData.append(
"image",
document.getElementById("id_image").files[0]
);
$.ajax({
async: true,
type: frm.attr('method'),
url: frm.attr('action'),
data: formData,
cache: false,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
console.log("success")
},
error: function(request, status, error) {
console.log("error")
}
});
});
</script>
Is there a way to send both the file and the other form dara at the same time?
Try passing this to FormData Also, you were setting type twice.
var frm = $('#my_form');
frm.submit(function (e) {
e.preventDefault(e);
var formData = new FormData(this);
$.ajax({
async: true,
type: frm.attr('method'),
url: frm.attr('action'),
data: formData,
cache: false,
processData: false,
contentType: false,
success: function (data) {
console.log("success")
},
error: function(request, status, error) {
console.log("error")
}
});
});
Your last block using formData is only appending the file. This is why data only contains the file no other form data. Be sure to fully populate formData first.

Sending formdata for file upload using ajax

I am trying to upload an image by using form data with ajax. Though below line seems to be working fine and saving the image on my local machine.
<form ref='uploadForm' id='uploadForm' action='/tab10/uploadImage' method='post' encType="multipart/form-data">
<input type="file" class="btn btn-default" name="file" />
<input type='submit' class="btn btn-default" value='Broadcast Image' />
</form>
But when instead of specifying action as a form attribute, i try to make the call using ajax, things didn't seem to be working fine.Below is the code that i am using to make the post API call using ajax.
HTML
<form ref='uploadForm' id='uploadForm' encType="multipart/form-data">
Jquery
$("form#uploadForm").submit(function (event) {
//disable the default form submission
event.preventDefault();
var formData = $(this).serialize();
console.log(formData);
$.ajax({
url: '/tab10/uploadImage',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function () {
alert('Form Submitted!');
},
error: function(){
alert("error in ajax form submission");
}
});
return false;
});
Below is the code i am using for saving the image.
exports.uploadImage = function(req, resp) {
var res = {};
let file = req.files.file;
file.mv('./images/image', function(err) {
if (err) {
res.status = 500;
res.message = err;
// return res.status(500).send(err);
return resp.send(res);
}
res.status = 200;
res.message = 'File uploaded!';
return resp.send(res);
});
};
When i checked the request data in my uploadimage function, it seems that in the request, parameter called "files" is not being send in the later case.
I think you have to create FormData, after you can append the file to the formData, add an ID to the input <input type="file" class="btn btn-default" name="file" id="uploadFile"/>
$("form#uploadForm").submit(function (event) {
//disable the default form submission
event.preventDefault();
var formData = new FormData();
formData.append('file',$('#uploadFile')[0].files[0]);
$.ajax({
url: '/tab10/uploadImage',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function () {
alert('Form Submitted!');
},
error: function(){
alert("error in ajax form submission");
}
});
});
use
$("#uploadForm").submit(function () {
var formData = new FormData(this);
$.ajax({
url: '/tab10/uploadImage',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function () {
alert('Form Submitted!');
},
error: function(){
alert("error in ajax form submission");
}
});
return false;
});
Use this format to fire ajax.because file is multipart or jquery serialize() method not serialize multipart content,so we need to put it manual.
//get choosen file
var fileContent = new FormData();
fileContent.append("file",$('input[type=file]')[0].files[0]);
$.ajax({
type: "POST",
enctype:"multipart/form-data",
url: "/tab10/uploadImage",
data: fileContent,
processData: false,
contentType: false,
success: function(response) {
}
});

Submit an ajax-created form via ajax

I'm having trouble getting an ajax-loaded form (#ajaxLoadedForm) to submit via ajax. The formData object gathers no data. I figure I've got to attach an event-handler to the form so the DOM recognizes it, but I can't figure out how.
A couple of notes: I'm bypassing the 'submit' method and using a button (#button), so I can't attach the handler to that. The form itself is a sibling to #button, not a child.
<form id="ajaxLoadedForm" enctype="multipart/form-data" action="destination.php" method="POST">
<input type="hidden" name="state" value="1" />
<label for="fullname">Your Full Name</label>
<input type="text" id="name" autocapitalize="off" autocorrect="off" name="fullname" placeholder="your name" value="" />
</form>
<div id="button">Submit me!</div>
$('#button').click(function(){
var uploadData = new FormData($("#ajaxLoadedForm")[0]);
jQuery.ajax({
url: 'destination.php',
data: uploadData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
data = JSON.parse(data);
if (data['pass'] == false) {
console.log('fail');
} else {
console.log('success');
}
}
});
});
Try using the submit handler on the form itself
$('#ajaxLoadedForm').submit(function(e){
e.preventDefault();
var uploadData = new FormData(this);
});
Then make your button for submit a submit type
<button type='submit'>Submit</button>
In your php side, test the data coming by doing this:
print_r($_POST);
you can use serialize function for sending form data . Like below
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script >
$('#button').click(function(){
var uploadData = $('#ajaxLoadedForm').serialize();
jQuery.ajax({
url: 'destination.php',
data: uploadData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
data = JSON.parse(data);
if (data['pass'] == false) {
console.log('fail');
} else {
console.log('success');
}
}
});
});
</script>
Try below code..
$('#button').click(function(){
var uploadData = new FormData();
uploadData.append('fullName',$('#fullName').val());
jQuery.ajax({
url: 'destination.php',
data: uploadData,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
}
});
});
And try to access full name in php

File upload using Jquery ajax without form

Here is mycode
function addPackage(elem)
{
var dataimg = new FormData();
dataimg.append('', $("#browseimg"+elem).prop('files')[0]);
var startdate=$("#from_date"+elem).val();
var enddate=$("#to_date"+elem).val();
$.ajax({
url: "addpackage/",
type:"post",
contentType:false,
data:{startdate:startdate,enddate:enddate,packageid:elem,img:dataimg},
success: function(data) {
}
});
}
I tried post method ajax to upload image and input field data without form. In ajax call it showing [object object]. How to post image with input field without form in jquery ajax?
You can do it like following. Hope this will help you.
function addPackage(elem)
{
var dataimg = new FormData();
dataimg.append('startdate', $("#from_date"+elem).val());
dataimg.append('enddate', $("#to_date"+elem).val());
dataimg.append('packageid', elem);
dataimg.append('img', $("#browseimg"+elem)[0].files[0]);
$.ajax({
url: "addpackage/",
type:"post",
cache : false,
contentType : false,
processType : false,
data: dataimg,
success: function(data) {
}
});
}
You can try this:
Your JS Code:
<script type="text/javascript">
var data = new FormData(document.getElementById("yourFormID")); //your form ID
var url = $("#yourFormID").attr("action"); // action that you mention in form action.
$.ajax({
type: "POST",
url: url,
data: data,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
dataType: "json",
success: function(response)
{
// some code after succes from php
},
beforeSend: function()
{
// some code before request send if required like LOADING....
}
});
</script>
Dummy HTML:
<form method="post" action="addpackage/" id="yourFormID">
<input type="text" name="firstvalue" value="some value">
<input type="text" name="secondvalue" value="some value">
<input type="file" name="imagevalue">
</form>
in addpackage php file:
print_r($_POST);
print_r($_FILES);

Categories