Ajax sucess function not called (returning data) - asp.net-mvc

I have a simple $.ajax call that i did a million times before
$.ajax({
type: "POST",
url: url,
data: data,
sucess: function (data) {
alert(data);
}
});
and a controller that accepts my data without a problem but i can't seem to return data to the sucess function.
[HttpPost]
public ActionResult MyAction(MyClass data)
{
//do something
return Content("blabla");
}
What seems to be the problem?
EDIT:
Everything was ok but i wrote sucess instead of success.
$.ajax({
type: "POST",
url: url,
data: data,
success: function (data) {
alert(data);
}
});

It could be that you need to return a json-p style response... if the javascript and server side code are running on different domains then this is almost certainly the case.
Take a looks at http://api.jquery.com/jQuery.ajax/ for some more details.
I suggest you try :
$.ajax({
type: "POST",
datatype: "text",
async: false,
url: url,
data: data,
sucess: function (data) {
alert(data);
}
});
The idea is if you ask for a synchronous call and request type of text then it should get around the jsonp / callback issue.
Hopefully worth a try :)

Related

How to send JSON to MVC API (using Ajax Post)

I am trying to post some data using Ajax, but it is not getting through when using content type of application/json (HTTP/1.1 406 Not Acceptable), however if I change the content type to 'application/x-www-form-urlencoded' then it does work.
Any ideas?
Ajax code extract:
$.ajax({
type: "POST",
data: {"hello":"test"},
url: "http://workingUrl/controller",
contentType : 'application/json',
cache: false,
dataType: "json",
.....
Web API 2:
public IHttpActionResult Post(testModel hello)
{
/// do something here
}
Model:
public class testModel
{
public string hello {get;set;}
public testModel()
{ }
}
Fiddler:
HTTP/1.1 406 Not Acceptable (In the IDE, I have a breakpoint in the Post method which is not hit).
I have tried adding a formatter to WebAPi.config, but no luck
config.Formatters.Add(new JsonMediaTypeFormatter());
Try with this JSON.stringify(TestData) as shown below -
var TestData = {
"hello": "test"
};
$.ajax({
type: "POST",
url: "/api/values",
data: JSON.stringify(TestData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
console.log(data);
console.log(status);
console.log(jqXHR);
alert("success..." + data);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
Output -
I've never specified contentType when I've done this and it's always works. However, if it works when you use 'application/x-www-form-urlencoded' then what's the problem?
I do see a couple thing off in your ajax. I would do this
$.ajax({
type: "POST",
data: {hello:"test"},
url: "http://workingUrl/controller/Post",
cache: false)}
For data, maybe quotes around the variable name will work but I've never had them there.
Next, the url in the ajax call doesn't have the name of your controller action. That needs to be in there.

I get 401 (Unauthorized) and Invalid HTTP status code 401 for the POST/OPTIONS call. Works on POSTMAN/RESTCLIENT

I'm new to Jquery and JqueryMobile . I'm having a bit of a trouble and was hoping someone here would help me. From what I understand, before I can actually do "POST", the browser does a "preflight" OPTIONS call. The problem with me is that the OPTIONS call fails with 401. I tested the api with RESTclient and POSTMAN and it works for just "POST".
I have one more block of code which is similar and makes a call to get the authorization token(authtoken). The only difference between this block and the other block are
1) Data block.
2) BeforeSend block.
The code for making the call.
jQuery.support.cors = true;
$.ajax({
type: "POST",
url: "https://myurl/api/APIName",
beforeSend: function (request)
{
request.setRequestHeader('AuthToken', "This is where I'll insert my authtoken");
request.setRequestHeader('Content-Type', "application/json");
$.mobile.showPageLoadingMsg();
},
complete: function () {
$.mobile.hidePageLoadingMsg();
},
data: {FirstName: "Albert", LastName: "Einstein"},
dataType: 'json',
success: function (response) {
alert(response.APIStatus.ErrorCode);
},
error: function () {
alert(response.APIStatus.ErrorCode;
}
});
The code to get Authorization Token. This block does its work without any issue.
jQuery.support.cors = true;
$.ajax({
type: "POST",
url: "https://myurl/api/THEURLTOAUTHENTICAREME",
beforeSend: function () {
$.mobile.showPageLoadingMsg();
},
complete: function () {
$.mobile.hidePageLoadingMsg();
},
data: {username: "Nickolas", Password: "Te$l#"},
dataType: 'json',
success: function (response) {
if (response.AuthToken) {
alert(response.AuthToken);
}else {
alert(response.APIStatus.Message);
}
},
error: function () {
alert("Woops");
}
});
I'm not the one whose working on the api piece of the application, but I do know the person who are working on it.
The first block needs to have an "authtoken" in the header and that's the reason why I'm doing request.setRequestHeader('AuthToken', "This is where I'll insert my authtoken");. Am I doing this wrong?
Hitting the API in Postman: http://i.imgur.com/rEk3rAr.png
Console/Inspector from Chrome: http://i.imgur.com/vfSHqR4.png
Please help me!

Success and Error functions not firing in Ajax call

Below is an Ajax call I'm using to determine which menu options to show to users (I know it's a flawed method, just up against a time crunch for a demo). When the page loads, I can step through the controller method in Visual Studio so I know it's hitting the controller and sending back the right information.
Looking at Chrome's Network console I can also see that the browser received the right response. However, neither the console.log or the alert are firing. Nothing in the success or error methods is executed either. Does anyone see what's going wrong?
View
$(document).ready(function ($) {
//Determine which links to show in navbar
window.onload = function () {
$.ajax({
type: 'GET',
url: '#Url.Action("CheckSecurity","Home")',
dataType: 'json',
succcess: function (data) {
console.log(data);
alert(data);
if (data == "admin") { $('#adminLink').show(); }
else if (data == "IT") { $('#ITLink').show(); }
else if (data == "viewer") { $('#viewerLink').show(); }
else if (data == "modifier") { $('#modifierLink').show(); }
},
error: function (data) {
alert("error");
}
});
};
Controller
[HttpGet]
public JsonResult CheckSecurity()
{
if (Security.IsAdmin(User)) return Json("admin", JsonRequestBehavior.AllowGet);
if (Security.IsItSupport(User)) return Json("IT", JsonRequestBehavior.AllowGet);
if (Security.IsViewer(User)) return Json("viewer", JsonRequestBehavior.AllowGet);
if (Security.IsModifier(User)) return Json("modifier", JsonRequestBehavior.AllowGet);
return Json("NA", JsonRequestBehavior.AllowGet);
}
Here are a couple screen shots of the Network and regular console in Chrome. Bother are from after I've stepped through the controller method and the program has returned a value back to the browser.
Network Console
Standard Console
There is an extra c in your
succcess:
So the response is a 200 request , but because you have no mapping for success defined, it is just never logged
It is success instead of succcess
NealR
Deprecation Notice:
The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks
will be deprecated in jQuery 1.8. To prepare your code for their
eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always()
instead.
Check the done, fail and always callbacks below.
$.ajax({
url: 'Your Url',
data: JSON.stringify(Parameter list),
type: 'POST',
contentType: 'application/json, charset=utf-8',
dataType: 'json',
beforeSend: function (xhr, opts) {
}
}).done(function (data) {
debugger;
}).fail(function (data) {
debugger;
}).always(function(data) {
alert("complete");
});
.ajax().always(function(a, textStatus, b){});
Replaces method .complete() which was deprecated in jQuery 1.8.
In response to successful transaction, arguments are same as .done() (ie. a = data, b = jqXHR) and for failed transactions the arguments are same as .fail() (ie. a = jqXHR, b = errorThrown).
This is an alternative construct for the complete callback function above. Refer to deferred.always() for implementation details.
$.ajax({
url: 'Your Url',
data: JSON.stringify(Parameter list),
type: 'POST',
contentType: 'application/json, charset=utf-8',
dataType: 'json',
beforeSend: function (xhr, opts) {
}
}).always(function(data) {
alert("complete");
});
.ajax().done(function(data, textStatus, jqXHR){});
Replaces method .success() which was deprecated in jQuery 1.8.
This is an alternative construct for the success callback function above. Refer to deferred.done() for implementation details.
$.ajax({
url: 'Your Url',
data: JSON.stringify(Parameter list),
type: 'POST',
contentType: 'application/json, charset=utf-8',
dataType: 'json',
beforeSend: function (xhr, opts) {
}
}).done(function (data) {
debugger;
});
.ajax().fail(function(jqXHR, textStatus, errorThrown){});
Replaces method .error() which was deprecated in jQuery 1.8.
This is an alternative construct for the complete callback function above. Refer to deferred.fail() for implementation details.
$.ajax({
url: 'Your Url',
data: JSON.stringify(Parameter list),
type: 'POST',
contentType: 'application/json, charset=utf-8',
dataType: 'json',
beforeSend: function (xhr, opts) {
}
}).fail(function (data) {
debugger;
});
Check here for more details
Check here for the documentation details

AJAX POST to MVC Controller showing 302 error

I want to do AJAX POST in my MVC View. I've written the following:
Script Code in View
$('#media-search').click(function () {
var data = { key: $('#search-query').val() };
$.ajax({
type: 'POST',
url: '/Builder/Search',
data: JSON.stringify(data),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('.builder').empty();
alert("Key Passed Successfully!!!");
}
});
});
Controller Code
[HttpPost]
public ActionResult Search(string key)
{
return RedirectToAction("Simple", new { key=key });
}
But on AJAX POST I am getting the 302 found Error
The '302' response code is a redirect. Your controller action explicitly returns a RedirectToAction, which simply returns a 302. Since this redirect instruction is consumed by your AJAX call and not directly by your browser, if you want your browser to be redirected, you will need to do the following:
$.ajax({
type: 'POST',
url: '/Builder/Search',
data: JSON.stringify(data),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.redirect) {
window.location.href = data.redirect;
}
$('.builder').empty();
alert("Key Passed Successfully!!!");
}
});
If not, you'll need to return something more meaningful than a redirect instruction from your controller.

Sending String Data to MVC Controller using jQuery $.ajax() and $.post()

There's got to be something I'm missing. I've tried using $.ajax() and $.post() to send a string to my ASP.NET MVC Controller, and while the Controller is being reached, the string is null when it gets there. So here is the post method I tried:
$.post("/Journal/SaveEntry", JSONstring);
And here is the ajax method I tried:
$.ajax({
url: "/Journal/SaveEntry",
type: "POST",
data: JSONstring
});
Here is my Controller:
public void SaveEntry(string data)
{
string somethingElse = data;
}
For background, I serialized a JSON object using JSON.stringify(), and this has been successful. I'm trying to send it to my Controller to Deserialize() it. But as I said, the string is arriving as null each time. Any ideas?
Thanks very much.
UPDATE: It was answered that my problem was that I was not using a key/value pair as a parameter to $.post(). So I tried this, but the string still arrived at the Controller as null:
$.post("/Journal/SaveEntry", { "jsonData": JSONstring });
Answered. I did not have the variable names set correctly after my first Update. I changed the variable name in the Controller to jsonData, so my new Controller header looks like:
public void SaveEntry(string jsonData)
and my post action in JS looks like:
$.post("/Journal/SaveEntry", { jsonData: JSONstring });
JSONstring is a "stringified" (or "serialized") JSON object that I serialized by using the JSON plugin offered at json.org. So:
JSONstring = JSON.stringify(journalEntry); // journalEntry is my JSON object
So the variable names in the $.post, and in the Controller method need to be the same name, or nothing will work. Good to know. Thanks for the answers.
Final Answer:
It seems that the variable names were not lining up in his post as i suggested in a comment after sorting out the data formatting issues (assuming that was also an issue.
Actually, make sure youre using the
right key name that your serverside
code is looking for as well as per
Olek's example - ie. if youre code is
looking for the variable data then you
need to use data as your key. –
prodigitalson 6 hours ago
#prodigitalson, that worked. The
variable names weren't lining up. Will
you post a second answer so I can
accept it? Thanks. – Mega Matt 6 hours
ago
So he needed to use a key/value pair, and make sure he was grabbing the right variable from the request on the server side.
the data argument has to be key value pair
$.post("/Journal/SaveEntry", {"JSONString": JSONstring});
It seems dataType is missed. You may also set contentType just in case. Would you try this version?
$.ajax({
url: '/Journal/SaveEntry',
type: 'POST',
data: JSONstring,
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});
Cheers.
Thanks for answer this solve my nightmare.
My grid
..
.Selectable()
.ClientEvents(events => events.OnRowSelected("onRowSelected"))
.Render();
<script type="text/javascript">
function onRowSelected(e) {
id = e.row.cells[0].innerHTML;
$.post("/<b>MyController</b>/GridSelectionCommand", { "id": id});
}
</script>
my controller
public ActionResult GridSelectionCommand(string id)
{
//Here i do what ever i need to do
}
The Way is here.
If you want specify
dataType: 'json'
Then use,
$('#ddlIssueType').change(function () {
var dataResponse = { itemTypeId: $('#ddlItemType').val(), transactionType: this.value };
$.ajax({
type: 'POST',
url: '#Url.Action("StoreLocationList", "../InventoryDailyTransaction")',
data: { 'itemTypeId': $('#ddlItemType').val(), 'transactionType': this.value },
dataType: 'json',
cache: false,
success: function (data) {
$('#ddlStoreLocation').get(0).options.length = 0;
$('#ddlStoreLocation').get(0).options[0] = new Option('--Select--', '');
$.map(data, function (item) {
$('#ddlStoreLocation').get(0).options[$('#ddlStoreLocation').get(0).options.length] = new Option(item.Display, item.Value);
});
},
error: function () {
alert("Connection Failed. Please Try Again");
}
});
If you do not specify
dataType: 'json'
Then use
$('#ddlItemType').change(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("IssueTypeList", "SalesDept")',
data: { itemTypeId: this.value },
cache: false,
success: function (data) {
$('#ddlIssueType').get(0).options.length = 0;
$('#ddlIssueType').get(0).options[0] = new Option('--Select--', '');
$.map(data, function (item) {
$('#ddlIssueType').get(0).options[$('#ddlIssueType').get(0).options.length] = new Option(item.Display, item.Value);
});
},
error: function () {
alert("Connection Failed. Please Try Again");
}
});
If you want specify
dataType: 'json' and contentType: 'application/json; charset=utf-8'
Then Use
$.ajax({
type: 'POST',
url: '#Url.Action("LoadAvailableSerialForItem", "../InventoryDailyTransaction")',
data: "{'itemCode':'" + itemCode + "','storeLocation':'" + storeLocation + "'}",
contentType: "application/json; charset=utf-8",
dataType: 'json',
cache: false,
success: function (data) {
$('#ddlAvailAbleItemSerials').get(0).options.length = 0;
$('#ddlAvailAbleItemSerials').get(0).options[0] = new Option('--Select--', '');
$.map(data, function (item) {
$('#ddlAvailAbleItemSerials').get(0).options[$('#ddlAvailAbleItemSerials').get(0).options.length] = new Option(item.Display, item.Value);
});
},
error: function () {
alert("Connection Failed. Please Try Again.");
}
});
If you still can't get it to work, try checking the page URL you are calling the $.post from.
In my case I was calling this method from localhost:61965/Example and my code was:
$.post('Api/Example/New', { jsonData: jsonData });
Firefox sent this request to localhost:61965/Example/Api/Example/New, which is why my request didn't work.

Resources