Ajax Request 500 Internal Server Error in Internet Explorer - asp.net

I am getting this 500 Internal Server Error only in IE 10 when I run my application that makes a simple Ajax request to a Page Method. I have tested it in Chrome and Firefox, it works fine in these. Please make any relevant suggestion ASAP.
I will paste the code below:
function GetProductId() {
$.ajax({
type: "POST",
url: "Default.aspx/GenerateQrCode",
data: "{'Products':" + JSON.stringify([{ ProductId: 1 }, { ProductId: 2 }]) + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
},
success: function (msg) {
var data = $.parseJSON(msg.d);
}
});
}
[WebMethod]
public static string GenerateQrCode(List<Product> Products)
{
List<string> images = new List<string>();
foreach(var product in Products)
{
string qrCodeLocation = (from pic in products
where pic.ProductId == product.ProductId
select pic.QrCode).FirstOrDefault().ToString();
images.Add(qrCodeLocation);
}
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(images);
}

Is a bug of .Net framework:
IE10 is not mapped as IE browser, and ASP.NET throw back the JS code for a generic browser.
Add this meta-tag in the top of your master page and try again:
<meta http-equiv="X-UA-Compatible" content="IE=9"/>

Related

Add ASP.NET Image from Page Method

I am making an Ajax request with data to a Page Method in my code behind in my ASP.NET Web Forms application. I have a Panel control in my aspx page but I cannot get the control from that Page Method with its ID. I can get it from the Page_Load event though. What can I do to get the Panel control from the page method or is it not possible or maybe an alternative?
<asp:Panel ID="pnlImages" runat="server"></asp:Panel>
<script type="text/javascript">
function GetProductId() {
$.ajax({
type: "POST",
url: "Default.aspx/GenerateQrCode",
data: "{'Products':" + JSON.stringify(data) + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
},
success: function (msg) {
alert('Success');
}
});
}
</script>
[WebMethod]
public static void GenerateQrCode(List<Product> Products)
{
foreach(var product in Products)
{
string qrCodeLocation = products.Where(pid=>pid.ProductId == product.ProductId).Select(s=>s.QrCode).FirstOrDefault().ToString();
Image image = new Image();
image.ID = product.ProductId.ToString();
image.ImageUrl = qrCodeLocation;
//Cannot get 'pnlImages' here
}
}
You won't be able to do that, WebMethod doesn't follow the same flow as normal page methods. It's not even a instance method but static.
You'll have to return the information on client and create the image there using javascript.

Just another jQuery AJAX not POST parameters correctly

I've googled many similar situations, but none of them could solve my problem. Please take a look at my code:
JavaScript:
$.ajax({
type: 'POST',
url: 'alarmInfo.aspx',
data: {request:'BasicGpaInfo'},
dataType: "json",
success: function (data) {
alert(data);
},
error: function () {
alert("Error in loading alarm information!");
}
});
ASP.NET:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form["request"] == "BasicGpaInfo")
{
Response.Write(BasicGpaInfo());
}
else
{
Response.Write("Nothing");
}
}
This always returns "Nothing" and break point tells that Request.Form is null. And I have tried with GET and Request.QueryString which gives the same situation.
I guess there's something wrong with data in ajax function and I've tried with the following things that won't help:
data: $.param({request:'BasicGpaInfo'})
data: "{request:'BasicGpaInfo'}"
data: {request:'BasicGpaInfo'}
It won't work on all Web Browsers.
Please give some advice. Thanks!
I tested your code and it runs fine. However it always returns "Error in loading alarm information!" because you are not returning Json from the server.
Javascript is fine, once you return json, it will go into success.
You are returning the whole page, and your ajax method is getting the whole html instead of Json from BasicGpaInfo()
try putting a breakpoint in alert, and you will see all the data come inside data
error: function (data) {
alert("Error in loading alarm information!");
}
alternatively try
error: function (data) {
alert(data);
}
Here is the full code
$.ajax({
type: 'POST',
url: 'Default.aspx/BasicGpaInfoWebMethod',
data: { request: 'BasicGpaInfo' },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
},
error: function (data) {
alert("Error in loading alarm information!");
//alert(data); // uncomment to see the whole response
}
});
and your webmethod will be :
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string BasicGpaInfoWebMethod(string request)
{
return request;
}
Try this JSON.stringify before post. For using JSON.stringify in IE<=7 include json2.js file from json.org
$.ajax({
type: 'POST',
url: 'alarmInfo.aspx',
data: JSON.stringify({ request: 'BasicGpaInfo'}),
dataType: "json",
success: function (data) {
alert(data);
},
error: function () {
alert("Error in loading alarm information!");
}
});

aspx and jquery.ajax is always returning an error

