pass value/variable from fancybox iframe to parent - javascript

I'am trying to pass a variable/ value from the fancybox iframe to the parent window without success.
Fancybox is launched from a link with
class="fancybox fancybox.iframe"
My code in the fancybox.iframe is:
$(document).ready(function(){
$('.insert_single').click(function(){
var test = $('.members_body').find('{row.U_USERNAME}');
setTimeout(function(){ parent.$.fancybox.close();},300);return true;
});
});
Where '{row.U_USERNAME}' is the username to find in the iframe.
Then, in the parent there's the following code:
$(document).ready(function(){
$('.fancybox').fancybox(
{
openEffect:'fade',
openSpeed:500,
afterClose: function(){
alert($(".fancybox-iframe").contents().find(test));
$('#form input[name=username]').val()(test);return false;
}
}
);
});
But when the fancybox is closed, there's no alert showing up with the variable "test", nor the variable is showing up as a value or as a text in the input field of the form.
I've read and tried various solutions found here on stackoverflow without success.
Thanks in advance for helping
EDIT
Here's an Example

When the fancybox is closed the iframe is removed from the document. So you must use beforeClose event instead of afterClose
$(document).ready(function() {
$('a.fancybox').fancybox({
openEffect:'fade',
openSpeed:500,
beforeClose: function() {
// working
var $iframe = $('.fancybox-iframe');
alert($('input', $iframe.contents()).val());
},
afterClose: function() {
// not working
var $iframe = $('.fancybox-iframe');
alert($('input', $iframe.contents()).val());
}
});
});
JSFiddle: http://jsfiddle.net/NXY7Y/1/
EDIT:
I edited your jsfiddle (http://jsfiddle.net/NXY7Y/9/). Update is in this link
http://jsfiddle.net/NXY7Y/13/
Main page javscript:
$(document).ready(function() {
$('a.fancybox').fancybox({
openEffect:'fade',
openSpeed:500//,
//beforeClose: function() {
// // working
// var $iframe = $('.fancybox-iframe');
// alert($('input', $iframe.contents()).val());
//},
//afterClose: function() {
// // not working
// var $iframe = $('.fancybox-iframe');
// alert($('input', $iframe.contents()).val());
//}
});
});
function setSelectedUser(userText) {
$('#username').val(userText);
}
No need to use afterClose or beforeClose events. Just access the parent function setSelectedUser from the iframe on link click event like this:
$(document).ready(function() {
$('a.insert_single').click(function() {
parent.setSelectedUser($(this).text());
parent.$.fancybox.close();
});
});

Some clarifications :
You should use .find() to find elements by selector (you are trying to find a variable .find(test), which is not a valid format).
You should use .val() to get the contents of an input field or .val(new_value) to set the contents of an input field
You should use .html() or .text() to get the contents of any element other than input,
example: having this html code
<p class="test">hola</p>
... and this jQuery code
var temp = $(".test").html();
... temp will return hola.
On the other hand, if you have control over the iframed page and it's under the same domain than the parent page, then you may not need to set any jQuery in the child page.
so, having this html in the child (iframed) page for instance
<div class="members_body">
<p>GOOGLE</p>
<p>JSFIDDLE</p>
<p>STACKOVERFLOW</p>
</div>
You could set this jQuery in your parent page to get the contents of any clicked element in your child page :
var _tmpvar; // the var to use through the callbacks
jQuery(document).ready(function ($) {
$(".fancybox").fancybox({
type: "iframe",
afterShow: function () {
var $iframe = $('.fancybox-iframe');
$iframe.contents().find(".members_body p").each(function (i) {
$(this).on("click", function () {
_tmpvar = $('.members_body p:eq(' + i + ')', $iframe.contents()).html();
$.fancybox.close();
}); // on click
}); // each
},
afterClose: function () {
$('#form input[name=username]').val(_tmpvar);
}
});
}); // ready
Notice that we declared the var _tmpvar globally so we can use it within different callbacks.
See JSFIDDLE

Related

External Jquery Plugins not working after ajax call content [duplicate]

This question already has answers here:
Making jquery plugins work after an Ajax call
(3 answers)
Chosen not working on elements from AJAX call
(2 answers)
Closed 1 year ago.
So I have this Jquery functions that I've created using delegations and call each functions in the documeny.ready.
$(document).ready(function () {
getContent();
getQuoteButtton();
popupModal();
plugins();
});
function getQuoteButtton() {
// button quote
$("body").on("click", ".btn-quote", function (e) {
var $this = $(this);
$this.toggleClass('quote-selected');
if ($this.hasClass('quote-selected')) {
$this.text('Selected');
} else {
$this.text('Select This Quote');
}
});
}
function getContent() {
// fire on click
$("body").on("click", 'nav#sidebar.get-qoute-sidebar ul li a', function (e) {
// setting target from data attributes
var $this = $(this),
target = $this.attr('data-target'),
container = $('#get_content');
container.load('pages/' + target + '.php');
});
}
function popupModal() {
/*Toggle popup-modal class */
$("body").on("click", ".popup-modal-toggle", function (e) {
$('.popup-modal').fadeIn().show();
});
//close popup button
$("body").on("click", ".popup-close", function (e) {
$('.popup-modal').fadeOut().hide(300);
});
}
function plugins() {
// phone number plugin initialized singapore and malaysia only
$("#phone-num").intlTelInput({
initialCountry: "SG",
onlyCountries: ['SG', 'MY'],
utilsScript: './resources/vendors/intl-tel-input-master/js/utils.js'
});
// Select tags with search bar
$(".chzn-select").chosen();
}
The other functions is working fine but when I call the plugins function it doesn't seem to load after using the getContent.
The getContent function is where I handle my ajax call to load each pages in the section using the div element #get_content
I don't understand why my plugins function is not working. Does anybody know why? Do I have to call each functions in plugins to use delegations also? if so, what's the process? Thanks.
EDIT - Correct Answer
I have find out the solution, in the getContent function, I also added the plugins() function inside to fetch it after ajax. I don't know why this question was closed even though I have a different approach in coding.
function getContent() {
// fire on click
$("body").on("click", 'nav#sidebar.get-qoute-sidebar ul li a', function (e) {
// setting target from data attributes
var $this = $(this),
target = $this.attr('data-target'),
container = $('#get_content');
container.load('pages/' + target + '.php', function (response, status, xhr) {
// include the plugins function after the content loads -> if no initialization function won't load
plugins();
});;
});
}

JQuery detect widget attached

I have a web application with a medium amount of ajax requests.
I load all jquery and jquery widgets on head then i load my base.js before close body tag.
function baseScripts() {
$(".open-dialog").click(function (event) {
event.preventDefault();
event.stopPropagation();
alert("Opening dialog");
href = $().buildUrl($(this).attr("href"), "&isAjax=true");
$().createDialog(href, "Window Title");
return false;
});
$("input:hidden.select").each(function () {
var element = $(this);
if (!($("#s2id_" + element.attr("id")).length)) {
$(element).select2({
// select2 properties...
});
}
});
}
}
SCRIPT BLOCK TO LOAD BASE SCRIPTS ON EVERY AJAX REQUEST
$(document).ajaxComplete(baseScripts);
The problem is after every ajax request the base scripts its called again and them opening dialog multiple times and attaching select2 multiples times too.
How i can detect if widget is already attached into element or class?
Execute scripts on every ajax request (like i did) its a bad pratice?
It doesn't make sense that you will want to re-bind the click event and select2 on ajaxComplete. They should be a one-time binding, in which case, you can just do:
$(document).ready(function(){
baseScripts();
function baseScripts() {
$(".open-dialog").click(function (event) {
event.preventDefault();
event.stopPropagation();
alert("Opening dialog");
href = $().buildUrl($(this).attr("href"), "&isAjax=true");
$().createDialog(href, "Window Title");
return false;
});
$("input:hidden.select").each(function () {
var element = $(this);
if (!($("#s2id_" + element.attr("id")).length)) {
$(element).select2({
// select2 properties...
});
}
});
}
});

