skwidbreth skwidbreth - 3 months ago 63x
Ajax Question

Rails - AJAX window.location redirect not working

In my Rails app, stringified JSON form input is passed to a controller via AJAX - on success, the user is to be redirected to a summary page, but the AJAX redirect doesn't seem to be working...

url: "report/submission",
type: "POST",
beforeSend: function(xhr) {xhr.setRequestHeader("X-CSRF-Token", $("meta[name='csrf-token']").attr("content"))},
data: {"report" : reportParameter},
success: function(response) {
window.location.href = "/report/summary";

and the associated controller

def submission
@incomingReport = ActiveSupport::JSON.decode(params[:report])

@newReportIDArray =

@incomingReport.each do |x|

hash =

@new_report =


Everything else seems to work just fine - the data is entered, but the redirect does not trigger. I've searched all around and it looks like this is the syntax that everyone says to use, but it doesn't seem to work for me. I'm sure that I am doing something wrong, but I'm not sure what.

Editing to clarify problem/solution
During a chat with @Jonathan and @Kumar, I noted that"/report/summary")
did work correctly - @Jonathan suggested that I just try
before the ajax call, and to my surprise, the script from a function from elsewhere in my app was logged. Big shocker now - THE FUNCTION WAS CALLED
!!! Renaming the function and then restarting the app in a new window solved the problem. Learn from my mistake, kids - don't name a function


Ruby isn't my first language but it doesn't look like you're sending a response back. Try returning something or putsing. Look up how to do that with rails, a proper response. Maybe render json: [success: 200] or something like that. Maybe it's irrelevant. In any case, if it's not working try changing success for complete and log out the response to debug. The complete will always fire, but success won't always.

Try this:

respond_to do |format|
  format.json do
    render json: {
      success: 200

In your AJAX setup, add "datatype": "json".

You could improve the response to conditionally send a failure like success: 500 if something went wrong.

You don't really need respond_to block here because you're always expecting JSON, but that's the kind of format that's often used in Rails if not mistaken.

If that doesn't work just use the render json: part as that is definitely a return.

Update Further from our discussion it turns out that after making a robust Ajax call and tweaking the action, the final hurdle was a window.location that was not working. The cause of the problem was that location had been rebound to another function. All that needed to be done in the end is to rename that custom function and Bob's your uncle.