Ajax send image within data - javascript

I'm trying to send some data by Ajax and this data may contain an image.
I don't have any forms, so I can't submit by the traditional way.
This is my HTML:
<input type="file" accept="image/png,image/jpg,image/jpeg,image/bmp" id="addProduct_image">
Whenever the user changes the file I get that value.
var files;
$(document).on('change', '#addProduct_image', function(e){
prepareUpload(e);
});
function prepareUpload(event){
files = event.target.files;
}
When the OK button is pressed I call an ajax function.
$(document).on('click', '#addProduct_OK', function(e){
var img = new FormData();
$.each(files, function(key, value)
{
img.append(key, value);
});
$.ajax({
url: 'responses/product.php?type=productAdd',
type: 'POST',
data: {title: $("#addProduct_title").val(), description: $("#addProduct_description").val(),
image: img, status: $("#addProduct_status").val()
},
success: function(data){
console.log(data);
}
});
});
I'm currently receiving the error on chrome console
Uncaught TypeError: Illegal invocation
in the ajax line. I'm to far away from how to send an image by ajax with other data also?

You need to sent the FormData as the data for the ajax request, so the additional params also has to be appended to the fomdata
$(document).on('click', '#addProduct_OK', function (e) {
var img = new FormData();
$.each(files, function (key, value) {
img.append(key, value);
});
img.append('title', $("#addProduct_title").val());
img.append('description', $("#addProduct_description").val());
img.append('status', $("#addProduct_status").val());
$.ajax({
url: 'responses/product.php?type=productAdd',
type: 'POST',
data: img,
processData: false,
contentType: false,
success: function (data) {
console.log(data);
}
});
});

Related

Issue with nested Ajax calls

I am having a series of nested Ajax calls to create and update data into the database as well as calling the updated list once data are successfully submitted.
This is how the code works:
(1) A list of transaction is shown when the page is rendered, each row can be edited by the user.
(2) When clicking a specific row, I run an Ajax call to retrive the form filled with the data to be updated
(3) The form is then submitted via Ajax as well.
(4) If successfully submitted it perform another Ajax call to get the table updated.
First problem: when the table is loaded via Ajax the "edit" button is not working anymore.
Second problem: The form displayed to update and to create is the same, except when updating the form is pre-filled. I would like to avoid duplicating the Ajax call but I had to do it otherwise I wasn't able to submit the form after it was loaded from the first Ajax call (pt 1). Is there a way to make a more clean code?
Here it is the javascript code, server side all works just fine:
$(".edit-transaction").click(function () {
// obtain the object id to load the correct form
const object_id = $(this).data('object-id');
// request the form via AJAX Get request
$.ajax({
type: 'GET',
url: "/transaction/",
data: {
'slug': object_id
},
success: function(response) {
// Get the form for the requested object
$("#display-form").html(response.html); // this code retrive the form
$("#transaction-form").submit(function (e) {
// preventing from page reload and default actions
e.preventDefault();
let serializedData = $(this).serialize();
// Update the form via AJAX
$.ajax({
type: 'POST',
url: "/transaction/",
data: serializedData,
success: function (response) {
console.log('updated successfully')
// load the table with the new content updated
$.ajax({
type: 'GET',
url: "/get-transactions-list/",
success: function (data) {
$("#display-transaction-list").html(data.html);
},
});
},
error: function (response) {
let error = response ["responseJSON"]["error"];
$.each(error, function (code, message) {
alert('message');
});
}
})
})
},
error: function (response) {
let error = response ["responseJSON"]["error"];
$.each(error, function (code, message) {
alert('message');
});
}
})
});
$("#transaction-form").submit(function (e) {
// preventing from page reload and default actions
e.preventDefault();
let serializedData = $(this).serialize();
// Create a new transaction via AJAX
$.ajax({
type: 'POST',
url: "/transaction/",
data: serializedData,
success: function (response) {
console.log('created successfully')
// load the table with the new content updated
$.ajax({
type: 'GET',
url: "/get-transactions-list/",
success: function (data) {
$("#display-transaction-list").html(data.html);
},
});
},
error: function (response) {
let error = response ["responseJSON"]["error"];
$.each(error, function (code, message) {
alert('message');
});
}
})
})
Thanks for any help
Since some of the elements are added asynchronously, this means that the event listeners which were added at runtime will not affect those elements. You should instead listen to events on them via "events delegation".
You can also create a custom event for loading the table content. So to update the table, you just .trigger() your custom event. This is useful when you want to implement other functionalities which will need a table update like, delete, etc.
// custom event for loading the table content
$(document).on('load.table', '#display-transaction-list', function () {
const $table = $(this);
$.ajax({
type: 'GET',
url: "/get-transactions-list/",
success: (data) => $table.html(data.html)
});
});
// edit transaction event
$(document).on('click', '.edit-transaction', function () {
// obtain the object id to load the correct form
const object_id = $(this).data('object-id');
// request the form via AJAX Get request
$.ajax({
type: 'GET',
url: "/transaction/",
data: {
'slug': object_id
},
success: function(response) {
// Get the form for the requested object
$("#display-form").html(response.html); // this code retrive the form
},
error: function (response) {
let error = response ["responseJSON"]["error"];
$.each(error, function (code, message) {
alert('message');
});
}
})
});
// save transaction event
$(document).on('submit', '#transaction-form', function (e) {
// preventing from page reload and default actions
e.preventDefault();
let serializedData = $(this).serialize();
// Update the form via AJAX
$.ajax({
type: 'POST',
url: "/transaction/",
data: serializedData,
success: function (response) {
// you can add some data to the response
// to differentiate between created and updated. Eg response.actionType
console.log('created or updated successfully')
// load the table with the new content updated
$("#display-transaction-list").trigger('load.table');
},
error: function (response) {
let error = response ["responseJSON"]["error"];
$.each(error, function (code, message) {
alert('message');
});
}
})
})

