Does JQuery's Ajax refer to maxJsonLength property in web.config - javascript

In my ASP.NET site, I use Jquery AJAX to load json data (in fact a string) from a webservice when clicking the search button :
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(parameterArray),
contentType: "application/json",
dataType: "json",
success: function(response) {
d = JSON.parse(response.d);
}
When the return string gets too big, the page stop responding. I have to go to web.config and add this property in order for the website to work :
<jsonSerialization maxJsonLength="2147483644"/>
Here is how do the application handle the search result before returning data to the browser :
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
string strData = dService.searhforData(ipt);
List<Dictionary<string, object>> lRow = processData(strData);
string r = serializer.Serialize(lRow);
return r;
In case the Json string got too long, the page just stop responding, there wasn't any error in the console window. As I debug at the .Net application side, the serializer.Serialize(lRow); went smoothly and successfully return the r, after that, the loading icon on the page just keep spinning. If I press F5 on the page, the search data appears.
My question is, if JQuery's Ajax refers to the web.config for the max json string length, why couldn't I find any information regarding this on the internet ?

I'm sure there is a limit on the amount of data that JSON.parse() can handle, but that's not related to your problem.
Your web.config file holds settings to be used server side. The JS on the client is not related to that at all. If you needed to amend that setting it's because your ASP.Net code was producing a JSON response longer than was previously allowed by the default setting of jsonSerialization.
If you checked the browser console after making the failed request you would most likely have seen an error in the response which guided you to the problem.

Related

AJAX throws error when response exceeds certain size

My ASP.NET 4.5 .asmx web service (part of a web forms project, not separated) returns an xml string whenever the user double-clicks on a table row so the details for that row can be retrieved from the database.
This, in and of itself, works fine.
In situations however, where the response is somewhat longer (around 200k, 300k char count from what I can see), the web page will throw a js alert popup (saying "Error") and I'll see a 500 Internal Server Error in the Chrome console, no further details. However, when I go to the web method url and enter the arguments manually, I'll get an immediate and complete xml string in response without issues.
I'm using the following (synchronous) js/ajax to call the web method:
function GetDetailsFromTableRow(userID, country, rowName) {
var url = "http://MyServer/MyWebService.asmx/MyWebMethod",
result = '';
$.ajax({
type: "POST",
async: false,
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({
'userID': userID,
'country': country,
'rowName': rowName
}),
success: function (response) {
result = response.d;
},
error: function (x, t, m) {
if (t === "timeout") {
alert('timeout!');
}
else {
alert(t); //<- this gets thrown apparently
}
}
});
return result;
}
From this js you can ascertain that this function is, in fact, NOT throwing a timeout so I'm fairly certain I can eliminate that.
Furthermore, I would assume that I needn't chunk the response myself for data that is merely a few hundred kilobytes but still: I might be wrong.
I'm also quite aware that the better way to call web methods is asynchronously, but I'm succeeding in calling other (substantial) data already (both in async and sync ways) so I'm looking for an answer to the question why this is not working for responses over a certain size (I have responses that are 80kB and some that are 200+kB, the former work, the latter don't) because I'm obviously not understanding some parts of the whole story.
For completeness: an async=true call to the web service causes the exact same behavior.
debugging the js in IE yielded following error:
Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property
as mentioned in this answer (and corrective comments), adding the following entries to the web.config increased the maxJsonLength value to int.MaxValue:
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="2147483644"></jsonSerialization>
</webServices>
</scripting>
</system.web.extensions>
subsequent tests are all successful. Issue resolved.

Jquery ajax function returns wrong page, though the url in a browser window shows correct page

