FormData is not a constructor - javascript

I'm trying to make a ajax request to upload a image. My problem is when I create the FormData. My console is saying "dataForm is not a constructor".
How can I solve this ?
here is my script
$("#new-broadcast-image-static").on("change", function(formData) {
var formData = new formData();
// line that console point the error //
var file = $("#new-broadcast-image-static")[0].files[0];
formData.set("image", file);
$.ajax({
url: apiUrl + "image/upload",
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
xhrFields: {
withCredentials: true
},
success: function(data) {
hashNewBroadcastImage = data.data.identifier;
$("#hash-new-broadcast-image-static").val(hashNewBroadcastImage);
}
});
});

Capitalize it: var formData = new FormData();
But what are you trying to acomplish anyways? You are reasigning a variable you are getting as parameter:
$("#new-broadcast-image-static").on("change", function(formData) {
var formData = new formData();
You probably want to change it to something like
$("#new-broadcast-image-static").on("change", function(e) {
var formData = new FormData();

Not totally sure about it, but I think you have a capital letter mistake, you've write formData() instead of FormData()
The correct way:
var formData = new FormData();

Please Check this Possibility it will definitely solve your problem
Anywhere in your JS Code if you are assigning a value to FormData like below
FormData={"PersonID":1,"PersonName":"Test"};
and if you use like this
var a = new FormData();
Then it will throw an error like "FormData is not a constructor as it is already declared as an Object".

as my experience sometime because of in javascript function is debugger mode.

I tried all of the solutions for this and none worked. After hours of pulling my hair out, I discovered it was because I had a filed named FormData, which was a partial Vue Pinia State. I changed the name of that file to formData and it worked. So if you run into this problem and can't solve it and you have FormData used as a variable or file name anywhere in your project - change it and see if that fixes it.

Related

Creating a file from a blob

I'm in need of some javascript guru. I have this code:
handleImage(new File([blob], blob.name, {type: blob.type})).done(/* something */)
and
handleImage = function (image) {
// create some fake form data
var formData = new FormData();
formData.append("attachment", image);
formData.append("auto", true);
formData.append("_csrf", "xxxxxxxxx");
// post to the server.
return $.ajax({
url: "/some/url",
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
error: function () {
console.log("error");
}
});
This works fine with Chrome and Firefox, but when using Safari (10.1.1), the server (java / spring mvc) receive in the MultipartHttpServletRequest an empty file for "attachment". So it seems to me that new File([blob], blob.name, {type: blob.type}) is somehow failing.
Any idea of what's wrong here?
This is probably a bug in safari's young implementation.
But why do you even convert it to a File object ?
A File object is a Blob, the only difference being that it has a name and a lastModified properties. But since you already seem to extend your blob, it leaves only this lastModifiedproperty that you could add too anyway.
The only API I can think of, where it makes a difference if your object is a Blob or a File is FormData.append method ; where if you pass a File object, it will be able to set the filename automatically. But this method has a third parameter, allowing you to set this filename.
So if you change your code to include formData.append("attachment", image, image.name); and call it with handleImage(blob) directly, it will do exactly the same request as the one you're doing, except that it will work on Safari and every other browser that don't support the File constructor (looking at you IE).

Ajax request not passing parameter to ASP.NET MVC controller

Tried looking in stackoverflow because this looked so trivial. Found many similar questions and read through them. Found no solution using these examples. Here is my code, can anyone help?
function testAjax() {
return $.ajax({
type: "GET",
url: '#Url.Action("Nodes","Competence", new { userId = Sven });',
contentType: "application/json;charset=utf-8",
dataType: "json"
});
}
var promise = testAjax();
promise.success(function (data) {
var dataConverted = JSON.stringify(data);
$('#tree').treeview({ data: dataConverted, multiSelect: true });
});
ASP.NET MVC method
public JsonResult Nodes(string userId)
{
var temp = userId;
var list = new List<Node>();
list.Add(new Node("Test1"));
list.Add(new Node("Test2"));
list.Add(new Node("Test3"));
return Json(list, JsonRequestBehavior.AllowGet);
}
EDIT:
Just before I was about to turn crazy on Halloween night, i figured out to try in a new session. Turns out it was just a caching problem..Thanks for the help everyone
Since your server may not expecting a request with JSON content, try removing the contentType parameter on your ajax call. Its default value is "application/x-www-form-urlencoded; charset=UTF-8" and is fine for most cases.
It's type should be "POST"
return $.ajax({
type: "POST",
url: '#Url.Action("Nodes","Competence")',
data: { userId: "Test" },
contentType: "application/json;charset=utf-8",
dataType: "json"
});
As it's a GET verb, it'll be easiest to pass this in as a querystring value. This also conforms better with a RESTful design.
For example replace #Url.Action("Nodes","Competence")
with
#Url.Action("Nodes","Competence", new { userId = id });
Then you can delete the data property. This will append ?userId=valueOfId into your url and then it should be mapped correctly to your action with the userId correctly populated.
Update
As #freedomn-m stated:
This will generate the url when the view is built server-side. If the
parameters never change, then fine - but it's relatively unlikely that
the parameters won't change, in which case you should add the url
parameters at runtime if you want them on querystring.
This is completely accurate. Without knowing your exact implementation I can only make assumptions. But technically you could wrap your ajax call in a function and then you could either pass in the userId and generate the url within that function or pass in the url, performing the url generation outside of the function.
This would mean that you only need one function that performs the ajax request and you can have another function that gets the userId (and possibly generates the url) and then passes that into the ajax function. How you store the userId is entirely up to you, but one thing I would suggest is investigating data attributes which is a fairly well defined way for storing data on html elements.

Cropping an image on rails

I have the following data both in my js file or as a param in rails. Togther there is an image that is to be sent to server, what I want to achieve is to crop the image based on the data such as below. I am not allowed to use gems :) just using ruby/js code if I can manipulate the image already in js side. I am using cropper js which generated the output to me. What should I do to achieve cropping ?
{"x":552.697358490566,"y":-72.49509433962258,"width":696.9599999999999,"height":696.9599999999999,"rotate":0,"scaleX":1,"scaleY":1}
Check out the fiddle: Link
This is the code you should be using, since your JSON is already formatted the same way Cropper takes its input:
//get the data from your rails framework and save it in a variable, below I just pasted the same data you put in your question
var data = {"x":552.697358490566,"y":-72.49509433962258,"width":696.9599999999999,"height":696.9599999999999,"rotate":0,"scaleX":1,"scaleY":1};
//remember to change my-picture to the id of your img
$('#my-picture').cropper('setData', data);
//also make sure to bind this to your own button
$('#crop-button').click(function(e){
//this will transform the image into a blob, so you can submit it in form data
$(this).href = $('#my-picture').cropper("getCroppedCanvas").toBlob(function (blob) {
var formData = new FormData();
formData.append('croppedImage', blob);
//this is where you put your Rails path to upload
//it's going to be a POST, so you should know how to handle it
$.ajax('/path/to/upload', {
method: "POST",
data: formData,
processData: false,
contentType: false,
success: function () {
console.log('Upload success');
},
error: function () {
console.log('Upload error');
}
});
});
});

How to pass formData to postData in loadOneTab?

I have a formData object and would like to pass it to loadOneTab()
Example:
var formData = Components.classes['#mozilla.org/files/formdata;1']
.createInstance(Components.interfaces.nsIDOMFormData);
formData.append('Content-Type', 'multipart/form-data');
formData.append('filename', '');
formData.append('image_url', URL);
How can I pass above object to postData
window.gBrowser.loadOneTab('https://www.example.com/',
{inBackground: false, postData: postStream});
I already kinda answered this as part of your last question.
Unfortunately we cannot use FormData here, as there is currently no way to get the stream (and other information) from a FormData instance (nsIXHRSendable is not scriptable, unfortunately). postData however expects the value to be an nsIInputStream instance.
So there is no way to use FormData in conjunction with loadOneTab and friends (essentially all <tabbrowser> and <browser> methods expect a stream if they accept a postData argument).

Javascript Blob changes file

I really have no prior knowledge to Blob objects in JavaScript aside from what I've read here but need to use them to convert a string of binary data into a .xls file which I then make available to the user. The catch is when I construct a blob, get the location, and open up the file to look at it, it opens up saying
The file you are trying to open is in a different format that
specified by the file extension. Verify that the file is not
corrupted and is from a trusted source before opening the file.
(I know this data is incorrect because when I submit the form normally I get the file correctly and don't have this issue)
This is done in an ajax call and the success functions parameter data is the binary data.
$("#fileForm").submit(function(){
var fileData = $("#fileInputElmt").prop("files")[0];
var data = new FormData();
data.append("upload",fileData);
var url = "process.action?" + $("#fileForm").serialize();
$.ajax({
type: "POST",
url:url,
data:data,
cache:false,
contentType:false,
processData:false,
success:function(data){
var bb = new Blob([data],
{ type: 'application/vnd.ms-excel',endings:'native'});
var bUrl = URL.createObjectURL(bb);
window.open(bUrl,"_self");
hideProgressBar();
},error:function(data){
hideProgressBar();
}
});
return false;
});
Am I doing something wrong? or is there a better way of doing this?

Categories

Resources