Perform RedirectToAction in AJAX post call - asp.net-mvc

I have passed the Model object from the View to controller action method through the AJAX post call. Inside the action method, we have a some business logic to be perform based on the received input fields. if business logic fails, then we will return the error message to user else, then we need to redirect the user to some other page. in this case, Redirection to other page is not working in the AJAX post call.
Could you please provide me the any alternative approach on this?
Note:- i need to perform this post operation in the AJAX call.
Thanks

You can simply check if the status is an error and if so redirect in your ajax call
$.ajax({
url: '/ThingToDo/',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: data,
success: function (status) {
if (!status.error) { alert(!status.error); }
else { window.location.href = "/Redirecthere/"; }
}

Related

What do I do with low Scores in reCAPTCHA v3?

I have set up reCAPTCHA v3 on my ASP.NET MVC project. Everything is working fine and is passing back data properly.
So the code below depends on another dll I have, but basically, the response is returned in the form of an object that shows everything that the JSON request passes back, as documented by https://developers.google.com/recaptcha/docs/v3
It all works.
But now that I know the response was successful, and I have a score, what do I do? What happens if the score is .3 or below? Some people recommend having v2 also set up for secondary validation (i.e. the 'choose all the stop signs in this picture' or 'type the word you see'). Is that really the only 'good' option?
Obviously the code isn't perfect yet. I'll probably handle the solution in the AJAX call rather than the controller, but still. What should I do if the score is low?
I read this article
reCaptcha v3 handle score callback
and it helped a little bit, but I'm still struggling to understand. I don't necessarily need code (although it would never hurt) but just suggestions on what to do.
VIEW:
<script src="https://www.google.com/recaptcha/api.js?render=#Session["reCAPTCHA"]"></script>
grecaptcha.ready(function () {
grecaptcha.execute('#Session["reCAPTCHA"]', { action: 'homepage' }).then(function (token) {
$.ajax({
type: "POST",
url: "Home/Method",
data: JSON.stringify({token: token }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log('Passed the token successfully');
},
failure: function (response) {
alert(response.d);
}
});
});
});
CONTROLLER:
[HttpPost]
public void ReCaptchaValidator(string token)
{
ReCaptcha reCaptcha = new ReCaptcha();
Models.ReCaptcha response = new Models.ReCaptcha();
response = reCaptcha.ValidateCaptcha(token);
//response returns JSON object including sucess and score
if (response.Success)
{
//WHAT DO I DO HERE????
}
}
Ended up getting the answer from another forum. Basically, the answer is "anything you want". There is no right or wrong when handing a successful response.
So what could be done, is if the response is successful and CAPTCHA doesn't throw a flag, do nothing. But if CAPTCHA is unhappy, you could display an alert or a banner that says 'could not process', or you could even add in CAPTCA version 2, which would make them do the picture test or the 'I am not a robot' checkbox, etc.

How do you pass devise authentication details to a rails controller action?

I have a controller action that is expected to be called by jquery. Here's the call:
$.ajax({
url: "/comments.json",
type: "POST",
dataType: "json",
data: {
commentable_id: $("#addCommentForm").attr("data-site-update-id"),
commentable_type: 'SiteUpdate',
content: $("#addCommentForm textarea#content").val()
},
success: function(comment) {
}
});
It works just fine, but for some reason, "current_user" is nil inside of the controller. If I force authenticate_user! as a filter, rails returns an HTTP Unauthorized.
How can I pass the authentication details so that this controller action works with devise? Even better, is there a way I can make this transparent? I don't want to pass the authentication details over and over for each ajax request...
In Java, once a user is logged in... they are logged in. You don't have pass anything from url to url anymore - it's in a session somewhere and it's all occuring transparently. Is there a way I can do this with rails? I don't want to focus on these details.
Thanks
EDIT: The solution is to add the following to your javascript somewhere:
$(document).ajaxSend(function(e, xhr, options) {
var token = $("meta[name='csrf-token']").attr("content");
xhr.setRequestHeader("X-CSRF-Token", token);
});
Devise does maintain sessions.
This may be your problem.

Show loading screen while performing task in Rails 3

If my 'create' action takes a while to load (due to doing an API call and then a calculation) what's the best way to show the user a 'loading screen' while this task is performed in the background?
Write some AJAX magic ;) Show the loading image when activated and hide it when the AJAX call is complete. And if you don't want to use AJAX, well, hmm, you could check out this:
http://yehudakatz.com/2010/09/07/automatic-flushing-the-rails-3-1-plan/
There's also a gem out there, that somewhat does that.
But I don't have any experience with that.
I would go for the AJAX method =)
EDIT:
Yeah, you should call the create action with AJAX in jQuery. You could do:
function create() {
$('#loading_image').show();
$.ajax({
type: 'POST',
url: /* URL to your create action: e.g. '/user/create/' */,
data: $('form').serialize(),
success: createSuccessHandler,
error: createErrorHandler,
complete: hideLoadingImage
});
}
function createSuccessHandler(data) {
alert("User created!")
}
function createErrorHandler(data) {
alert("It failed, ffs!")
}
function hideLoadingImage() {
$('#loading_image').hide()
}

