2

I can send a POST request and render the response as a full page via submitting a form. How can I do that via a ajax request? That is:

$.ajax('test.com', {
    'method': 'POST',
    'success': function(res) {
        // open a new page, render res as a full page
        // I can't simply do window.location = "foobar" as it's a POST
    }
});

Or, if this is strange, what is the conventional way of doing it?

Boyang
  • 2,322
  • 5
  • 22
  • 47

2 Answers2

3

If you just need to open result of your form processing in new page you don't need ajaxa and you can just use target property of form like

<form action="http://test.com/" method="post" target="_blank">
Your inputs, etc.
</form>
SeriousDron
  • 1,226
  • 9
  • 12
  • Is there a way to avoid using form? – Boyang Mar 07 '15 at 12:56
  • Why you want to avoid form? User is entering data somewehere anyway. If you really don't need it, I can just create form on the fly, send and never show to user. That's how ajax file uploads working without File API. – SeriousDron Mar 07 '15 at 16:15
  • I just feel it's convoluted and there should be a more straightforward way... But anyways, thanks! – Boyang Mar 08 '15 at 19:52
2

Well i would go for form if you don't care about response at this point. But if you do, you can check response and do something like this:

$.ajax('test.com', {
    'method': 'POST',
    'success': function(res) {
        if ( res.code == 200 )
            document.location = 'page1.htm';
        else
            alert('error!');
    }
});
Piotr Łużecki
  • 993
  • 3
  • 15
  • 33
  • I can't do this as it's not a location. It will be a page response generated on-the-fly based on my POST data – Boyang Mar 07 '15 at 12:55
  • So you should check out first answer of this question http://stackoverflow.com/questions/133925/javascript-post-request-like-a-form-submit?rq=1 – Piotr Łużecki Mar 07 '15 at 15:03