23

I'm trying to send an array of data from my page to the MVC Action using jQuery Ajax. Here is my jQuery code:

$('#btnSave').click(
  function () {
    result = [];
    $('#tblMatters tbody tr.mattersRow').each(function () {
      if (!($(this).hasClass('warning'))) {
        var item = {};
        if ($(this).find('td.qbmatter > div.dropdown').length > 0) {
          item.QBDescription = $(this).find('td.qbmatter > div.dropdown > a').text();
        } else {
          item.QBDescription = $(this).find('td.qbmatter').text();
        }
        var id = $(this).find("td:first > a").text();
        item.Narrative = $("#collapse" + id).find("div.scrollCell").text();
        item.WorkDate = $(this).find('td.workDate').text();
        item.Hours = $(this).find('td.hours').text();
        item.Person = $(this).find('td.person').text();
        if ($(this).find('td.rate > div.dropdown').length > 0) {
          item.Rate = $(this).find('td.rate > div.dropdown > a').text();
        } else {
          item.Rate = $(this).find('td.rate').text();
        }
        item.Amount = $(this).find('td.amount').text();
        result.push(item);
      }
    });
    var originalRecords = $("#tblSummary tr.summaryTotalRow td.summaryOriginalRecords").text();
    var originalHours = $("#tblSummary tr.summaryTotalRow td.summaryOriginalHours").text();
    var excludedHours = $("#tblSummary tr.summaryTotalRow td.summaryExcludedHours").text();
    var totalHours = $("#tblSummary tr.summaryTotalRow td.summaryTotalHours").text();
    $.ajax({
      url: "/Home/SaveQBMatter",
      type: "POST",
      data: JSON.stringify({ 'Matters': result, 'originalRecords': originalRecords, 'originalHours': originalHours, 'excludedHours': excludedHours, 'totalHours': totalHours }),
      dataType: "json",
      traditional: true,
      contentType: "application/json; charset=utf-8",
      success: function (data) {
        if (data.status == "Success") {
          alert("Success!");
          var url = '@Url.Action("Index", "Home")';
          window.location.href = url;
        } else {
          alert("Error On the DB Level!");
        }
      },
      error: function () {
        alert("An error has occured!!!");
      }
    });
});

Let me explain a little bit. I have an HTML table that was built dynamically and I need to store this data into a database. In jQuery I have a loop going through the table and I store data of every row in the result array. Then I pass this data using Ajax into MVC Action.

And here is where my problem starts... I've realized that sometimes it goes as it should be, but sometimes I'm getting an error from Ajax alert("An error has occured!!!"); Now I've understood that this error occurs when my result array is getting big. For example: If it contains 100-150 items > everything is good, but when there are more than ~150 > Error.

Is there any POST limit in Ajax? How can I set it up for any sizes? I really need this functionality! Any help please!

My ActionResult Code:

public ActionResult SaveQBMatter(QBMatter[] Matters, string originalRecords, string originalHours, string excludedHours, string totalHours) {
  DBAccess dba = new DBAccess();
  int QBMatterID = 0;
  int exportedFileID = 0;
  foreach (QBMatter qb in Matters) {
    dba.InsertQBMatter(qb.QBDescription, qb.Narrative, qb.WorkDate, qb.Person, qb.Hours, qb.Rate, qb.Amount, ref QBMatterID);
  }
  ExcelTranslator translator = new ExcelTranslator();
  translator.CreateExcelFile("", Matters, originalRecords, originalHours, excludedHours, totalHours);
  return Json(new { status = "Success", message = "Passed" });
}

UPDATE: Found a solution

JSON has a maximum length! I need to increase this value. In web.config add the following:

<appSettings>
  <add key="aspnet:MaxJsonDeserializerMembers" value="150000" />
</appSettings>
dda
  • 6,030
  • 2
  • 25
  • 34
Bryuk
  • 3,295
  • 10
  • 45
  • 74
  • the reason for the error is something else. Use firebug / use visual studio breakpoints to see what your real problem is – Shyju Nov 27 '13 at 17:55
  • you will need the return code as a minimum from the debug alert / dev-tool – mschr Nov 27 '13 at 17:57
  • 1
    Guuys.. Please. I still need a help! – Bryuk Nov 27 '13 at 18:44
  • I found the problem! If this post will help somebody, any up votes appreciates! =) – Bryuk Nov 27 '13 at 18:53
  • @Bryuk You can answer your own post. – Aycan Yaşıt Nov 27 '13 at 19:19
  • I had this same issue also. y SPA application, was saving the UI state for local storage as a ~temp save in real time intervals, and then they could do a traditional save sending it from JS front end to c# back end, to sql for later retrieval. I had a hell of a time getting around the json length issue. The web.config param did not fix it for me. – Casey ScriptFu Pharr May 21 '20 at 04:48
  • I have seen that it is not necessarily the JSON length as if you converted to string and did a LENGTH(str) check against it, but a JSON nested objects max size issue for me. – Casey ScriptFu Pharr May 21 '20 at 04:49

7 Answers7

32