Asp.NET MVC Ajax-Post a FORM and Ajax-Get

I'm stuck, who can help me out? In my LogOn.aspx View I've login controls (Username, Password, RememberMe) inside a FORM tag:
<form id="loginform" method="post" action="/Account/LogOn/">
Below that, I've a hidden DIV with a OPTION dropdownlist and a confirm-button, with a onclick_event:
$.ajaxSetup({ cache: false });
$.ajax({
type: "GET",
url: "/Account/SetCompanyAndContinue",
data: "{ 'id' : '1'}",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
First, the user logs in. In jQuery, I post the login credentials via AJAX:
var loginCred = new Object();
loginCred.Username = $('#userName').val();
loginCred.Password = $('#password').val();
loginCred.RememberMe = $('#rememberMe').checked;
var myJsonObject = JSON.stringify(loginCred);
$.ajaxSetup({ cache: false });
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Account/LogOnAjax/",
data: myJsonObject,
dataType: "json",
success: function(data) {
PostCredentialsSuccess(data);
}
});
This POST works perfect. The breakpoint at the Controller Action is hit by the debugger and returns a JSON object of data. I put this JSON data into the OPTION dropdownlist. This Option Dropdownlist is then presented to the user. Then, when the user clicks the confirm-button, a second AJAX call is made:
$.ajaxSetup({ cache: false });
$.ajax({
type: "GET",
url: "/Account/SetCompanyAndContinue",
data: "{ 'id' : '1'}",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
I would expect that the Controller Action named "SetCompanyAndContinue" gets hit:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult SetCompanyAndContinue(string id)
{
SessionAdapter.CustomerID = Convert.ToInt32(id);
return null;
}
But it ain't happening, instead, the default Controller Action get's hit the first time:
public ActionResult LogOn()
{
return View();
}
BUT(!) the second time I click (the same) confirm-button the Controller Action finally hits [SetCompanyAndContinue].
Can somebody tell me what I'm doing wrong? Many thanks in advance.
you need to pass the data property as a javascript object not as a string
$.ajax({ type: "GET",
url: "/Account/SetCompanyAndContinue",
data: ({id : 1}),
contentType: "application/json; charset=utf-8",
dataType: "json" });
i recommend to use firebug to look at the actual HTTP Request that do get send from jQuery, that way tiny mistakes like this get obvious very quickly.
hth
try using a link to submit instead of a normal submit button, it probably has a conflict somewhere between the click, ajax and form.
I didn't know whether I got the correct information. But as per your description any click on the "submit" button will try to do the "Post" method and not the "Get" method.
The "Get" call is done only when you visit the page at first or refresh the url.
Use the link button to do the "Get" action.
That's why in your sample its calling "/Account/LogOnAjax/" this action with "Post" method.
To compare the different GET requests you can use a debugging HTTP proxy like Fiddler or Charles.
marc.d was right
A general rule of thumb (at least it works for me): if your action isn't being hit like you expect, it's likely something is wrong with your route params or if you're falling through to the default route, the form data being sent with the post isn't what's expected. I was using $(this).serialize() as a JQuery data arg for a $post and one of my hidden form fields was empty. The action, which wasn't included in any route, (I was letting it fall through to the default in this case), never saw the post.
Stupid mistake from my behalf:
i've added a cookie to the response-stream which made the webbrower behave unpredictable.
i've forgot to mark this one as answered

JSON parameters auto. convert to lowercase when ajax request made to MVC action method?

Would anybody know why my parameter is being "converted" to lowercase when it hits my ASP.NET MVC controller action?
I can only assume it is being converted as looking at data value just prior to the ajax request it is in correct casing, but then when debugging my action method within .NET during the ajax request and checking the incoming parameter, it has been converted to lowercase?
This is causing dramas for me as I need to keep the case entered by the user.
Code below, example data being sent is: 'SimpleDATATest1'
$.ajax({
type: "GET",
url: "/configuration/module-message-types/GetTranslation",
data: "messageToTranslate=" + messageToTranslate,
dataType: "json",
success: function(result) {
// Insert the returned HTML into the <div>.
$('#TranslationResponse').html(result.message).fadeIn('fast');
$("#" + ajaxLoadImgId).hide();
},
error: function(req, status, error) {
$('#TranslationResponse').text('Could not load example translation message, please try reloading the page.');
$("#" + ajaxLoadImgId).hide();
}
});
And MVC Action method signature is:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetTranslation(string messageToTranslate)
However, when checking the value of 'messageToTranslate' it is returning as: 'simpledatatest1'.
How can I stop whatever forces at work from changing this?
Nevermind... I found this that I implemented was the culprit:
http://www.coderjournal.com/2008/03/force-mvc-route-url-lowercase/

Resources