Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pjax submit form URL redirection

PJAX's documentation states that Github uses $.pjax.submit() in submitting a Gist form. A desired feature of an ajax form submission which Github nicely implements is that the URL redirects from the form's action to a newly created URL (in this case, one containing the newly server-side created gist ID).

For example, from this:

https://gist.github.com/gists //  form action

to this:

https://gist.github.com/tim-peterson/5019589 //assume this ID is generated server side

I've gotten this to work similarly on my site (i.e., the page itself redirects to the equivalent of https://gist.github.com/tim-peterson/5019589) but I can't redirect the URL (it stays like https://gist.github.com/gists).

Is this entirely a server-side issue (setting headers?) or is there something in pjax that I'm missing? I'm using a version of pjax I downloaded today so it can't be that i'm using a buggier version of pjax.

like image 421
tim peterson Avatar asked Feb 23 '13 13:02

tim peterson


2 Answers

Did you find any solution to this? I had the similar issue.

Basically you need to set X-PJAX-URL property in response header. It's value should be same as Request URL.

In Laravel, I did it like this...

App::after(function($request, $response)
{
  $response->headers->set('X-PJAX-URL', $request->getRequestUri());
});
like image 67
Ashit Vora Avatar answered Oct 16 '22 07:10

Ashit Vora


There may be a more-elegant / proper way to do this with $.pjax.submit(), but this is the solution I've been using without any problems. I serialize the form inputs prior to submission, then POST them to my server. Then check the reply from the server to make sure I don't need to prevent the user from going forward before calling my PJAX to continue.

$("#save").click(function(e) {

  e.preventDefault();
  dataString = $("#form").serialize();

  $.ajax({
    type: "POST",
    url: $("#form").attr("action"),
    data: dataString,
    dataType: "json",
    success: function(data)
    {
      // Handle the server response (display errors if necessary)

      $.pjax({
        timeout: 2000,
        url: data.url,
        container: '#main-content'
      });

    }
  });
});
like image 22
Dave Avatar answered Oct 16 '22 08:10

Dave