Karlom
Karlom

Reputation: 14874

How to redirect to calling url after ajax call?

I have a controller function that is posted by ajax call:

func AddLike(w http.ResponseWriter, r *http.Request) {

    fmt.Println("form posted \n\n")
    // Get session
    sess := session.Instance(r)
    var params httprouter.Params
    params = context.Get(r, "params").(httprouter.Params)
    Name := params.ByName("name")
   //do stuff
  //How to return to calling page?
}

This controller can be posted from several differnet urls. In the current situation, I see a blank page as the function returns to the url of ajax post, which is /addlike.

I'm wondering how to return/redirect to the calling page after post being processed?

Upvotes: 0

Views: 309

Answers (1)

noisypixy
noisypixy

Reputation: 774

As suggested in the comments, you can use the Referer (sic) header and http.Redirect to respond with a redirection.

func AddLike(w http.ResponseWriter, r *http.Request) {
    // TODO: Your stuff.

    redirectURL := r.Header.Get("Referer")
    if redirectURL == "" {
        // TODO: What to do in case you don't know
        // where to redirect.
        return
    }

    http.Redirect(w, r, redirectURL, http.StatusFound)
}

Upvotes: 1

Related Questions