Post preview - Passing data with AJAX and Fancybox
Solution 1:
As I mentioned in my comments, your preview button should submit the form via ajax to get the POST preview values (we'll use ajax
instead of iframe
) so :
<a class="preview2" data-fancybox-type="ajax" href="preview.php" id="preview2">Preview</a>
Then you would need to bind the preview button to a manual on("click")
method to submit the form via ajax
firstly ....and then post the results in fancybox secondly like :
$(document).ready(function () {
$('.preview2').on("click", function (e) {
e.preventDefault(); // avoids calling preview.php
$.ajax({
type: "POST",
cache: false,
url: this.href, // preview.php
data: $("#postp").serializeArray(), // all form fields
success: function (data) {
// on success, post (preview) returned data in fancybox
$.fancybox(data, {
// fancybox API options
fitToView: false,
width: 905,
height: 505,
autoSize: false,
closeClick: false,
openEffect: 'none',
closeEffect: 'none'
}); // fancybox
} // success
}); // ajax
}); // on
}); // ready
See DEMO (feel free to explore the source code)
Solution 2:
I don't like the solution, so I will post my own investigation.
Why writing code with 1. .on("click", ...
2. e.preventDefault
3. $.ajax
4. this.href
just to call fancybox on success, that already has all this functions inside?
If you decide to use ajax instead of iframe (like in accepted answer) you could simply add type
property to fancybox()
call, cause it's beening checked, and pass all other
$('.preview2').fancybox({
type: "ajax",
ajax: {
data: $('#postp').serialize()
// url: "someurl.php" not needed here, it's taken from href
// if you need it, e.g. you have a button, not a link
// use "href" property that overrides everything
// not attribute, cause it's invalid
}
// href: "url_to_add_or_override_existing_one",
// all other effects
// afterLoad: function () { // other cool stuff }
});
EDIT As @JFK pointed it's not enough, you have to get form data each time you click the link, so beforeLoad()
needed instead of data
. Finnaly:
$('.preview2').fancybox({
type: "ajax",
beforeLoad: function() {
this.ajax.data = $('#postp').serialize();
}
});
You can remove all data-*
atrributes too
FIDDLE
KISS