AJAX Post Test Method Failed to load resource - c#

I created a test web application that is calling my MVC application. I can call the POST fine with Postman and wanted to try and call it from a web browser but I am getting a 405 error. ANy help would be great.
Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
Test HTML Project
$.ajax({
type: "POST",
url: "URL",
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
},
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
crossDomain: true,
success: function (response) {
console.log('message: ' + "success" + JSON.stringify(json));
},
failure: function (error) {
console.log('message Error' + JSON.stringify(error));
}
});
MVC Application
public class PublicController : ApiController
{
[System.Web.Http.HttpPost]
public IHttpActionResult MethodTest(string key, string action)
{
}
}
web.config
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
</customHeaders>
</httpProtocol>

you have to fix your ajax.remove headers and contenttype and fix dataType and add data
$.ajax({
type: "POST",
url: "http://localhost:60876/WebApi/public/SkipAuthenticationAndLogin"
data:{
key:"key",
userName:"name",
succesUrl:"url"
},
dataType: "json",
success: function (response) {
console.log('message: ' + "success" + JSON.stringify(response));
},
failure: function (error) {
console.log('message Error' + JSON.stringify(error));
}
});
and remove post from action
public IHttpActionResult MethodTest(string key, string userName, string successUrl)
{
}

Related

I am using Window.onpopstate method in ajax for SPA

I am using Window.onpopstate method in ajax for SPA, before that I used window.history but I got an error like
"jquery-1.10.2.js:8720 Failed to load location:
http://localhost:22102/Coach/AddCoaches, state:
{"url":"/Coach/AddCoaches"}: Cross origin requests are only supported
for protocol schemes: http, data, chrome, chrome-extension, https."
my ajax call is
<script>
$('#loadingImage').hide();
$('.jq-navigation-link').click(function () {
var url = $(this).data('url');
loadPartial(url)
})
function loadPartial(url)
{
$('#renderPartial').html("");
$('#loadingImage').show();
$.ajax({
url: url + "?ispartial=" + true,
type: "GET",
success: function (data) {
$('#loadingImage').hide();
$('#renderPartial').html(data);
}
})
window.history.pushState({ url: url }, '', url);
}
window.onpopstate = function (event) {
debugger
if (event.state) {
var url = "location: " + document.location + ", state: " + JSON.stringify(event.state);
load(url);
}
};
</script>
<script type="text/javascript">
$('body').delegate(".btnUrl", "click", function (e) {
e.preventDefault();
var url = $('.btnUrl').data('url');
//var test = $('.form').serialize();
$('#loadingImage').show();
$.ajax({
async: true,
url: url,
type: 'POST',
data: $('.form').serialize(),
dataType: "json",
success: function (data) {
if (data.Success) {
$('#loadingImage').hide();
loadPartial(data.Url);
}
else {
$('#loadingImage').hide();
loadPartial(data.Url);
}
}
})
})
function load(url) {
$('#renderPartial').html("");
$('#loadingImage').show();
$.ajax({
url: url,
type: "GET",
success: function (data) {
$('#loadingImage').hide();
$('#renderPartial').html(data);
}
})
}
</script>
Error clearly says it is Cross origin requests. Your Web application is using port 8720 and you web API is using port 22102. Browser is considering requests as different origin and for security reason is blocking data for another site request.
For resolving this, you need to enable CORS on your application OR need to host Web application & Web API at same port or same IIS application.
For Enabling cors try:
install nuget package:
Install-Package Microsoft.AspNet.WebApi.Cors
In App_Start/WebApiConfig.cs, add following code in Register method before map routing :
config.EnableCors();
In API Controller, [EnableCors] attribute to the class:
[EnableCors(origins: "http://yoursitehere", headers: "*", methods: "*")]
public class TestController : ApiController
{
// Controller methods not shown...
}
OR
Adding the header through web.config
<httpProtocol>
<customHeaders>
<clear />
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
For more details refer:
https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api
https://forums.asp.net/post/5795304.aspx

Unable to send large data in Jquery ajax call

Hi I am developing MVC4 application. I am saving values to Database. I am getting below error.
The request filtering module is configured to deny a request where the query string is too long.
I am making ajax call and sending data as Json as below.
$.ajax({
type: "POST",
cache: false,
url: '/UploadDocument/SubmitDoc?JsonValue=' + JSON.stringify(SaveUpload) + '&gridData=' + strOrderArr,
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
'VerificationToken': forgeryId
},
success: function (response) {}
});
Web.config
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
May i know am i following good approach to handle above scenario when posting huge data to database? Thanks in advance.
It's a POST Request yet you're passing data in Query string!
Pass data in Data parameter:
$.ajax({
type: "POST",
cache: false,
url: '/UploadDocument/SubmitDoc',
data: JSON.stringify({ JsonValue: SaveUpload, gridData:strOrderArr }),
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
'VerificationToken': forgeryId
},
success: function (response) {}
});

