Ajax Serialize Need to get value - asp.net-mvc

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 );
}

Related

MVC Parallel transactions and session objects

I can't get the session values when I start a different operation while an operation is in progress like below;
$.ajax({
type: 'GET',
cache: false,
url: '/Home/StartOperation',
dataType: 'json',
data: { customerId: $("#txtCustomerId").val() },
error: function (xhr, status, error) {
$("#textlabel").text(error)
},
success: function (result) {
$("#textlabel").text(result.Result)
}
});
Controller side;
public ActionResult StartOperation(string customerId)
{
Session["OperationId"] = "operationid";
// Some web api transactions (This operations takes a few minutes.)
var data = new { Result = "Operation Completed." };
return Json(data, JsonRequestBehavior.AllowGet);
}
I am sure about Session["OperationId"] is not null, and then I call my cancel action while web api transactions in progress;
$(function () {
$('#btnCancelLogin').on('click', function () {
$.ajax({
type: 'GET',
cache: false,
url: '/Home/CancelOperation'
});
});
});
Controller side;
public ActionResult CancelOperation()
{
String operationId = Session["OperationId"] as String // return null
//Cancel operations
}
Why Session["OperationId"] is always null on CancelOperation() method ? Thanks for advices.
if you take data from ajax side for start operation you should use post. Actually your ajax type is incorrect.
$.ajax({
type: 'POST',
cache: false,
url: '/Home/StartOperation',
dataType: 'json',
data: { customerId: $("#txtCustomerId").val() },
error: function (xhr, status, error) {
$("#textlabel").text(error)
},
success: function (result) {
$("#textlabel").text(result.Result)
}
});
Or if you want to take data from controller you should return data
public ActionResult StartOperation(string customerId)
{
Session["OperationId"] = "operationid";
// Some web api transactions
return json(customerId);
}
also your ajax should be like this
$.ajax({
type: 'GET',
cache: false,
url: '/Home/StartOperation',
dataType: 'json',
data: { customerId: $("#txtCustomerId").val() },
error: function (xhr, status, error) {
$("#textlabel").text(error)
},
success: function (result) {
$("#textlabel").text(result.Result)
}
});

jquery ajax always get error section when try to pass json object(simple)

var jso = { "namep": "a", "age": "10" };
$.ajax({
type: 'POST',
url: '#Url.Action("gettestjsn","Cart")',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(jso),
success: function (data) {
alert(data.namep);
},
error: function () { alert("err"); }
});
this code always go to error function and i does not fire my mvc action,aslo i have a prop class which does match to this json obj. why is that i m new to json and jquery ajax please help
this is my action
public ActionResult gettestjsn(jso jso)
{
//do some here
return View();
}
Remove contentType from the ajax attributes and add
dataType: 'json',
This will work if the url is correct
this is how your code should look like
var jso = { "namep": "a", "age": "10" };
$.ajax({
type: 'POST',
url: '#Url.Action("gettestjsn","Cart")',
data: jso,
success: function (data) {
alert(data.namep);
},
error: function () { alert("err"); }
});
Also i would refrain from using alerts. Either use console.log or debug using the inspector in your browser (comes inbuilt with chrome) to see what your data from the server looks like.
Try like this,
var jso = { "namep": "a", "age": "10" };
$.ajax({
type: 'POST',
url: '/Cart/gettestjsn',
contentType: 'application/json; charset=utf-8',
data: jso,
success: function (data) {
alert(data.namep);
},
error: function (jqxhr, status, error) { alert("err:" + status + ':' + error); }
});
and your action should be,
[HttpPost]
public ActionResult gettestjsn(jso jso)
{
//do some here
return View();
}
Hope it helps.

synchronous ajax calls from jquery to mvc

I have to generate several graphs and each graph data I should get it from mvc controller.
so I am using the below jquery to do ajax calls from jquery to mvc
$(".emailgraphs").each(function () {
YAHOO.Report.Print("Email", $(this).attr("responsefield"), $(this).attr("id"), $(this).attr("metricid"));
});
Print: function (name, graphid, divid, metricid) {
try {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: m_oReport.ds,
data: JSON.stringify(m_oReport.printp(name, graphid, metricid)),
beforeSend: function () {
//Displays loading image before request send, till we get response.
//$("#" + divId).addClass("loading");
},
success: function (data) {
// if they define a success function (s), call it and return data to it.
if (typeof m_oReport.prints === "function") {
m_oReport.prints(data, divid, name)
}
},
error: function (err) {
$("#" + divid).html(err);
}
});
}
catch (err) { alert("catch"); }
}
The problem is the calls are asynchronous. sometimes I am getting one graph and sometime 2 like that and sometimes nothing.
Is there any fix for this?
try to use something like this
function getDataSync() {
return $.ajax({
type: "POST",
url: remote_url,
async: false,
}).responseText;
}

Why getting "Invalid JSON" added to my custom error message

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.

How to return bool from MSFT-MVC action to jQuery $.ajax()

I am calling a MSFT-MVC action using jQuery $.ajax()
public bool SetActivePatient(string patientID)
{
which returns a boolean.
The $.ajax() call is always firing the error option.
$.ajax({
type: 'POST',
url: '/Services/SetActivePatient',
data: { 'patientID': id },
dataType: 'text',
success: function(returnVal) {
if (returnVal == "True") {
...
}
else {
alert('Error setting active patient return value, PatientID=' + id);
}
},
error: function() {
alert('Error in ajax call');
}
});
The MVC action is called and works correctly, returning "True" as a .NET bool. Looking in FireBug the response is "True" from the MVC action. Do I have the wrong dataType?
Change your error signature to:
error:function (xhr, ajaxOptions, thrownError)
{
//inspect xhr.responseText, thrownError variables to find out what is the exact error.
//Once we know the exact error, it could be debugged further.
};

Resources