jQuery AJAX load() div table after loaded buttons are not working

currently having this problem, I have ajax request to send form datas and save it to database and after saving I then use load() function to refresh the list in table, but after being loaded the button inside the loaded div is not working which also uses js.
Ajax
var formData = new FormData(this);
$.ajax({
url: "/systemadmin/storemanagement/"+id,
method: "POST",
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log(data)
$("#storeDatatable").load(location.href + " #storeDatatable");
$(".message-error").remove();
$(".message-success").remove();
$('#store-update-header').append('<div class="message-success">Update succesfully</div>');
}, error:function (err) {
if (err.status == 422) {
console.log(err.responseJSON);
$(".message-error").remove();
$(".message-success").remove();
$.each(err.responseJSON.errors, function (i, error) {
$('#store-update-header').append('<div class="message-error">'+error[0]+'</div>');
});
}
}
});
solved by using
$(document).on('click','.toggleModal-updateStore', function(){ })
instead of
$('.toggleModal-updateStore.').on('click', function(){ })
for the buttons inside the row

ASP NET upload image with jQuery and AJAX

What I'm trying to do is theoretically simple: I want upload an image using ASP.NET, jQuery and AJAX, without submitting a form (this part is important).
So I have this:
HTML
<input type="file" accept="image/*" id="imguploader">
jQuery
var file_data = $("#imguploader").prop("files")[0];
var form_data = new FormData();
form_data.append("file", file_data);
$.ajax({
type: "POST",
url: '#Url.Action("InsertImage", "Product")',
data: { file: form_data },
contentType: false,
processData: false,
success: function (response) {
alert('succes!!');
},
error: function (error) {
alert("errror");
}
});
Controller
public ActionResult InsertImage(HttpPostedFileBase file) {
//blabla and the code to insert in the database.
return Content("");
}
What else I have tried:
// instead of using FormData, I tried to direclty capture the file using these:
var file = $("#imguploader").file;
//and
var file = $("#imguploader")[0].files;
//Same result (null).
The problem is that the file variable is always null no matter what. What I'm doing wrong? Can anybody helps?
You can manually set the FormData keys and values yourself.
<input type="file" name="imguploader" id="imguploader" />
<button id="btnUpload">Upload</button>
Create FormData and set a new key/value
$("#btnUpload").on("click", function(e) {
e.preventDefault();
var file = $("#imguploader").get(0).files[0];
var formData = new FormData();
formData.set("file", file, file.name);
$.ajax({
url: '#Url.Action("InsertImage", "Product")',
method: "post",
data: formData,
cache: false,
contentType: false,
processData: false
})
.then(function(result) {
});
});
The controller
[HttpPost]
public ActionResult InsertImage(HttpPostedFileBase file)
{
}

