Chris
Chris

Reputation: 961

Need to POST and close window when user clicks submit button

Right now I have the following:

<%= submit_tag 'Save' ,{:onClick => "window.close()"} %>

This works well for closing the window. Unfortunately, it closes the window before the form POSTs to the server.

The window was created using a link in the homepage:

function amenitiesPopup(){
  window.open("/amenities", "Swag", "status,width=600,height=800,resizable,scrollbars=yes","POS"); 
}

Without the :onClick => "window.close()" the form POSTs as expected. Just need to close it afterwards.

Thanks

Edit: My solution was to have the controller return a string literal:

if (params[:search])
    ...
    render :text => '<body onload="window.close()"></body>'
end

This will skip any layout/view items and just render an empty body that auto-closes

Upvotes: 2

Views: 7723

Answers (2)

Nicolas Straub
Nicolas Straub

Reputation: 3411

function onSubmit(){
    $.ajax({
        //POST info and URL etc goes here
    }).done(function(){
        window.close();
    });
}

You need to specify all arguments required by the jquery ajax api (url, data, etc).

if you submit without ajax you'll go to the page you submitted to and will no longer have control of your window, unless you control the destination page, in which case you should add the window.close to the script of your destination page:

<script>
    window.close();
</script>

Upvotes: 1

griffin
griffin

Reputation: 1258

Just return

<body onload="window.close()">

from the server, that way your POST is sure to go through before the window closes. So instead of closing from the submitting document, you close in the document received as reply by the server. Also, if you want to close the window afterwards, you might consider posting to an iframe instead depending on what you want to achieve.

Upvotes: 3

Related Questions