Redirecting to another page via a json call

I'm using the jquery file upload utility in my app. If I have some code like the following normally in rails...

if @course_module.save
  flash[:success] = "Class created!"
  redirect_to course_course_modules_path(@course)
else
  render 'new'
end

It will display error messages if there are errors in my form, or redirect to another page if it saved successfully. But this is not so when the page is submitted through the jquery plugin. The reason is it requires a json object to be returned....something like

         format.json {  
          render ':json => [@course_module.to_jq_upload].to_json ' 
        }

How would I instead of returning json, do the first code snippet instead? Either by redirecting if the save is successful, or display error messages if it is not? I've tried something like the following...

render 'new'

But that didn't work.

Answers


The normal ajax call has a success and error methods, just add to the json response a redirect_url key having the path you want to go to as the value and inside the success method redirect to this url.

$.ajax({
 type: "GET",
 url: '/path to your controller',
 datatype: 'json',
 success: function(data) {
   window.location.href = data.redirect_url
 };

});

and your json response should look like this inside the controller

render :json => {course_module: @course_module.to_jq_upload, redirect_url: course_course_modules_path(@course) }.to_json 

I hope that's what you are looking for


Need Your Help

Why python module not found on apache

python django apache

I have a problem with python and Django.

Optimize Populating Nested Accordions

c# jquery .net performance optimization

I have three data types in a Parent -> Child -> Grandchild relationship as follows:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.