how to send ajax POST request - ajax

I am using this method to send post request but it gives me error 500 internal error for jquery.1.11.1.min.js.
$(document).ready(function () {
$.ajax({
type: "POST",
url: '#Url.Action("cashondelivery", "Home")',
data: "",
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (result) {
alert(result);
},
error: function (data) {
alert(data);
}
});
});
//this is action method in controller
[HttpPost]
public ActionResult cashondelivery(productinfoModel mmodel)
{
return View();
}

try to call the url in DHC(chrome plugin),the response status code 500 means server internal error, it's the server-webapp developer's mistake. not your mistake.

Related

Not able Invoke controller action method from Ajax Jquery

I was trying to call mvc core action method from ajax but getting error in console:
Following are the code:
`
$.ajax({
url: LogOutUrl,
type: "POST",
dataType: "html",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "Success") {
alert("Done");
if (window.location.href.indexOf(EserviceLogOutUrl) === -1) {
window.location.href = EserviceLogOutUrl;
}
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error has occured!!!");
}
});
MVC:
MVC: Controller:
public ActionResult Signout()
{
foreach (var cookie in Request.Cookies.Keys)
{
Response.Cookies.Delete(cookie);
}
_httpContextAccessor.HttpContext.Session.Clear();
return new RedirectResult("http://Google.com");//Redirecting to different website in antoher domain.
}
Error in console: I am able to invoke the action methods. but not able redirect the URL.
SEC7123: Request header x-requested-with was not present in the Access-Control-Allow-Headers list.
Add a header to options to satisfy your server:
$.ajax({
url: LogOutUrl,
type: "POST",
dataType: "html",
contentType: "application/json; charset=utf-8",
headers: {'X-Requested-With': 'XMLHttpRequest'},
...

The required anti-forgery form field "__RequestVerificationToken" is not present

There really is a lot of info about this problem in internet, but nothing is helped me.
That is my client code:
var token = $('form[action="/Storage/AddReceipt"] input[name="__RequestVerificationToken"]').val();
var addAntiForgeryToken = function(data) {
data.__RequestVerificationToken = token;
return data;
};
var success = function (result) {
alert(result.success);
};
$.ajax({
url: '#Url.Action("AddReceipt", "Storage")',
type: 'POST',
contentType: 'application/json',
data: addAntiForgeryToken({ Number: 1, BatchDate: '24/03/2015' }),
success: success,
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown);
}
});
and controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddReceipt(...) {...}
and server response to my requerst -
The required anti-forgery form field
"__RequestVerificationToken" is not present.
but correct token is sending:
return JSON.stringify(data);
and
$.ajax({
...
data: $('form[action="/Storage/AddReceipt"]').serialize(),
...
}
doesnt help too.
You missed to add the __RequestVerificationToken to the request headers. Add it as follows.
$.ajax({
url: '#Url.Action("AddReceipt", "Storage")',
type: 'POST',
contentType: 'application/json',
headers:{__RequestVerificationToken : token},
data: JSON.stringify(addAntiForgeryToken({ Number: 1, BatchDate: '24/03/2015' })),
success: success,
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown);
}
});
We must add the anti forgery token to the request header.

Get response from url using ajax and jquery

want to get response from url using ajax and jquery.
tried with this code
$(document).ready(function () {
$.ajax({
type: 'POST',
url: 'apexweb.co.in/apex_quote/uname_validation.asp?,
dataType:'jsonp',
success: function(data){
alert(data);
}
});
});
i want to display response as fail but i didn't get any response on browser
Help Me
Try this
$(document).ready(function () {
$.ajax({
type: "POST",
url: "apexweb.co.in/apex_quote/uname_validation.asp?",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function (data) {
alert(data.d);
},
failure: function (data) {
alert(data.d);
}
});
});

Ajax success not working

I have this:
public ActionResult GetBear(int bearId)
{
return Json(bear);
}
Here is the ajax call to it:
$.ajax({ url: "correctUrl", dataType: 'json', data: { bearId: 2}, contentType: "application/json; charset=utf-8", success: function (data) {
alert("something")
}
GetBear gets executed, but the success method is not entered. What is the porblem?
I added error field and it says Internal server error. Why? I'm not comunicating with a server.
Try this, check if you get alert or not ?
$.ajax({
type: "POST",
url: "correctUrl",
dataType: 'json',
data: {bearId: 2},
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("something")
},
error: function(data) {
//AJAX request not completed
alert("it shows error");
}
And check if page(correctUrl) exist on which you send ajax request..
First check URl Since you wrote function executing
change your function return type from ActionResult to JsonResult

MVC2: Ajax call runs always in error function. Why? Whats wrong?

aspx site:
<script type="text/javascript">
function AjaxTest() {
var codeVal = "hello world";
if (codeVal) {
$.ajax({
type: "POST",
url: "CheckAge",
data: { code: codeVal },
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (result) {
alert("in ajax success");
},
error: function () {
alert("error");
}
});
}
}
Its double checked that the javascript function is called.
Controller:
[HttpPost]
public JsonResult CheckAge(String code)
{
return Json("abc");
}
It ended up always in the ajax - error - function.
The Controller function isnt called anyway. Why?
Why get I always an error?
What is wrong?
Check your url that you are posting to. It seems that you are missing the controller part. E.g. it should read /{controller}/{action}.
If that script is directly in the view (i.e. not in an external javascript file) you could have something like:
$.ajax({
type: "POST",
url: <%= Url.Action("CheckAge", "ControllerName") %>,
data: { code: codeVal },
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (result) {
alert("in ajax success");
},
error: function () {
alert("error");
}
});
Also, I find it advantageous to use firebug to debug ajax stuff. You can set break points in your javascript and also see all the requests and responses.
HTHs,
Charles
EDIT: Try simplifying things... e.g.
$.post('<%= Url.Action("CheckAge", "ControllerName") %>',
{ code: codeVal },
function (data) {
alert("in ajax success");
},
"json");

Resources