I'm building a chrome extension in javascript.
I'm trying to get the page contents from an Outlook mailserver through an ajax request, but I have trouble getting the correct page returned.
I suspect it is the danish letter æ, that creates the problem, but don't know how to resolve it.
$.ajax({
url: baseURL + 'Indbakke/',
data: "Cmd=contents&View=Ulæste%20meddelelser", //Avoid encodeURI
dataType: 'html',
processData: false, //Avoid encodeURI
cache: false,
success: function(data) {
fetchedInbox = $.parseHTML(data);
//If there are changes to the inbox, refresh the inbox page
if(findString(fetchedInbox, 'ingen emner'))
{
window.parent.frames[1].location = baseURL + 'Indbakke/?Cmd=contents';
}
},
complete : function(){
console.log("URL" + this.url)
}
});
The data variable of the succes function contains the wrong page, but if I copy 'this.url' from the complete function into a browser, it displays the right page. I have tried using default ajax settings and encodeURI on the full link (without using the 'data' option), but then neither 'data' or 'this.url' will work (i.e. I change the second parameter to 'View=Ul%C6ste%20meddelelser').
I do not have access to the (probably) asp page that the server sends, just javascript, so I can't do anything serverside.
Note: When chromes console show this.url, it breaks the link before æ, so I have to manually copy the url
It's probably the æ that creates this error. Replace æ by %C3%A6 and the headers will be send to the correct location.
data: "Cmd=contents&View=Ul%C3%A6ste%20meddelelser"
To find the encoded character, I used this converter: http://meyerweb.com/eric/tools/dencoder/

How can i retrieve a file from one url and post it to another?

I'm trying to create a javascript api to take a word doc as input from the server side (say A) and post it to another api (say B) that will convert it to pdf. The reason I'm doing this is so that i can use the call to B against any A instead of having to modify each of the A APIs (there are multiple As that give word docs).
This is what I have done so far. The problem is when I'm calling B I'm not able to get the file that i'm sending.
Here's my code.
javascript call to server.
$("#downloadFile").click(function(){
$.ajax({
url : "/fileDownload.action",
success : function(data){
handleFile(data);
}
});
});
});
function handleFile(inputFile){
$.ajax({
url : "/convertFile.action",
type : "POST",
data : {inputFile : inputFile },
cache:false,
processData:false,
contentType: "application/msword",
success : function(data){
alert("yay?");
}
});
}
On my server side (a struts 2.3 action class) for "/convertFile.action", I have a setInputFile(File inputFile) method to set the file from request. However, it is not setting the file.
Now if I use a standard file upload with a form in HTML it sets the file (no javascript though, just plain html and server side code).
Also If I try to construct a form and post without an ajax call, I still get the same result. I tried to use the js in this answer to post the form.
What am I doing wrong? One possibility is that I need to take the input as a string or a stream. But is there anything else that I'm doing wrong/violating/can't do?

Return PDF to browser using JSON and MVC3

My requirement is whenever a Image is clicked a PDF should be opened on the browser. I am using Jquery ajax [POST call] to make a call to the ASP.NET MVC side and a file is returned on the response. A POST is required from the jquery side since I need to pass substantial data from client to server.
HTML Part:
<span data-id='printSettings' title='Generate PDF' class="preferenceSettings"></span>
JS Part: This is fired when the Generate PDF icon is clicked.
var textToSend = $('.microChartTable', self.element)[0];
var dataToSend = { htmlContent: textToSend.outerHTML };
$.ajax({
url: "/EADashboard/ConvertToPDF",
data: JSON.stringify(dataToSend),
type: 'POST',
contentType: 'application/json',
success: function (data) {
} // -- success ends here
});
ASP.NET Side : In my controller, I have the following code:
[HttpPost]
public FileResult ConvertToPDF(HtmContent content)
{
string fileName = Server.MapPath("~/SeedData/data.pdf");
string contentType = "application/pdf";
return new FilePathResult(fileName, contentType);
}
Now the PDF generation code is correct just that the PDF file is not been opened on the browser side. I have seen the post Return PDF to browser using JSON and MVC? but since there was no solution provided, I am posting this again. Can anyone let me know how this can be achieved ?
Thanks
Two things.
Why are you doing post via ajax and not a regular post? With a regular post your code would probably work.
If you indeed need to do it with ajax, you are receiving result in the data object on the success of the ajax call, and I do not see that you do anything with it, which is why you do not see anything happening.

Ajax - 500 Internal Server Error

