开发者

jQuery - 2 different functions for 2 different submit buttons in one form

I have had a search around at other suggest开发者_运维知识库ions for what i want to do, but none seems to have what i need.

Basically i have a form with 2 submit buttons, i want one to save the data to the database, which i have done and works perfect ... the second submit button ( preview ) i need to open in a new window, take all the form data and display it on a form while leaving the previous page as it is ... if that makes sense.

I figure i cant do this with PHP as to get the post data it needs to basically reload a page ... i thought there might be a way with jQuery.

Any help?


I wouldn't use jQuery for this unless you're already using it elsewhere in the application.

HTML Markup:

<form method="post" action="foo.php" id="myform">
    <button type="submit" name="save_data">Save Data</button>
    <button type="submit" name="preview_data" onclick="document.getElementById('myform').target = '_blank'; return true;">Preview Data</button>
</form>

PHP:

<?php
if (isset($_POST['preview_data'])) {
    // Clicked Preview
} else if (isset($_POST['save_data'])) {
    // Clicked Save
} else {
    // How'd you get here? Probably not POST
}
?>


It sound like you need to use script for the 2nd button.

Would look something like this (using jQuery):

<button type="button" id="preview_button">preview</button>
<script type="text/javascript">
    $(document).ready(function(){
      $('#preview_button').click(function(){
        var pUrl = 'http://server/preview.php?' + $('#form_id').serialize();
        window.open(pUrl);
      });
    });
</script>


Of cours that it's possible with jQuery. All you need to do is to write two onClick functions (to each button). In first function simply call $("form_name").submit() and your data will be submited. And in the second function open the dialog (you can use this http://jqueryui.com/demos/dialog/), get all data from the form and put it into dialog in the way you need them). To get all data from your form you can user another jQuery function $("form_name").serialize(). Take look here: http://api.jquery.com/serialize/


It sounds like your preview button isn't a submit button, but should just be a regular button that you set a new click function for.

In that function you can open the new window with the fields from the form.

If you want the new window to do a round trip to the server, you could use an ajax call as John suggested or perhaps when the 2nd button is clicked set a flag in a hidden field and your server side script can check that flag to determine if it should save the data or generate the preview page.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