Insert a form field into a popup page using jquery

I'm trying to insert a form field into a popup page. For some reason the form field doesn't get inserted. Any pointers. Pasted below is the code:
$(".ddlAddListinTo li").click(function () {
var urlstring = "../ActionTypes";
var ddlselectedVal = $(this).attr('id');
var $form = $("#frmPostToEmailReports");
var AgentId = $form.find("#AgentId").val();
var ReportName = $form.find("#ReportName").val();
var Params = $form.find("#Params").val();
if (ddlselectedVal != "None" && ddlselectedVal != "select") {
$.post(urlstring, { AgentId: AgentId, ReportName: ReportName, Params: Params },
function (data) {
window.open(urlstring);
$("#divfrmInfo").append($form);
});
} });
HTML for my popup window :
<html>
<head></head>
<body>
<h2>AddToCart</h2>
<form name="frmContact">
<div>
<div class="CartHeader">
<ul>
<li>
<span class="CartImage"></span>
<span class="Title">To Add Listing(s) to Cart</span>
<span class="SubTitle">Select your personal cart or add listings to a contact</span>
</li>
</ul>
</div>
**<div id="divfrmInfo"></div>**
</div>
</form>
</body></html>
Looking at it some more you could do something like this, in opener document.
$(".ddlAddListinTo li").click(function () {
...
function (data) {
$(window.open(urlstring)).load ( function() {
// Here "this" will be the window.
$(this.document).find("#divfrmInfo").append($form.clone())
});
}
This way you attach to load event for popup by jQuery.
Have a look at .clone() for the append part. If it is not cloned it will be "ripped" from your main document and placed inside the popup.
Old answer:
...
Here is a fiddle (With fixed typo/formatting).
Next problem is in your script you say:
$(".ddlAddListinTo li").click
However, there are no elements in DOM with class ddlAddListinTo.
OK, by comment:
after window.open(urlstring); you are still in DOM of document from where you opened the window. As such:
$("#divfrmInfo")
will look for an element in original document with that ID, not in the popup.
If you add something like this in the popup document*:
$(window).load(function() {
// Call function "fill()" in opener.
window.opener.fill(document);
});
And this in your opener document:
function fill(what) {
// Here "what" is document of popup.
what.getElementById("divfrmInfo").innerHTML = "TEST";
}
I think the selector in your AJAX callback is unable to get DOM elements in the popup. Try this:
var tmpWin = window.open(urlstring);
$(tmpWin.document).find("#divfrmInfo").append($form);
THe problem is you are tring to aceess the DOM of the spawned page before it is there. The window is loaded but the HTML is still being loaded at the time you are trying to access it. You will need to change the parent and popup page. On the parent page you will need a function to return what you want to populate the pop up with. On the popup page you will want to call the function on the parent page when the DOM is ready.
Something like:
Parent Page
//Add this OUTSIDE your document ready
function getContent(){
return $("#frmPostToEmailReports");
}
Popup
//Include Jquery in your prefered way
<script>
$(document).ready(function () {
$("#divfrmInfo").append(window.opener.getContent());
});
</script>
Alos make sure to remove where you attempt to pupulate in the success function. Also see: How to get element and html from window.open js function with jquery
Previous Useless Answer Below
See this answer to get you started.
Instance you will want something like:
$(".ddlAddListinTo li").click(function () {
var urlstring = "../ActionTypes";
var ddlselectedVal = $(this).attr('id');
var $form = $("#frmPostToEmailReports");
var AgentId = $form.find("#AgentId").val();
var ReportName = $form.find("#ReportName").val();
var Params = $form.find("#Params").val();
if (ddlselectedVal != "None" && ddlselectedVal != "select") {
$.post(urlstring, { AgentId: AgentId, ReportName: ReportName, Params: Params },
function (data) {
var popup = window.open(urlstring);
popup.document.$("#divfrmInfo").append($form);
});
} });

Jquery function doesn't work after Ajax call

I've got this function:
$(document).ready(function() {
$('.post_button, .btn_favorite').click(function() {
//Fade in the Popup
$('.login_modal_message').fadeIn(500);
// Add the mask to body
$('body').append('<div class="overlay"></div>');
$('.overlay').fadeIn(300);
return false;
});
My page loads content with favourite buttons, but after Ajax call and generated additional new content the function doesn't work when you click new content's buttons. What could be not right?
That is because you are using dynamic content.
You need to change your click call to a delegated method like on
$('.post_button, .btn_favorite').on('click', function() {
or
$("body").on( "click", ".post_button, .btn_favorite", function( event ) {
Instead of this:
$('.post_button, .btn_favorite').click(function() {
do this:
$(document).on('click','.post_button, .btn_favorite', function() {
on will work with present elements and future ones that match the selector.
Cheers
class-of-element is the applied class of element. which is selector here.
$(document).on("click", ".class-of-element", function (){
alert("Success");
});
If you know the container for .post_button, .btn_favorite then use
$('#container_id').on('click', '.post_button, .btn_favorite', function () { });
so if '.post_button, .btn_favorite' are not found then it will bubble up to container_id
else if you don't know the container then delegate it to document
$(document).on('click', '.post_button, .btn_favorite', function () { });
Reference
I am not sure if I am getting your question right but you may want to try..
$.ajax({
url: "test.html"
}).done(function() {
$('.post_button, .btn_favorite').click(function() {
//Fade in the Popup
$('.login_modal_message').fadeIn(500);
// Add the mask to body
$('body').append('<div class="overlay"></div>');
$('.overlay').fadeIn(300);
return false;
});
Just try to paste your code inside done function.
Hope it helps :)
EDIT:
I also notice you are missing }); on your question.
The following worked for me
$(document).ready(function(){
$(document).bind('contextmenu', function(e) {
if( e.button == 2 && jQuery(e.target).is('img')) {
alert('These photos are copyrighted by the owner. \nAll rights reserved. \nUnauthorized use prohibited.');
return false;
}
});
});
You need to bind the jQuery click event once your ajax content is replaced old content
in AJAX success block you need to add code like here new response html content one a tag like
Click Me
So you can bind the new click event after change the content with following code
$("#new-tag").click(function(){
alert("hi");
return false;
});

Click link to execute a function?

I want to run a function after a link has been clicked.
The link I would like to point to the function is the one with the cancelLink class. The first link is here to show you as an example how I'm getting the AppointmentId the first link works by passing a parameter to another page.
I would like to be able to click the Cancel link and run a function on the current page.
Here are my links:
Invoice |
<a href="#" class="cancelLink" data-attr=${AppointmentId}>Cancel</a>
Below is my click function which is under the document ready:
$('a.cancelLink').click(function () {
var appointmentId = $(this).attr("data-attr");
//var appointmentId = $(this).attr("appointmentId");
MemberWebService.AppointmentStatusUpdate(appointmentId, 3, function () {
window.location = 'AppointmentViewAll.aspx';
});
});
Currently code does not enter this click function, how could I achieve this?
Your code seems fine to me. Here is a working plunk. Have you tried put a 'console.log("sample test");' inside your click handler to see if it's firing? Could you please also post how did you wrap your code inside $(document).ready() ?
Did you do it this way?
$(document).ready(function() {
$('a.cancelLink').click(function () {
var appointmentId = $(this).attr("data-attr");
//var appointmentId = $(this).attr("appointmentId");
MemberWebService.AppointmentStatusUpdate(appointmentId, 3, function () {
window.location = 'AppointmentViewAll.aspx';
});
});
});
try this:
$('a.cancelLink').click(function (e) {
e.preventDefault();
var appointmentId = $(this).attr("data-attr");
//var appointmentId = $(this).attr("appointmentId");
MemberWebService.AppointmentStatusUpdate(appointmentId, 3, function () {
window.location = 'AppointmentViewAll.aspx';
});
});
i hope it helps.
I found a few possible causes, see my comments;
HTML
Invoice
Cancel // Use quotes
Javascript
$(document).ready(function() { // Only access elements once the DOM is loaded
$(document).on('click', 'a.cancelLink', function(event) { // Try using on() instead of click() as you seem to be using some templating for creating the link ("${AppointmentId}").
event.preventDefault(); // DonĀ“t follow the link to #
var appointmentId = $(this).data('attr'); // Use data() instead of attr()
console.log(event.type, appointmentId); // View your console
MemberWebService.AppointmentStatusUpdate(appointmentId, 3, function() {
window.location = 'AppointmentViewAll.aspx';
});
});
});
See on() and data().
Use the onclick method to call a function and add parameters.
Cancel
function bindCancel(appointmentId) {
MemberWebService.AppointmentStatusUpdate(appointmentId, 3, function () {
});
}

Categories

Resources