Error 500 using C# WebMethod from jQuery ajax

I keep getting error 500 from my ajax function when trying to call WebMethod.
$.ajax({
type: "POST",
url: "BookingCalendar.aspx/TestFunction",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg);
},
error: function () {
alert("Error");
}
});
[WebMethod]
public static string TestFunction()
{
return DateTime.Now.ToString();
}
After more looking I found out that GET and POST are disabled by default in .NET. I added this to the web.config file:
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
For more information look here.

ajax GET works, POST gives 400 error

GetData(...) method was OK, but SetSimple(...) method throwing error 400.
Javascript:
$.ajax(url,
{
type: action,
timeout: 3000,
data: { value: 123 },
contentType: "application/json; charset=utf-8",
//dataType: "json",
success: function (data, textStatus, jqXHR) {
displayInfo("success: "+data);
},
error: function(jqXHR, textStatus, errorThrown ) {
displayInfo("error: "+errorThrown+" "+textStatus);
}
}
);
C#:
[WebGet(RequestFormat = WebMessageFormat.Json)]
string GetData(int value);
[WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, Method = "POST")]
string SetSimple(int value);
To run/test it I have the service opened in a browser, then my test page with the javascript in another browser. (And dataType: "json" doesn't seem to help.)
And the fiddler response shows "The server encountered an error processing the request. See server logs for more details", but I don't see anything in the Event Logs. Anyone see if/what I'm doing wrong?
You should be transform your JavaScript object into string.
JSON.stringify(data)
Then on your example
$.ajax (url,
{
type: action,
timeout: 3000,
data: JSON.stringify({ value: 123 }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, textStatus, jqXHR) {
displayInfo("success: "+data);
},
error: function(jqXHR, textStatus, errorThrown ) {
displayInfo("error: "+errorThrown+" "+textStatus);
}
}
);
Your ajax request is setting the "data" property to { value: 123 }. You need to pass the appropriate object to the SetObject method which is CompositeType. The ajax request looks like you're using it as a utility function so just pass data as a parameter so the ajax request would be:
var makeAjaxCall = function(url, action, data) {
$.ajax(url,
{
type: action,
timeout: 3000,
data: data,
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, jqXHR) {
displayInfo("success: "+data);
},
error: function(jqXHR, textStatus, errorThrown ) {
displayInfo("error: "+errorThrown+" "+textStatus);
}
}
);
}

How to send and retrieve data from web method using JQuery Ajax Call? [duplicate]

This question already has answers here:
Send JSON data via POST (ajax) and receive json response from Controller (MVC)
(8 answers)
Closed 9 years ago.
I have a text box and a button next to it. I want to send the content of textbox through Jquery ajax call to webmethod and get back the upper case value of the same and display that in alert. So far i have this code but its not working.
JAVASCRIPT:
function CallWM()
{
var name = $('#name').val();
RealCallWM(name);
}
function RealCallWM(name) {
$.ajax({
url: 'Register.aspx/UpperWM',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: { name: JSON.stringify(name) },
success: OnSuccess(response),
error: function (response) {
alert(response.responseText);
}
})
};
HTML:
Name: <input id="name" type="text" />
<input id="Button1" type="button" value="button" onclick="CallWM();"/></div>
</form>
WEB METHOD:
[WebMethod]
public static string UpperWM(string name )
{
var msg=name.ToUpper();
return (msg);
}
Replace:
data: '{name: ' + name + '}',
with:
data: { name: JSON.stringify(name) },
to ensure proper encoding. Right now you are sending the following payload:
{name:'some value'}
which is obviously an invalid JSON payload. In JSON everything should be double quoted:
{"name":"some value"}
That's the reason why you should absolutely never be building JSON manually with some string concatenations but using the built-in methods for that (JSON.stringify).
Side note: I am not sure that there's a callback called failure that the $.ajax method understands. So:
$.ajax({
url: 'Register.aspx/UpperWM',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: { name: JSON.stringify(name) },
success: OnSuccess(response),
error: function (response) {
alert(response.responseText);
}
});
Also notice that in your error callback I have removed the response.d property as if there's an exception in your web method chances are that the server won't return any JSON at all.
As per your comment I understood your issue not yet resolved, so just try this
function RealCallWM(name) {
$.ajax({
type: "POST",
url: "Default.aspx/UpperWM",
data: JSON.stringify({ name: $('#name').val() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data, status) {
console.log("CallWM");
alert(data.d);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});
}

Categories