I am trying to simply use jQuery's ajax method and method only call error callback.
$('form').submit(function() {
$.ajax({
url: this.action,
data: $(this).serialize(),
type: 'POST',
dataType: 'html',
success: function() {
debugger
alert('alert');
},
error: function(xhr, status, error) {
//status value is "error".
}
});
});
I am requesting to ASP.NET MVC action method. Method get request as expected and return partial view without any problem. Then jquery call error callback without specify detailed error info. I want to know some details about error then i can decide what can cause it.
Edit : I have tested below code and it works without problem. I just canceled form submit event.
$('form').submit(function(e) {
e.preventDefault();
$.ajax({
url: this.action,
data: $(this).serialize(),
type: 'POST',
dataType: 'html',
success: function() {
debugger
alert('alert');
},
error: function(xhr, status, error) {
//status value is "error".
}
});
});
Still answer is expecting right answer who can tell me reason of this error.
Could it be the reference this.action is undefined? Look at the network tab of your favorite dom inspector or just the error console of firebug. Does the POST request look as expected? (Check the URL, data sent, error code, etc)
$(this).attr('action') will certainly work, assuming this points to the form.
Related
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!
I have the following method in my Web API controller
[HttpGet]
[ActionName("GetByModule")]
public Object Get([FromUri]int id)
{
//var dblayer = new Db(WebConfigurationManager.ConnectionStrings["ConnectionString"]);
var annDb = new ContactsDB(WebConfigurationManager.ConnectionStrings["ConnectionString"]);
return annDb.GetContacts(id).Tables[0];
}
Here i the Jquery code which i am using to call the method
$.ajax({
type: "GET",
contentType: "application/json",
url: link,
data: null,
dataType: "json",
success: function (data) {
alert(data.d);
},
error: function (jqXHR, textStatus, err) {
alert("Error");
}
});
The URL which is getting called is
http://localhost:56834/api/Contacts/GetByModule?id=9
But i keep getting HTTP 405 Method Not Allowed on calling it from Jquery.
Any idea what i may be doing wrong.
Thanks in Advance
Can you make sure you are making a "GET" request? (maybe from Fiddler or browser's debug mode). I say this because you seem to setting the "contentType" property in your jquery, which ideally should not be present as you should not be sending body in a "GET" request. Could you share your full raw request(may be from Fiddler)?
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
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 :)
I'm wiring the following method to my document.ready function. However, the "myAutoCompleteURL.aspx" URL is never being accessed (I have a breakpoint on the page, and it's never being hit).
Anybody know why this isn't working? I'm new to the UI version of AutoComplete; I had previously only used the jquery-based (deprecated) version.
function myAutoComplete(myTextBox, myLabel, myHidden) {
var myType = $(myLabel).html();
$(myTextBox).autocomplete({
source: function (request, response) {
$.ajax({
type: 'POST',
dataType: 'json',
url: "../myAutoCompleteURL.aspx",
data: { q: request.term, type: myType },
success: function (myData) {
response($.map(myData, function (myItem) {
return { label: myItem.name, value: myItem.name, id: myItem.id }
}));
}
});
},
select: function (event, ui) {
$(myTextBox).val(ui.myItem.name);
$(myHidden).val(ui.myItem.id);
return false;
}
});
}
You can remove the ../ in your url. I used to have the same issue sometime ago.
Secondly have an error function in your ajax call. If it hits the error function, then there is some problem in your data and you need to correct that.
As #GregL mentioned in his comment, that you are using JSON and not application/json :)
Use Firebug and look for what URL is being hit instead. If nothing shows up in the console, then the javascript code is not working at all.