I am trying to learn AJAX for this project at work. I have a site that loads medications that a patient is taking.
I call this AJAX function up recursively so that it will append a new table containing a single medication and 7 days worth of history. I am having issues getting the code to execute in FF and IE. Works perfectly fine in chrome. I had alerts displaying the xmlhttp.status and this is what I got:
xmlhttp.status==500 (internal server
error).
I commented out all of my recursion so it is narrowed down to this tid bit of code. ( x keeps track of the number of meds so i know when to stop)
function LoadMeds()
if ( x == MaxMedCount )
{
document.getElementById("the_day").value = parseInt(document.getElementById("the_day").value)+7;
}
if ( x == (MaxMedCount - 1) )
{
document.getElementById("x").value = x + 1;
show();
}
else
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
try
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var div = document.createElement('div');
div.innerHTML= xmlhttp.responseText;
document.getElementById('MedTable').appendChild(div);
document.getElementById("the_med_").value = the_med_;
}
}
catch(e)
{
alert("Error");
}
}
xmlhttp.open("GET","URL with variables passed",true);
xmlhttp.send();
document.getElementById("x").value = x + 1;
}
if more code is needed just let me know.
The 500 (internal server error) means something went wrong on the server's side. It could be several things, but I would start by verifying that the URL and parameters are correct. Also, make sure that whatever handles the request is expecting the request as a GET and not a POST.
One useful way to learn more about what's going on is to use a tool like Fiddler which will let you watch all HTTP requests and responses so you can see exactly what you're sending and the server is responding with.
If you don't have a compelling reason to write your own Ajax code, you would be far better off using a library that handles the Ajax interactions for you. jQuery is one option.
I think your return string data is very long. so the JSON format has been corrupted.
You should change the max size for JSON data in this way :
Open the Web.Config file and paste these lines into the configuration section
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
This may be an incorrect parameter to your SOAP call; look at the format of the parameter(s) in the 'data:' json section - this is the payload you are passing over - parameter and data wrapped in JSON format.
Google Chrome's debugging toolbar has some good tools to verify parameters and look at error messages - for example, start with the Console tab and click on the URL which errors or click on the network tab. You will want to view the message's headers, response etc...
Uncomment the following line : [System.Web.Script.Services.ScriptService]
Service will start working fine.
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
To allow this Web Service to be called from script, using ASP.NET
AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
Had the very same problem, then I remembered that for security reasons ASP doesn't expose the entire error or stack trace when accessing your site/service remotely, same as not being able to test a .asmx web service remotely, so I remoted into the sever and monitored my dev tools, and only then did I get the notorious message "Could not load file or assembly 'Newtonsoft.Json, Version=3.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dep...".
So log on the server and debug from there.
One must use behavior: JsonRequestBehavior.AllowGet in Post Json Return in C#
I fixed an error like this changing the places of the routes in routes.php, for example i had something like this:
Route::resource('Mensajes', 'MensajeriaController');
Route::get('Mensajes/modificar', 'MensajeriaController#modificarEstado');
and then I put it like this:
Route::get('Mensajes/modificar', 'MensajeriaController#modificarEstado');
Route::resource('Mensajes', 'MensajeriaController');
I had the same error. It turns out that the cause was that the back end method was expecting different json data. In my Ajax call i had something like this:
$.ajax({
async: false,
type: "POST",
url: "http://13.82.13.196/api.aspx/PostAjax",
data: '{"url":"test"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
});
Now in my WebMethod, inside my C# backend code i had declared my endpoint like this:
public static string PostAjax(AjaxSettings settings)
Where AjaxSettings was declared:
public class AjaxSettings
{
public string url { get; set; }
}
The problem then was that the mapping between my ajax call and my back-end endpoint was not the same. As soon as i changed my ajax call to the following, it all worked well!
var data ='{"url":"test"}';
$.ajax({
async: false,
type: "POST",
url: "http://13.82.13.196/api.aspx/PostAjax",
data: '{"settings":'+data+'}',
contentType: "application/json; charset=utf-8",
dataType: "json"
});
I had to change the data variable inside the Ajax call in order to match the method signature exactly.

Categories

Resources