开发者

jQuery: Post form to a modal window for previewing the entered data

I am looking for a way to use jQuery to allow a user to look at a modal window "preview" of a form before they submit the form to be saved.

I have this working with javascript, the form is posted to a file named preview.php that iterates through the posted information. The script currently opens a new window.

I would like instead to use jQuery to post the form to a modal window for previewing. Does anyone have an开发者_开发问答y thoughts on how to do this?

This is what I am currently using:

<script language="JavaScript">
function preview(form) {
  form.target='_blank';
  form.action='http://example.com/preview.php';
  form.submit();
}
</script> 
<input type="button" value="preview" onclick='preview(this.form)'>


Just use the http://jquery.malsup.com/ form plugin. Add an empty div with a id of 'preview'.

$(document).ready(function() { 
    $('#form').ajaxForm({ 
        target: '#preview', 
        url: 'http://example.com/preview.php' 
    }); 
});

The form will be posted to the preview.php file and return any text that is printed in that file.


You'll want to pass your form data to the PHP page...To do this, serialize and stringify your form and its elements and pass them in the url.

JavaScript / HTML

<form action="javascript:void(0)" onsubmit="preview(this);">
    <input name="bodyBgColor" value="#ffffff" />
</form>

<div id="previewDiv" class="modal"></div>

$.fn.serializeObject = function(){
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
}; 

function preview(form) {
    var json = JSON.stringify( $(form).serializeObject() );
    var url ='/preview.php?j=' + encodeURIComponent(json);
    $('#previewDiv').load(url);
    return(false);
}

preview.php

<?php
    $json = $_REQUEST['j'];
    $j = json_decode($json, true);

    // 'bodyBgColor' is the name of the input element you want the value for.
    $bodyBGColor= $j['bodyBgColor']; 
?>

<html>
    <body style="background:#<?php echo $bodyBGColor ?>;">
        This is a preview using BGColor: <?php echo $bodyBGColor ?>
    </body>
</html>

Obviously you want to avoid using inline styling, but you get the idea.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