JSON has a maximum length! I need to increase this value. In web.config add the following:

<appSettings>
  <add key="aspnet:MaxJsonDeserializerMembers" value="150000" />
</appSettings>
dda
  • 6,030
  • 2
  • 25
  • 34
Bryuk
  • 3,295
  • 10
  • 45
  • 74
  • Its already in my web config but still getting error of length exceeded when i pass json data to controller. I'm passing more than 600 length of list. – SPnL Dec 22 '17 at 13:25
  • already there bigger value.it is _2147483647_ but still getting error. – SPnL Dec 23 '17 at 04:33
5

Is it any POST Limit in Ajax?

No, the HTTP specification doesn't impose a specific size limit for posts. However it depends on the Web Server which you are using or the programming technology used to process the form submission.

In ASP.NET MVC you can try this:

<system.webServer>
<security>
    <requestFiltering>
        <requestLimits maxAllowedContentLength="1000000" />
    </requestFiltering>
</security>
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • So what could be cause of problem? – Bryuk Nov 27 '13 at 17:54
  • @Bryuk:- It is really difficult to actually tell the cause as there could be many reasons. I would recommend you to use any debugger to check the actual problem but going by your title line there is no such limit for POST in Ajax – Rahul Tripathi Nov 27 '13 at 17:58
  • @Bryuk:- I dont know if that is going to work for you or not but once I have received the same POST 500 Internal Server Error and changing from POST to GET worked for me. Could you try that where you have written type:'POST' – Rahul Tripathi Nov 27 '13 at 18:22
  • I just tried change POST to GET and in this case I got all data in my Action = null... – Bryuk Nov 27 '13 at 18:29
  • I spent much time on this and research, and saw that even after the web config settings, if issue exist it may not be the actual length of the json, but this error is general for also covering the max limit reached of JSON nested object length. – Casey ScriptFu Pharr May 21 '20 at 04:52
4

The HTTP spec doesn't defining a limitation of POST data size.

But using ASP.NET MVC, there could be a POST data limitation, try to increase it in your Web.Config file:

<system.webServer>
<security>
    <requestFiltering>
        <requestLimits maxAllowedContentLength="1000000" />
    </requestFiltering>
</security>

From MSDN:

Specifies the maximum length of content in a request, in bytes. The default value is 30000000.

Yair Nevet
  • 12,725
  • 14
  • 66
  • 108
  • Anyway I'm getting an error and I even didn't get into the action, so it's 100% ajax... – Bryuk Nov 27 '13 at 18:04
3

This solved my problem:

<system.web.extensions>
    <scripting>
        <webServices>
            <jsonSerialization maxJsonLength="2147483647" />
        </webServices>
    </scripting>
</system.web.extensions>
1

IF there is a client-side limit then it would be browser specific but the HTTP spec does not define a limitation of POST data size.

Keep in mind that a POST is merely bytes across the network so the more fields you are posting then the longer it can take to upload that data.

A 1MB POST is going to make the user feel like the form is broken and unresponsive if using a traditional form submit.

If there are a lot of fields to serialize() then AJAX could hang up the browser while it collects all of the data. I think browsers do have a memory limit for JavaScript overall so if you hit that limit then the AJAX process will fail.

// wanna have some fun?
var html = '<div></div>';

for(var i = 0; i < 1000000; i++){
    html += html;
}

Your best bet is to increase the maximum allowable POST size on the server-side to avoid issues.

Most commonly issues arise when people make an upload script which simply seems to hang while the user is confused why their 3MB pictures are going slow on a 125KB/s upload link.

MonkeyZeus
  • 20,375
  • 4
  • 36
  • 77
  • "Your best bet is to increase the maximum allowable POST size on the server-side" - Can you please help to do this=) I really need this... – Bryuk Nov 27 '13 at 18:15
  • Unfortunately I am a PHP developer so Yair Nevet's or Rahul Tripathi's post is your best bet. I doubt the POST size is your issue to be honest. There could potentially be many things wrong or mis-formatted with your AJAX call. If possible I recommend posting the code which is contained on your `/Home/SaveQBMatter` page because a 500 error refers to an issue with the server. – MonkeyZeus Nov 27 '13 at 18:21
  • If you would like to see a super basic and thorough AJAX example with PHP then please visit my answer here: http://stackoverflow.com/questions/20150130/ajax-and-php-to-enter-multiple-forms-input-to-database/20150474#20150474 – MonkeyZeus Nov 27 '13 at 18:24
0

The limit is set through a server 'max_post_size' or similar naming. Typical default server settings are 2-8 MB in one post.

On the client side, only GET has a maximum limit, generally considered 1500 bytes (minus 30-150 from request headers) and the reason is the MTU in the more lowlevel network hardware

mschr
  • 8,531
  • 3
  • 21
  • 35
0

In my case the class I was posting to had 'internal set' on the property.

Changed:

public EnabledDataBundle EnabledDataBundle { get; internal set; }

to:

public EnabledDataBundle EnabledDataBundle { get; set; }
BMills
  • 881
  • 1
  • 10
  • 24