I'm trying to call an Action from javascript with Ajax but when i publish the site the request returns me a 302 error
this is the javascript call
$("#buyButton").click(function () {
$.ajax({
type: "POST",
url: "/TessileCart/Buy?offerType=" + '#ViewBag.offerType' + "&requestPath=" + '#ViewBag.requestPath' + "¤cy=" + currentCurrency,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: ({
}),
error: function (data) {
},
success: function (data) {
window.location = '/'
}
});
});
and this is the Action server side
public ActionResult Buy(string offerType, string requestPath, string currency)
{
try
{
decimal codStore = Convert.ToDecimal(HttpContext.Session[Global.CodStore]);
string userName = HttpContext.Session[Global.UserName].ToString();
cartRep.CheckOut(codStore, userName, System.Web.HttpContext.Current, currency);
return RedirectToAction("Index", "Home", new { offerType = offerType });
}
catch (Exception ex)
{
Global.log.WriteLog(this.GetType().Name, "Buy", "", ex, Session[Global.UserName].ToString());
return RedirectToAction("Index", "Cart", new { offerType = offerType, requestPath = requestPath, error = Global.ErrorMex });
}
}
can someone explain me how to resolve?
Thanks,
Federico
You are calling a post method, but using the get method way.
the url should stop until /buy
url: "/TessileCart/Buy",
before that build the post parameter, before the $.ajax call:
let senddata = {
offerType: #ViewBag.offerType,
requestPath: #ViewBag.requestType,
currency: currentCurrency
}
the rest of parameter, send it as json as input to data
data: JSON.stringify(senddata),
and last decorated your action with HttpPost
[HttpPost]
public ActionResult Buy(...)
Related
I have page witha table and a button. When I push the button a partial view loads into a div. On the partial view there is an ajax form which sends back the partial view with validation error in case of wrong form data but I want to remove the partial view and refresh the table in case of successful insertion.
The form header:
#using (Ajax.BeginForm("RequestInsert", "Home", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "requestForm" }, new { id = "reqins" }))
The jQuery submit event handler on the host page:
$(document).on('submit', '#reqins', function (e) {
e.preventDefault();
let data = $("form :input").serializeArray();
$.ajax({
url: '#Url.Action("RequestInsert", "Home")'
,type: "POST"
,data: { "__RequestVerificationToken": token, "model": data }
})
.done(function (data) {
$("#requestForm").html("");
table.search('').columns().search('').draw();
})
.fail(function (jqXHR, textStatus) {
alert("fail");
});
});
I am a little confused with the partial view and ajax form.
Since your objective is checking validation status from AJAX response, you can use if condition against AJAX response as shown below:
$('#reqins').submit(function (e) {
e.preventDefault();
let data = $('form :input').serializeArray();
$.ajax({
url: '#Url.Action("RequestInsert", "Home")',
type: 'POST',
data: { "__RequestVerificationToken": token, "model": data },
success: function (result) {
// check valid response
if (result.invalid) {
$('#requestForm').html(result.form);
}
else {
$('#requestForm').html(result);
table.search('').columns().search('').draw();
}
},
error: function (jqXHR, textStatus) {
alert("fail");
}
});
});
Then inside controller action you can return both validation status and partial view using Controller.Json() with RenderViewToString() extension method provided here:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RequestInsert(ViewModel model)
{
// perform validation here
// assume IsValid is a boolean returned from validation status
if (IsValid)
{
// successful validation, return empty form
return PartialView("FormPartialView");
}
else
{
// validation failed, return failure status and previously-filled form
return Json(new { invalid = true, form = RenderViewToString(PartialView("FormPartialView", model)) });
}
}
try this and remove the Ajax Helper
$('#reqins').on('click', function () {
let data = $("form :input").serializeArray();
$.ajax({
url: '#Url.Action("RequestInsert", "Home")'
,type: "POST"
,data: data
,success:function (result) {
$("#requestForm").html(result);
}});
});
modify your action to this
public JsonResult RequestInsert()
{
try
{
return Json(new { success = true, result = PartialView("Prtialview") });
}
catch (Exception ex)
{
return Json(new { success = false, result = ex.ErrorMessage });
}
}
and then modify the client side as following
$('#reqins').on('click', function () {
let data = $("form :input").serializeArray();
$.ajax({
url: '#Url.Action("RequestInsert", "Home")'
,type: "POST"
,data: data
,success:function (result) {
if(result.succuss)
{
$("#requestForm").html(result);
}
else
{
alert("Error");
}
}});
});
I am trying to send my userid and password to my login Controller Action method.
//Login button click code
$("#btnLogin").click(function () {
var userCrdential = {
UserName: $("inputEmail3").val(),
Password: $("inputPassword3").val()
};
$.ajax({
type: "POST",
url: "/Home/Login",
content: "application/json; charset=utf-8",
dataType: "json",
data: userCrdential,
success: function (res) {
// alert("data is posted successfully");
if (res.success == true)
alert("data is posted successfully");
else {
// alert("Something went wrong. Please retry!");
}
},
error: function (xhr, textStatus, errorThrown) {
alert(xhr.statusMessage);
}
});
});
and in my home Controller I have login Action method
[HttpPost]
[ActionName("Login")]
public ActionResult Login(User userCrdential)
{
string userIdtest = userCrdential.UserName;
string userPasswordtest = userCrdential.Password;
var result=false;
if (userIdtest != null && userPasswordtest != null)
{
result = true;
}
else
{
result = false;
}
return Json(result);
//return RedirectToAction("Index");
}
but my action method is not invoking...
You need to change content to contentType and call JSON.stringify on your data:
$.ajax({
type: "POST",
url: "/Home/Login",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(userCrdential),
...
});
See jQuery.ajax
Just change it from:
var userCrdential = {
UserName: $("inputEmail3").val(),
Password: $("inputPassword3").val()
};
to:
var userCrdential = "UserName=" + $("inputEmail3").val() + "&Password=" + $("inputPassword3").val();
all other things is ok in your code, but make sure your controller parameter having the same parameters passing here i.e. UserName and Password.
however you need to check user input before calling ajax.
You should never hard-code URLs in MVC.
Instead use #Url.Action.
url: ('#Url.Action("Login", "Home")',
userCrdential needs to be JSON encoded:
JSON.stringify(userCrdential)
Also, for the same of your sanity, please use the fail method.
$.ajax("url")
.done(function() {
alert("success");
})
.fail(function() {
alert("error");
})
One last note, success is deprecated as of jQuery 1.8; you should use done instead.
I have a JavaScript method dotrack(). I am calling an action UpdateJson from the JavaScript through AJAX. I am passing JSON data type and the method will return true/false. After executing system is going to success block but the returned value is not true/false.
My question is, whether the system is calling the action properly or not.
function doTrack() {
var D = { 'pageUrl': PageURL, 'linkUrl': linkURL, 'linkName': linkText, 'linkType': ControlType, 'leadId': LeadID, 'userType': UserType, 'portalId': PortalID, 'languageId': LanguageID, 'countryId': CountryID };
D = JSON.stringify(D);
$.ajax({
type: "POST",
url: "portal/UpdateJson",
data: D,
contentType: "application/json; charset=utf-8",
success: function (result) {
if(result == true)
alert("Success");
else
alert(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError + " :: " + ajaxOptions);
//alert('unable to complete ajax request.');
}
});
}
Controller is Portal & Action is UpdateJson:
[HttpPost]
public ActionResult UpdateJson(string pageUrl, string linkUrl, string linkName, string linkType, string leadId, string userType, string portalId, string languageId, string countryId)
{
//do stuff
return Json(true);
}
Please help.
Your ajax code is working fine.
You just need to use the result variable directly instead of result.val.
success: function (result) {
exists = (result);
alert(exists);
}
If you want to use val property, you need to return an object that has val property too.
return Json(new { val = true });
Also you should use Url.Action for preventing incorrect URL.
url: "#Url.Action("UpdateJson", "portal")"
i have a ajax call which calls the ControllerName "Floor" and ActionMethod "GetHotelingList".i have a Dropdown list facility. when i select option from the Dropdownlist list the control goes to ajax call.based on selection value, the Webgrid must be displayed. #grdHoteling is Webgrid id.
$.ajax({
type: 'GET',
url: '/Floor/GetHotelingList',
cache: false,
contentType: 'application/html; charset=utf-8',
dataType: 'html',
data: { floorId: floorId },
success: function (data) {
debugger;
$("#grdHoteling").val(data);
//debugger;
//$("#grdHoteling").html(data);
},
complete: function () {
},
error: function () {
if (facilityName.indexOf('-') != -1) {
$('#floor').empty();
return;
}
else
alert("Error in generating hoteling information");
}
});
Here is the ActionMethod GetHotelingList value is paased floorId for some fileration.
public List<IDictionary> GetHotelingList(int floorId)
{
var model = new List<IDictionary>();
using (var context = new FloorContext())
{
try
{
model = ListHotelingByFloorId(context, floorId);
}
catch (Exception ex)
{
}
}
return model;}
On Success of the ajax call, when i check through debugger am getting data as "System.Collections.Generic.List`1[System.Collections.IDictionary]" and child cannot be evaluated.
kindly help...!
thanks...!
I use $.ajax() to poll an action method every 5 seconds as follows:
$.ajax({
type: 'GET', url: '/MyController/IsReady/1',
dataType: 'json', success: function (xhr_data) {
if (xhr_data.active == 'pending') {
setTimeout(function () { ajaxRequest(); }, 5000);
}
}
});
and the ActionResult action:
public ActionResult IsReady(int id)
{
if(true)
{
return RedirectToAction("AnotherAction");
}
return Json("pending");
}
I had to change the action return type to ActionResult in order to use RedirectToAction (originally it was JsonResult and I was returning Json(new { active = 'active' };), but it looks to have trouble redirecting and rendering the new View from within the $.ajax() success callback. I need to redirect to "AnotherAction" from within this polling ajax postback. Firebug's response is the View from "AnotherAction", but it's not rendering.
You need to consume the result of your ajax request and use that to run javascript to manually update window.location yourself. For example, something like:
// Your ajax callback:
function(result) {
if (result.redirectUrl != null) {
window.location = result.redirectUrl;
}
}
Where "result" is the argument passed to you by jQuery's ajax method after completion of the ajax request. (And to generate the URL itself, use UrlHelper.GenerateUrl, which is an MVC helper that creates URLs based off of actions/controllers/etc.)
I know this is a super old article but after scouring the web this was still the top answer on Google, and I ended up using a different solution. If you want to use a pure RedirectToAction this works as well. The RedirectToAction response contains the complete markup for the view.
C#:
return RedirectToAction("Action", "Controller", new { myRouteValue = foo});
JS:
$.ajax({
type: "POST",
url: "./PostController/PostAction",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function (result) {
if (result.responseText) {
$('body').html(result.responseText);
}
}
});
C# worked well
I just changed the JS because responseText was not working for me:
$.ajax({
type: "POST",
url: posturl,
contentType: false,
processData: false,
async: false,
data: requestjson,
success: function(result) {
if (result) {
$('body').html(result);
}
},
error: function (xhr, status, p3, p4){
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
console.log(err);
}
});
You could use the Html.RenderAction helper in a View:
public ActionResult IsReady(int id)
{
if(true)
{
ViewBag.Action = "AnotherAction";
return PartialView("_AjaxRedirect");
}
return Json("pending");
}
And in the "_AjaxRedirect" partial view:
#{
string action = ViewBag.ActionName;
Html.RenderAction(action);
}
Reference:
https://stackoverflow.com/a/49137153/150342