ajax error 500 & Internal Server Error in MVC - asp.net-mvc-4

I used ajax method to call the controller and fetch the data and convert it to json or list and set a jquery DataTable. With 1000 records it's working fine, but when I fetch more than 5000 records, ajax method gives me:
500 Internal server error
Here is my code:
$('#btnAllData').click(function () {
$.ajax({
url: 'PartMaster/GridLoad',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Result) {
debugger;
var pageload = Result.split('|');
var status = (pageload[0])
if (status == "ERROR") {
Error(pageload[1]);
}
else {
var Partdetails = (pageload[0]);
//var LocDetails = JSON.parse(pageload[2]);
}
//gridDetails(status1);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});

check how much time your database is taking to returning data.
Set length of web response ( You can adjust the JSON response size in the web.config with ).
<configuration>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="1000000" />
</webServices>
</scripting>
</system.web.extensions>
</configuration>

Related

How to call a method from API Controller using ajax

I want to call a method from API Controller using AJAX. I have tried the following
I have added one hidden field in the view (like what we are doing in mvc controller)
<input type="hidden" id="GetShoppingCartUrl" value="#Html.Action("GetShoppingCartUrl","Cart")"/>
Then I have written ajax
function GetShoppingCart() {
debugger;
var url = $('#GetShoppingCartUrl').val();
$.ajax({
type: "get",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
error: function () {
}
});
}
But here it is not getting the method, GetShoppingCartUrl from the API Controller CartController. I want to call that method, what changes make it happening ?
function GetShoppingCart() {
debugger;
var url = "Cart/GetShoppingCartUrl"
$.ajax({
type: "get",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
error: function () {
}
});
}
you can directly put your actionlink in the url
Hope it helps. :)
Use this below code to get the url of your site in javascript and append it before the url in ajax call. e.g var url = baseUrl+ "Cart/GetShoppingCartUrl";
#{
string url = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath;
if(url[url.Length-1]!='/')
{
url =url+ "/";
}
}
var baseUrl = '#url';
//alert(baseUrl);

400 Bad Request - https://accounts.google.com/o/oauth2/token

can anyone please tell me why this is bad request
var searchurl = "https://accounts.google.com/o/oauth2/token";
$.ajax({
dataType: "json",
url:searchurl,
context: {code:auth_code, client_id:'clientid', client_secret:'secret', redirect_uri:'http%3A%2F%2Flocalhost:8085%2FGmailIntegration%2FgetAuthResponse.jsp', grant_type:'authorization_code'},
type:"POST",
contentType:"application/x-www-form-urlencoded",
success:function(data) {
alert(data);
},
error: function(jqXHR, exception) {
console.log(jqXHR);
}
});
I got this working.. i am sharing the code for those who are stuck with this:
$.ajax({
dataType: "json",
url:searchurl,
data: {code:code, client_id:'clientid', client_secret:'secret', redirect_uri:'http://localhost:8085/GmailIntegration/getAuthResponse.jsp', grant_type:'authorization_code'},
type:"POST",
contentType:"application/x-www-form-urlencoded; charset=utf-8",
crossDomain:true,
cache : true,
success:function(data) {
alert(data);
},
error: function(jqXHR, exception, errorstr) {
console.log(jqXHR);
alert(errorstr);
}
});
but now i have new issue. The url get 200 OK response but i am not getting response at all
OAuth2 user agent flow is recommended for JS clients, see https://developers.google.com/accounts/docs/OAuth2UserAgent
Is there any specific reason you want to use the web server flow in a JS app?

Same Origin Policy Error when using jQuery JSONP with CloudFlare API

I recieve an error (XMLHttpRequest cannot load https:// www.cloudflare.com/api_json.html?tkn=&email=&z=&a=rec_load_all&callback=%3F. Origin http:// domainmanager.tech-bytes.org is not allowed by Access-Control-Allow-Origin.) (spaces inserted in URLs due to Stack Overflow link limit) when trying to send a JSONP request via jQuery to CloudFlare. The CloudFlare API states that you can ask for a JSONP callback by appending a &callback=mycallback parameter. I am not sure if I am supposed to replace mycallback with something, I tried replacing it with ? as that is what some other resources said, or if I have to do some other modifications to my code.
Try in this way for cross domain request.
$.ajax({ url: "yourUrl",
data:{paramName1: JSON.stringify(paramValue1),paramName2: JSON.stringify(paramValue2)},
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function(data) {
alert(data.d);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
You can use CORS for this purpose.
Example code:
jQuery.support.cors = true;
function CrosDom_ajax(url) {
if (window.XDomainRequest
&& $.browser.msie
&& $.browser.version < 10) {
xdr = new XDomainRequest();
if (xdr) {
xdr.onload = function () {
alert(xdr.responseText);
};
xdr.open("get", url);
xdr.send();
}
}
else {
$.ajax({
url: url,
success: function (response) {
},
error: function (data) {
}
});
}
}
Also you need to Write the following code in server side, to allow cross domain access
Response.AppendHeader("Access-Control-Allow-Origin", "*");

how to call this calling WCF method continuously

I have an ajax enabled WCF service method :
[OperationContract]
public string Test(string name)
{ return "testing testing." + name; }
and I am calling it with following code:
$(document).ready(function () {
var varData = $("#NewSkill").val();
$("#Button1").click(function () {
$.ajax({
type: "POST",
url: "TimeService.svc/Test",
data: '{"name" : "John"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
}
});
});
});
I want to call this method continuously after every 5 seconds using above code . How can I do this ?
Move the $.ajax(); part to a Javascript function say AjaxCall(). Create a javascript variable
var isActivated = false;
$(document).ready(function () {
while(isActivated){
setTimeout("AjaxCall()",3000);
}
}
);
$("#Button1").click(isActivated = true)
Hope this helsps...

jQuery Ajax call returning null from WCF RIA REST service

I have created a WCF REST .NET 4 service and deployed it to a local IIS 7.
If I use Fiddler and use the request builder, I am able to call the service and see the data been returned OK. If I try hitting the same REST location in the browser, JSON is not been returned but it looks like XML.
My service looks like this:
[OperationContract]
[WebGet(UriTemplate = "/{id}/details.json",
ResponseFormat=WebMessageFormat.Json)]
public SampleItem Get(string id)
{
return new SampleItem{ Id=1, StringValue="value from string"};
}
My web.config file has only a slight change:
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" defaultOutgoingResponseFormat="Json"/>
I am trying to call the service using jQuery like this:
$(document).ready(function () {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://wcf-rest/service1/1/details.json",
dataType: "json",
success: function (data) { alert(data); },
error: function (e) { alert("error"); }
});
}); // end .ready
However, null is being returned every time. What do I need to change?
I've been using jQuery and Ajax extensively with a JSON datatype, and I believe you need to change data to data.d. See my example below.
function getMakes() {
$.ajax({
type: "POST",
url: "../../WebService_VehicleAssignment.asmx/getAllVehicleMakes",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var response = msg.d;
$('#output').empty();
$.each(response, function (vehicle, vehicle) {
$('#output').append(new Option(vehicle.Make, vehicle.Id));
});
},
failure: function (msg) {
alert('failure');
}
});
}<br />
I use Firebug to debug this stuff. I can see exactly what's getting posted to the web service and what is coming back. And if the web service is complaining, what it's complaining about.
Read about why the .d is necessary in A breaking change between versions of ASP.NET AJAX. In short, I believe it is a wrapper so that returned data is treated as a string rather than being returned and executed if it is raw literal JavaScript code.