2

I'm trying my hand at unobtrusive JS, using JQuery in my Ruby On Rails app.

After the user fills out a form, the client-side JQuery code calls:

$.post("/premises", ui.form)

I can see the POST hit the server, and I can see the server emit a redirect notice to http://localhost:3000/users/42 complete with the data to be displayed.

But the browser page doesn't change. This doesn't really surprise me -- the whole point of client-side javascript is to control what gets updated -- I get that. But in this case, I'd like to honor whatever the server replies with.

I tried extending the call to post() based on How to manage a redirect request after a jQuery Ajax call:

$.post("/premises", 
       ui.item,  
       function(data, textStatus) {
           if (data.redirect) {
               // data.redirect contains the string URL to redirect to
               window.location.href = data.redirect;
           } else {
               // data.form contains the HTML for the replacement form
               $("#myform").replaceWith(data.form);
           }
       });

... but (among other problems) data.redirect is undefined. I suspect the real answer is simple, right? Looking forward to it!

Community
  • 1
  • 1
fearless_fool
  • 33,645
  • 23
  • 135
  • 217

3 Answers3

1

The post you refer to uses JSON as return value and it is constructing that json on server side. it means if there is redirect your data object would look like

{redirect:'redirecturl.html'}

and if it is not redirect then data object would be like

{form:html-string-for-form}

now job is to construct json object accordingly on server side

Muhammad Adeel Zahid
  • 17,474
  • 14
  • 90
  • 155
0

The server is saying that the data you want to process with JavaScript is available at a different URL, not that the browser should load a new document into the top level frame. Sending the browser to the URL where it was told the data it was requesting with JS is wouldn't be honouring the redirect.

If you want to do that, then the server should respond with data (in the body of the response) that the JavaScript interprets as a reason to assign a new value to location.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

data.redirect is probably undefined because you're not specifying it on the server side. In the answer you linked to the point was to have the server always respond with 200 regardless of the outcome, and then the JSON body it sends back determines how the client reacts. So, on the server side you'd want to respond with {"redirect" : "/where/to/go"}

Robert
  • 21,110
  • 9
  • 55
  • 65