This code worked fine in mvc2, but moving back to traditional ASPX (because of Sharepoint 2010). I am encountering errors. Can anyone tell me what I am doing wrong for this framework?
This ajax call is in the $.ready
$.ajax({
type: "POST",
dataType: "json",
data: 'siteName=a&siteUrl=b',
url: 'Wizard.aspx/DoesNameUrlExist',
beforeSend: function () { alert("before send"); },
complete: function () { alert("complete"); },
success: function (data) { alert("success"); },
error: function (data) {
if ($("meta[name=debug]").attr("content") == "true") {
//Full Error when debugging
var errDoc = window.open();
errDoc.document.write(data.responseText);
errDoc.document.close();
}
else {
// generic error message for production use
alert("An unexpected error occurred.");
} return false;
}
});
code behind
[WebMethod]
public static string DoesNameUrlExist(string siteName, string siteUrl)
{
//do something
return someString;
}
I get an error everytime.
You need to send JSON to the service and indicate that you're doing so via the contentType header:
$.ajax({
type: "POST",
contentType: 'application/json',
data: '{"siteName":"a","siteUrl":"b"}',
url: 'Wizard.aspx/DoesNameUrlExist',
beforeSend: function () { alert("before send"); },
complete: function () { alert("complete"); },
success: function (data) { alert("success"); },
error: function (data) {
if ($("meta[name=debug]").attr("content") == "true") {
//Full Error when debugging
var errDoc = window.open();
errDoc.document.write(data.responseText);
errDoc.document.close();
}
else {
// generic error message for production use
alert("An unexpected error occurred.");
} return false;
}
});
More info here: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Also, if you're using jQuery 1.4, you can drop the dataType. jQuery will infer JSON automatically based on the response's Content-Type header.
Ajax calls in jQuery will always give you an error if you declare your contentType as json and the response content type is anything but json. If the response from your WebMethod has something different (such as html or text), you'll always get that error. You can set that response type on your method like this:
[WebMethod]
[ScriptMethod (UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string DoesNameUrlExist(string siteName, string siteUrl)
Outside of WebMethods this can also be achieved like this:
Response.ContentType = "application/json";

2 page methods on an aspx page

I'm calling a page method with jquery and it works just fine. I'm creating a second one and it's not working at all; all I get is the error function. Is it possible to put more than 1 page method in an aspx page?
Here's my jquery on the client:
function LoadCount() {
var TheObject = $.toJSON(CurrentForm);
var TheParameter = "{'TheParameter' : '" + TheObject + "'}";
$('#testobj').html("loading");
$.ajax({
type: "POST",
url: "../Pages/MyPage.aspx/GetCount",
data: TheParameter,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFn,
error: errorFn
});
};
function successFn(thedata) { $('#result').html(thedata.d); };
function errorFn() { alert("problem getting count"); };
function LoadData() {
var ConfirmLoad = "test";
$.ajax({
type: "POST",
url: "../Pages/MyPage.aspx/GetLoaded",
data: ConfirmLoad,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successLoad,
error: errorLoad
});
};
function successLoad(thedata) { alert((thedata.d)); };
function errorLoad() { alert("problem getting loaded"); };
And on the server side, I have this:
[WebMethod]
public static string GetCount(string TheParameter)
{
// some code
return JsonResult;
}
[WebMethod]
public static string GetLoaded(string ConfirmLoad)
{
return "test string";
}
LoadCount and GetCount work great, I thought I'd copy the implementation to create another page method but the second time, nothing good happens. Thanks for your suggestions.
You need to set dataType: "text" in the $.ajax() call properties if you're just returning plain text instead of a JSON encoded string.
You might also want to leave the contentType unspecified (at the default value of 'application/x-www-form-urlencoded') if your're sending plain text instead of a JS object.

JQuery and ASP.Net

Well im trying to return a more complex type than a string or bool but i fail what am i doing wrong?
JavaScript
<script language="javascript" type="text/javascript">
///<Reference Path="~/Script/jquery-1.3.2-vsdoc.js" />
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function() {
$.ajax({
type: "POST",
url: "Test.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.Name);
},
failure: function() { alert("Failed") }
});
});
});
</script>
C# (This is not a webservice just a normal webpage)
[WebMethod]
public static ImageDC GetDate()
{
ImageDC dc = new ImageDC();
dc.Id = 1;
dc.Name = "Failwhale";
dc.Description = "Hurry the failwale is going to eat us!";
dc.IsPublic = true;
return dc;
}
I'm not sure what version .NET your running, but there is a breaking change with object returned from a web service. Check out this article.
http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/
If you use fiddler to look at the request/response, it should be easy to tell if this is the problem.
http://www.fiddler2.com/fiddler2/
You should return a string.
return "dc = {Id:"+dc.Id+", Name:" + dc.Name +", Description: " +dc.Description + ", IsPublic: " +dc.IsPublic "}";

Resources