FormData gets uncaught type error

I am making a form submission through AJAX using jQuery. I have the following code:
$("#myForm-form").on("submit", function(event) {
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: {
'eoss': 'indexEOSS',
'form': 'myForm',
'values': createJSON(),
'formData': formData
},
success: function(data) {
console.log(data);
eval(data);
myFormForm(data);
},
processData: false,
contentType: false
});
return false
});
However I get this:
GET http://localhost/EOSS2/request.php?[object%20Object] 404 (Not Found)
When I remove processData: false and contentType: false I get the following error:
Uncaught TypeError: Illegal invocation
What should I do?
You have two issues here. Firstly your error message indicates that you're sending a GET request, which does not work with FormData. Using POST would seem the most applicable in this case.
Secondly, you cannot send FormData in an object as jQuery will attempt to URL encode it which will lead to issues. Instead use the append() method to add information to your FormData object. Try this:
$("#myForm-form").on("submit", function(e) {
e.preventDefault();
var $form = $(this);
var formData = new FormData($form[0]);
formData.append('eoss', 'indexEOSS');
formData.append('form', 'myForm');
formData.append('values', createJSON());
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'), // change the attribute in HTML or hardcode to 'post'
data: formData,
success: function(data) {
console.log(data);
// eval(data); < never, ever use eval()
myFormForm(data);
},
processData: false,
contentType: false
});
});

How to pass selected file to php script using jQuery?

The following form is what I use:
<form id="form-attachment" action="" method="post" enctype="multipart/form-data">
<input name="attachment" type="file" />
<input type="submit" />
</form>
This is what I do with jQuery:
$('body').on('submit', '#form-attachment', function(e) {
e.preventDefault();
var data = $(this).serialize();
console.log('fine', data);
var url = 'imageupload.php';
$.ajax({
type : "POST",
url : url,
data : data,
success : function(response) {
console.log('success: ' + response);
},
complete : function(response) {
console.log('complete: ', response);
},
error: function(response) {
console.log('error: ', response);
}
});
});
And this is my imageupload.php file:
$response = array();
$response["c"] = isset($_FILES["attachment"]);
echo json_encode($response);
And this is result on console on submit():
success: {"c":false}
So, what is wrong? Why my file is not visible at all?
You can use FormData object, as shown below..
$('body').on('submit', '#form-attachment', function(e) {
var data = new FormData(jQuery('#form-attachment')[0]);
jQuery.ajax({
type: "post",
contentType: false,
processData: false,
url: jQuery(this).attr('action'),
dataType: "json",
data: data,
success: function (r) {
// Success Handeling
}
});
});
NOTE:- No need to append anything as other answer suggests.
This method shall pass all the input fields just like they would in a normal http form POST method.
Use FormData object.
Here's the example how to send file via jQuery ajax request:
$(document).on('change', 'input[type=file]', function() {
formData = new FormData;
formData.append('file', $(this)[0].files[0]);
$.ajax {
url: '/upload-url',
data: formData,
type: 'post',
processData: false,
contentType: false,
success: function(data) {
console.log(data);
}
}
});
In your case you should serialize form first, append serialized data to the formData object. Then get file (or files) from a file field and append it to the same formData object. And finally send the formData object via ajax.

Categories