Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append objects in FormData in javascript?

We need to send the data to the server by appending it within formdata in javascript. In javascript, we have handle this as like below.

var ajax = new XMLHttpRequest();
ajax.open("POST", url, true);
var formData = new FormData();
var obj = {url: "uploadUrl",type: 'POST', mode: true};
formData.append('myData', JSON.stringify(obj));
ajax.send(formData);

In server end, we have the method as like below.

 public void Save(MyModel args) {
     ....
    }


    public class MyModel
    {

        public MyObj myData { get; set; }

    }
    public class MyObj
    {
        public string url { get; set; }
        public string type { get; set; }
        public bool mode { get; set; }
    }

args.myData always received as null. How to receive the data sent from the client here in this format ? Suggest your ideas.

like image 635
Karthik Ravichandran Avatar asked Oct 15 '22 12:10

Karthik Ravichandran


2 Answers

You need to explicitly send the formData:

var ajax = new XMLHttpRequest();
ajax.open('POST', url, true);
var formData = new FormData();
var obj = {url: "uploadUrl",type: 'POST', mode: true};
formData.append('myData', obj);
ajax.send(formData);

(Note that I fixed the arg order in ajax.open and the received formdata will be something like [object Object] but I think JSON.stringify() should be the solution here - that depends on how your server parses the formdata)

like image 106
Jb31 Avatar answered Oct 31 '22 21:10

Jb31


In server code, set the type of args to String and check if you are getting the stringified data. If you are getting it, parse the data accordingly to fit into MyModel.

Providing more info of Server code might help me to look into further.

EDIT 1: Links that might also help

  • Reading file input from a multipart/form-data POST
  • Are there any multipart/form-data parser in C# - (NO ASP)
like image 39
Naveen Kumar V Avatar answered Oct 31 '22 23:10

Naveen Kumar V