Ajax - 500 Internal Server Error - javascript

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.

Related

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

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.

jquery ajax call fails when data size exceeds 1119 bytes

A button click triggers this code:
$("#testButton").click(function() {
var str = $("#ptext").html();
$.ajax({
type: "POST",
url: "/pages/testfn",
data: { thetext: str }
})
.done(function(msg) {
alert( "success " + msg );
});
});
The php that handles this is this:
public function testfn() {
$s = $_POST['thetext'];
echo strlen($s);
}
This works perfectly if the amount of text I have in the #ptext div is less than 1120 bytes. More than that and it silently fails. How can I pass more than 1120 bytes to the testfn function?
Check your PHP configuration. This is most likely a configuration issue. Try fiddle with the values below in your php.ini:
post_max_size=32M
upload_max_filesize=32M
memory_limit=32M
32M (megabytes) is just an example, you might want to have other values.
Well, this is embarrassing. I discovered the problem only occurred when I was testing the site through a proxy server. To get at the site from the "outside" I used a Netshade proxy server in Canada. The clue was that the POST worked when I tested it with my cell phone browser. So I used the local IP address and turned off the proxy server and it all works.

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.

google spreadsheets - ajax call (get and post)

what I need to do is read the content of a "public" google spreadsheet (by public I mean that I saved the sheet clicking on "File > Publish to the web", so it's accessible without the need to be logged in into a google account), and, why not, write something into it too.
googlin' around, I found that I can access the sheet and get the xml equivalent of the sheet content with something like
https://spreadsheets.google.com/feeds/list/<sheetCode>/od6/public/values
It works great if I load that url into a browser. But I need to find a "javascript-way" to get and handle the returned value, ie the xml (or json, but xml would be preferable).
I tried to use an ajax call, but I think there's something messy with the protocol.. I can't get the server response correctly.
$.ajax({
type: "GET",
url: "https://spreadsheets.google.com/feeds/list/<sheetCode>/od6/public/values",
success: function(data){alert("yeah");},
error: function(){alert("fail..");},
dataType:"xml",
});
I also tried to get the json instead of xml, adding "?alt=json" to the url and changing the datatype, but I still have the problem..
Any idea / suggestion?
Thanks in advance, best regards
You need to request with a JSONP call and you need to specifiy a callback - method. This can be done in jQuery using:
var url = 'https://spreadsheets.google.com/feeds/list/<CODE>/od6/public/values?alt=json-in-script&callback=?';
jQuery.getJSON(url).success(function(data) {
console.log(data);
}).error(function(message) {
console.error('error' + message);
}).complete(function() {
console.log('completed!');
});
Documentation and samples for google spreedsheets .

JQuery external Ajax call not working in IE

I have an ajax script that sends some data to an external URL. The external URL is hosted on the same server, however the domain is different than the source of the ajax call.
This is working perfectly in Firefox and Chrome. However in IE The ajax call does not go through, and the Return False function does not either work (once the ajax call fails).
Below is my code:
$.get('http://myexternaldomian.com/feedback/save.php', {
answer: $('#answer').val(),
page_url: pathname
});
// Keeps the user on the page
return false;
When I try removing the http:// from the ajax url, the return false does work.
Any help on this would be greatly appreciated. Thank You
From jQuery documentation
Due to browser security restrictions,
most "Ajax" requests are subject to
the same origin policy; the request
can not successfully retrieve data
from a different domain, subdomain, or
protocol.
and Same Origin Policy on Wiki
I'm surprised any of them are working. Browsers generally don't allow ajax calls to a domain other than the one the current page came from.
The main exception to this rule is if you make an ajax call using jsonp (json with padding). You can do this with jQuery, here's how. Look under the dataType option.
(this is copypaste from my another similar answer). You could try enabling "jQuery.support.cors=true" flag and see how it goes. I use jQuery v1.7.2.
I had to load webpage from local disk "file:///C:/test/htmlpage.html", call "http://localhost/getxml.php" url, and do this in IE8+ and Firefox12+ browsers, use jQuery v1.7.2 lib to minimize boilerplate code. After reading dozens of articles finally figured it out. Here is my summary.
server script (.php, .jsp, ...) must return http response header Access-Control-Allow-Origin: *
before using jQuery ajax set this flag in javascript: jQuery.support.cors = true;
you may set flag once or everytime before using jQuery ajax function
now I can read .xml document in IE and Firefox. Other browsers I did not test.
response document can be plain/text, xml, json or anything else
Here is an example jQuery ajax call with some debug sysouts.
jQuery.support.cors = true;
$.ajax({
url: "http://localhost/getxml.php",
data: { "id":"doc1", "rows":"100" },
type: "GET",
timeout: 30000,
dataType: "text", // "xml", "json"
success: function(data) {
// show text reply as-is (debug)
alert(data);
// show xml field values (debug)
//alert( $(data).find("title").text() );
// loop JSON array (debug)
//var str="";
//$.each(data.items, function(i,item) {
// str += item.title + "\n";
//});
//alert(str);
},
error: function(jqXHR, textStatus, ex) {
alert(textStatus + "," + ex + "," + jqXHR.responseText);
}
});
http://en.wikipedia.org/wiki/Same_origin_policy
I dont think it should work on Chrome or Firefox, unless you testing on localhost or something like that, this would be against the crossdomain policy.
What you need is to proxy it inside the same domain, use php to connect to the destination you need and call the url from the same domain.
save_cross_domain.php -> connect through server to the desired url
then ajax calls save_cross_domain.php
you should add a
callback=?
to your url and handle this on the server side.
I did this once for a java servlet, and when the callback param was included I added an extra pair of parenteses around the json response..
hope it helps!
A couple of things:
The answers/conversation for this question has gone a bit out of context. Actually from the question it was more implied how to make ajax calls in IE. [Atleast modify the question title, else the question is very localized]
A couple of solutions to this cross-domain issue:
CORS[compatible after IE7]
JSONP [ here actually the browser takes in the input thinking it is a script]
server side encoding

Categories

Resources