I have this ajax call below
$(function(){
$.ajax({
type: "GET",
url: '/CafeTableDetails/GetTotalItems',
data: '{"url":"test"}',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
debugger
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
debugger
alert("some error");
}
});
});
and it can call the action method of my controller in C# MVC /CafeTableDetails/GetTotalItems
public ActionResult GetTotalItems()
{
bool isSuccess = true;
return Json(new { isUpdateSuccess = isSuccess, JsonRequestBehavior.AllowGet });
}
But as the action method return it back as Json, it falls into error. The XMLHttpRequest return state is 4, textStatus = "Error" and errorThrown is "Internal Server Error". How do I troubleshoot this further?
Your ajax method should be :
$.ajax({
type: "GET",
url: "/CafeTableDetails/GetTotalItems",
data: JSON.stringify({ url: 'test' }),
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function(response) {
console.log(response);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr.responseText);
}
});
and your controller action method will be:
[HttpGet]
public JsonResult GetTotalItems(string url)
{
// some business logic and return
return Json(url, JsonRequestBehavior.AllowGet);
}
Related
I have an ajax call that is of type post and I want to return the data by way of using return.
I have tried:
function GetDataById(Id){
return $.ajax({
type: "POST",
url: url,
data: JSON.stringify({ ID: Id }),
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, jqXHR) {
return data;
},
error: function (jqXHR, exception) {
}
});
}
and I have tried:
function GetDataById(Id){
$.ajax({
type: "POST",
url: url,
data: JSON.stringify({ ID: Id }),
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, jqXHR) {
return data;
},
error: function (jqXHR, exception) {
}
});
}
and what I am doing is:
(function(){
const data = GetDataById(208);
console.log(data);
})();
$.ajax() returns a promise. If you want to implement a function that gets the data after the call, you can simply return $.ajax() call and use promise's then and catch instead.
function GetDataById(Id){
return $.ajax({
type: "POST",
url: url,
data: JSON.stringify({ ID: Id }),
contentType: "application/json; charset=utf-8"
});
}
(function(){
GetDataById(208).then(data => console.log(data));
})();
I'm trying to get my server-side code to play nicely with some page templates we got from a design agency. All is good except that I'm struggling to implement the correct behaviour with the results of the form submission.
What should happen is, if the form submits successfully, some JQuery is triggered to animate into a success message. If not, the user should be redirected to an error page.
Here's the form submit script:
$.ajax({
type: 'POST',
data: JSON.stringify(userObject),
url: submitFormUrl,
contentType: 'application/json; charset=utf-8',
cache: 'false',
dataType: 'json',
success: function (data) {
if(data.Success){
console.log('success');
$('.thanks-msg').fadeIn(1000);
$('#market-message').hide();
}else{
console.log('Error');
}
}
});
And here's the controller action that it posts to:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Register(User userObject)
{
bool userExists;
try
{
if (ModelState.IsValid)
{
userExists = InsertUser(userObject); //calls a sproc
}
else
{
return CollectValidationErrors(); // collects all validation errors into a string
}
}
catch(Exception ex)
{
ViewBag.ErrorMessage = "Sorry! There has been an error " + ex.Message;
return Json(new { result = "Redirect", url = Url.Action("Error", "Home") });
}
if(userExists)
{
ViewBag.ErrorMessage = "This user already exists";
return Json(new { result = "Redirect", url = Url.Action("Error", "Home") });
}
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
What happens is that the form submission is received and the code inside executed successfully. But if an error state is returned, there's no redirect.
What am I doing wrong?
Try to use error property of ajax call:
$.ajax({
type: 'POST',
data: JSON.stringify(userObject),
url: submitFormUrl,
contentType: 'application/json; charset=utf-8',
cache: 'false',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
//Do Something
},
success: function (data) {
if(data.Success){
console.log('success');
$('.thanks-msg').fadeIn(1000);
$('#market-message').hide();
}else{
console.log('Error');
}
}
});
You do not send an error.
You can throw an Exception (forces HTTP Status 500 Internal Server Error) in the Controller Action. It will result that the success is not invoked, but the error function of ajax.
$.ajax({
type: 'POST',
data: JSON.stringify(userObject),
url: submitFormUrl,
contentType: 'application/json; charset=utf-8',
cache: 'false',
dataType: 'json',
success: function (data) {
if(data.Success){
console.log('success');
$('.thanks-msg').fadeIn(1000);
$('#market-message').hide();
}else{
console.log('Error');
}
},
error: function(function (xhr, status, errorThrown)){
// Do Redirect
}
});
Here is the code I am using to access my web API controller named Owner; the success function is not being called. Any ideas?
$.ajax({
type: "GET",
url: 'http://localhost:26533/api/Owner',
contentType: "application/json",
dataType: "jsonp",
success: function (response) { alert("yes"); }
});
Remove the contentType and dataType and check the response..
Here an example:
$.ajax({
type: 'GET',
url: 'http://localhost:26533/api/Owner',
success: function(data){
alert(data);
},
error: function(xhr, type, exception) {
// if ajax fails display error alert
alert("ajax error response type " + type);
}
});
With this you can see what's wrong...
I try to send a JSON object back to the server. This is my AJAX call:
$.ajax({
url: '/Home/NewService',
async: false,
type: "POST",
data: JSON.stringify(props),
error: function (jqXHR, textStatus, errorThrown) {
console.log("FAIL: " + errorThrown);
},
success: function (data, textStatus, jqXHR) {
console.log("SUCCES");
}
});
The evaluation of JSON.stringify(props) in the browser's debugger is
"[{"name":"firstName","value":"firstValue"}]"
This is the method in the controller which is being called:
[HttpPost]
public void NewService(dynamic json)
{
Response.Write(json);
}
The problem I have is that always the json variable from above is an empty object.
The success function gets called but when I debug the json var is displayed as empty.
Please tell me what I am doing wrong.
Thank you.
I don't think you can bind to a dynamic type the way you're trying to. You can try to create a class that maps your data, something like:
public class Content
{
public string Name { get; set; }
public string Value { get; set; }
}
Now in your action:
[HttpPost]
public ActionResult NewService(Content[] data)
{
// sweet !
}
And in your js like Olaf Dietsche said you need to specify your contentType:
var props = [
{ "Name": "firstName", "Value": "firstValue" },
{ "Name": "secondName", "Value": "secondValue" }
];
$.ajax({
url: '/Home/NewService',
contentType: "application/json",
async: true,
type: "POST",
data: JSON.stringify(props),
error: function (jqXHR, textStatus, errorThrown) {
console.log("FAIL: " + errorThrown);
},
success: function (data, textStatus, jqXHR) {
console.log("SUCCESS!");
}
});
According to jQuery.ajax(), the default content type is is application/x-www-form-urlencoded. If you want to send the data as JSON, you must change this to
$.ajax({
url: '/Home/NewService',
contentType: 'application/json',
...
});
Use the following code to solve this problem
Ajax Call
function SaveDate() {
var obj = {};
obj.ID = '10';
obj.Name = 'Shafiullah';
$.ajax({
url: '/Home/GetData',
dataType: "json",
type: "Post",
contentType: 'application/json',
data: JSON.stringify({ ID: obj.ID, Name: obj.Name }),
async: true,
processData: false,
cache: false,
success: function (data) {
alert(data.id + ' , ' + data.name);
},
error: function (xhr) {
alert('error');
}
});
}
My controller action method
[HttpPost]
public IActionResult GetData([FromBody] Employee employee)
{
return Json(employee);
}
I'm passing two string parameters from a jQuery ajax call to an MVC controller method, expecting a json response back. I can see that the parameters are populated on the client side but the matching parameters on the server side are null.
Here is the javascript:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "List/AddItem",
data: "{ ListID: '1', ItemName: 'test' }",
dataType: "json",
success: function(response) { alert("item added"); },
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
});
Here is the controller method:
Function AddItem(ByVal ListID As String, ByVal ItemName As String) As JsonResult
'code removed for brevity
'ListID is nothing and ItemName is nothing upon arrival.
return nothing
End Function
What am I doing wrong?
I tried:
<input id="btnTest" type="button" value="button" />
<script type="text/javascript">
$(document).ready( function() {
$('#btnTest').click( function() {
$.ajax({
type: "POST",
url: "/Login/Test",
data: { ListID: '1', ItemName: 'test' },
dataType: "json",
success: function(response) { alert(response); },
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
});
});
});
</script>
and C#:
[HttpPost]
public ActionResult Test(string ListID, string ItemName)
{
return Content(ListID + " " + ItemName);
}
It worked. Remove contentType and set data without double quotes.
If you have trouble with caching ajax you can turn it off:
$.ajaxSetup({cache: false});
You need add -> contentType: "application/json; charset=utf-8",
<script type="text/javascript">
$(document).ready( function() {
$('#btnTest').click( function() {
$.ajax({
type: "POST",
url: "/Login/Test",
data: { ListID: '1', ItemName: 'test' },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(response) { alert(response); },
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
});
});
});
</script>
var json = {"ListID" : "1", "ItemName":"test"};
$.ajax({
url: url,
type: 'POST',
data: username,
cache:false,
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success:function(response){
console.log("Success")
},
error : function(xhr, status, error) {
console.log("error")
}
);
In my case, if I remove the the contentType, I get the Internal Server Error.
This is what I got working after multiple attempts:
var request = $.ajax({
type: 'POST',
url: '/ControllerName/ActionName' ,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ projId: 1, userId:1 }), //hard-coded value used for simplicity
dataType: 'json'
});
request.done(function(msg) {
alert(msg);
});
request.fail(function (jqXHR, textStatus, errorThrown) {
alert("Request failed: " + jqXHR.responseStart +"-" + textStatus + "-" + errorThrown);
});
And this is the controller code:
public JsonResult ActionName(int projId, int userId)
{
var obj = new ClassName();
var result = obj.MethodName(projId, userId); // variable used for readability
return Json(result, JsonRequestBehavior.AllowGet);
}
Please note, the case of ASP.NET is little different, we have to apply JSON.stringify() to the data as mentioned in the update of this answer.