Reputation: 3775
I would like a method on a button to execute a post redirect, and then have the page redirected by rails according to the controller's action.
Now I have the following method attached to a button on an angular page running in the page's Angular controller:
$scope.addClass = function(class_id_string) {
let payload = {class_id: class_id_string};
$http({
method: 'POST',
url: ADD_CLASS_ACCOUNT_URL,
data: payload
});
}
In my Rails controller, I have the following code:
def save_class_account
class_id = params[:class_id]
return redirect_to display_chart_path unless class_id.nil?
[...]
end
I have confirmed that the controller method is being called, and that the class_id parameter is coming through in the params collection. But still, nothing happens on the page when this method is called. I assume what is actually happening is that the entire page is being returned to the $http post method and ignored, instead of redirecting the browser, but I am not sure what is really going on here. But the page doesn't redirect as desired.
How can I get the redirect to happen?
Upvotes: 0
Views: 373
Reputation: 935
Angular is using Ajax calls using $http service. It means update a web page/Send data to server without reloading the page.
When you post data using HTTP Service, it will call Rails Controller methods and do the action and send the response back to Ajax.
Here page redirection doesn't work from Rails Controller. If you want to redirect page, Please do as shown below in the $http service itself.
$scope.addClass = function(class_id_string) {
let payload = {class_id: class_id_string};
$http({
method: 'POST',
url: ADD_CLASS_ACCOUNT_URL,
data: payload
}).then(function mySuccess(response) {
window.location = "Paste Redirection URL here"
}, function myError(response) {
"Show Error message here"
});
}
And also in the Rails Controller, When you call methods from Ajax, It will send JSON response as shown below
def save_class_account
class_id = params[:class_id]
render json: {url: display_chart_path, mgs: 'Successfully created'}, status: :created}
end
Upvotes: 1