Why getting "Invalid JSON" added to my custom error message - asp.net-mvc

Invalid JSON:
Error 1 : Non-MDX format found.
Why I am getting the Invalid JSON with my custom error message.
My code is given bellow:
$('#btnCreateView').click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '#Url.Action("Create", "Mdx")',
data: $('form').serialize(),
dataType: "json",
success: function (result) {
alert("View Created Successfuly");
window.location = result.link;
},
error: function (jqXhr, textStatus, errorThrown) {
$('#ErrorMessageField').html(errorThrown);
}
});
})

In your controller action you seem to be returning a partial view:
return PartialView("Fail");
but in your AJAX request you inidicated
dataType: "json",
Obviously this is inconsistent. When jQuery attempts to parse the string returned from your controller action back into javascript object it fails because you are not sending JSON, you are sending partial HTML.

Related

Ajax success issue with React and Rails

I've got a form that I am trying to handle with React. This is the ajax method in the handleSubmit function:
$.ajax({
data: formData,
dataType: "json",
url: '/requests',
type: "POST",
success: function(data, status, xhr) {
console.log('SHOW HERE ON RESPONSE');
this.setState({
formSubmitted: true
});
}
});
When I click on submit, I can see the POST request go through and the server responds with a 200. But the success callback is never entered, I don't see the console message.
My rails controller's action is just a simple:
return render nothing: true, status: 200 if request.xhr?
The log with the server response includes:
Completed 200 OK in 11ms (Views: 2.5ms | ActiveRecord: 2.6ms)
However when I move the stuff from the success callback in the ajax request to a complete callback then I see this error in the console:
Uncaught TypeError: this.setState is not a function
You are seeing this error, because this behaves differently inside $.ajax()'s success callback, because jQuery uses it internally.
Suppose you are executing the following ajax call in response to a click function, then:
var $this = $(this);
$.ajax({
data: formData,
dataType: "json",
url: '/requests',
type: "POST",
success: function(data, status, xhr) {
console.log('SHOW HERE ON RESPONSE');
$this.setState({
formSubmitted: true
});
}
});
In the callback, this refers to the jqXHR object of the ajax call, instead of the context you expect (in this case, the component you're calling setState on).
$.ajax allows you to set the context explicitly to avoid these types of conflicts.
$.ajax({
data: formData,
dataType: "json",
url: '/requests',
type: "POST",
context: this,
success: function(data, status, xhr) {
console.log('SHOW HERE ON RESPONSE');
this.setState({
formSubmitted: true
});
}
});
Adding context: this will fix this issue.

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.

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 Serialize Need to get value

I have the following ajax serialize:
$.ajax({
type: "POST",
url: $form.attr('action'),
data: $form.serialize(),
error: function (xhr, status, error) {
ConfirmDialog('The page save failed.');
},
success: function (response) {
// need to retrieve an output value from the controller here
}
});
When it does a post, I am doing to an ActionResult method. How do I pass a value from the ActionResult so that I can get the value of it in when it is successful (under where it says success:function(response).
The output is in the response
success: function(response) {
alert( response );
}

Simple problem on jQuery ajax method

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.

Resources