Fetch particular field from moodialog and pass value to parent screen - php

I used MooDialog.iframe and onClose i need some values. But not able to fetch values from that iFrame and want to use in the page i opened this frame in popup.
The function/code i used for popup is below:
function popup_window() {
var hostname = location.protocol + "//" + location.hostname + (location.port && ":" + location.port) + "/";
var opcion = "crear";
co2=new MooDialog.IFrame(hostname+'infinity/contabilidad/cuenta%20crear/popup_window.php?action=2',
{
title: 'Editar Centro','class' : 'content_edit1 MooDialog',
onClose: function()
{
/////////alert(document.getElementById('numero_cuenta').value);
//numero_cuenta is something i want
location.reload();
}
}
);
}
numero_cuenta is the id of the input.text of the popup iframe.

I found the solution:
From the popup_window.php file get the element by id via frame. We need to use the following code:
onClose: function()
{
var myIFrame = document.getElementById("MooFrame");
var content = myIFrame.contentWindow.document.getElementById('abcd').value;
alert('content: ' + content);
location.reload();
}

Related

Changing class type using Jquery

I am using this code to fetch the data from startup.php.The response of the PHP file is JSON with 3 fields. One of the field in JSON response is a status message. How to change the value of div class .content based on the status message. I need to do that to change the color of the text displayed in the content DIV based on the status message. .content is the class name of the DIV
var loadinggif = '../img/loading.gif';
$(document).ready(function(){
// set up the click event
$('body').on('click','.btnbg', function() {
var toLoad = '../vr/startup.php';
$('.content').empty();
$('.content').slideUp('slow', loadContent);
$('#load').remove();
$('#waiting').append('<div id="load"><img src="' + loadinggif + '" alt="Loading" /></div>');
$('#load').fadeIn('normal');
function loadContent() {
var userName = $('#userName').val();
var remote_addr = $('#remote_addr').val();
var forwarded_for = $('#forwarded_for').val();
var url = $('#url').val();
//$('#forwarded_for1').val()'';
var _post = {'userName': userName, 'ipAddr1':remote_addr,'ipAddr2':forwarded_for, 'url':url};
$('.content').load(toLoad, _post , function(response, status, xhr)
if (status == 'error') {
var msg = "Sorry but there was an error: ";
$(".content").html(msg + xhr.status + " " + xhr.statusText);
}
}).slideDown('slow', hideLoader());
}
function hideLoader() {
$('#load').fadeOut('normal');
}
return false;
});
You can use the css() function in Jquery :
$(".content").css({'background-color': 'red'});
Edit
I red your question wrong. To change class you can use $('.content').removeClass('classOne').addClass('classTwo');
If you have a class like has-error, you can use toggleClass() to toggle it, it will remove it if it's present or add it if not :
$('.content').toggleClass('has-error');
for your if elseprobleme, simply do :
if(condition) {
$('.content').removeClass('class2 class3').addClass('class1');
} else if(condition2) {
$('.content').removeClass('class1 class3').addClass('class2');
} else {
$('.content').removeClass('class1 class2').addClass('class3');
}
Use removeClass() and addClass().
Here is an example:
$('.content').removeClass("styleOne").addClass("styleTwo");
Edit
if(response == "Worked Fine"){
$('.content').removeClass("default").addClass("styleGreen");
}else{
$('.content').removeClass("default").addClass("styleRed");
}

Two different ajax requests without refreshing page

I have a site that uses ajax to load a post directly to the page when clicked.
But... I also have an ajax contact-form at the same page. But if I click a post first, then want to send a message later, it fails. But if I refresh the page and go straight to the contact-form and send a message it doesn't fail at sending. Is there any way that I can maybe "reload" ajax without refreshing the page so that you can do multiple things at my site with ajax?
$(document).ready(function() {
function yournewfunction() {
var requestCallback = new MyRequestsCompleted({
numRequest: 3,
singleCallback: function() {
alert("I'm the callback");
}
});
var width = 711;
var animationSpeed = 800;
var pause = 3000;
var currentSlide = 1;
var $slider = $("#slider");
var $slideContainer = $(".slides");
var $slides = $(".slide");
var $toggleRight = $("#right");
var $toggleLeft = $("#left");
$toggleRight.click(function() {
$slideContainer.animate({
'margin-left': '-=' + width
}, animationSpeed, function() {
currentSlide++;
if (currentSlide === $slides.length) {
currentSlide = 1;
$slideContainer.css('margin-left', 0);
}
});
});
$toggleLeft.click(function() {
if (currentSlide === 1) {
currentSlide = $slides.length;
$slideContainer.css({
'margin-left': '-' + width * ($slides.length - 1) + 'px'
});
$slideContainer.animate({
'margin-left': '+=' + width
}, animationSpeed, function() {
currentSlide--;
});
} else {
$slideContainer.animate({
'margin-left': '+=' + width
}, animationSpeed, function() {
currentSlide--;
});
}
});
if ($(".slide img").css('width') == '400px' && $(".slide img").css('height') == '400px') {
$(".options").css("width", "400px");
$(".slide").css("width", "400px");
$("#slider").css("width", "400px");
$(".video-frame").css("width", "400px");
var width = 400;
};
if ($("#slider img").length < 2) {
$("#right, #left").css("display", "none");
};
if ($("iframe").length > 0 && $("iframe").length < 2) {
$(".options").css("width", "711px");
$(".slide").css("width", "711px");
$("#slider").css("width", "711px");
$(".video-frame").css("width", "711px");
$('.slide').hide();
var width = 711;
};
if ($(".slide img").css('width') > '400px' && $(".slide img").css('width') < '711px') {
$(".options").css("width", "600px");
$(".slide").css("width", "600px");
$("#slider").css("width", "600px");
$(".video-frame").css("width", "600px");
var width = 600;
};
}
$.ajaxSetup({
cache: false
});
$(".post-link").click(function(e) {
e.preventDefault()
var post_link = $(this).attr("href");
$("#single-post-container").html('<img id="loads" src="http://martinfjeld.com/wp-content/uploads/2015/09/Unknown.gif">');
$("#single-post-container").load(post_link, function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#error").html(msg + xhr.status + " " + xhr.statusText);
} else {
$("#main-content").fadeIn(500);
$("body").addClass("opens");
yournewfunction();
}
});
requestCallback.requestComplete(true);
return false;
});
});
$(function() {
var form = $('#ajax-contact');
var formMessages = $('#form-messages');
$(form).submit(function(event) {
event.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
}).done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
$('#message').val('');
}).fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
Though it's hard to follow exactly what is going on without being able to see the context of your HTML and without you giving us a more concrete description of exactly which line of code fails to execute, this is likely because one Ajax call is replacing a bunch of HTML which clobbers all your event handlers. So, when you then try to do the second Ajax operation, it's click handler is no longer in force so nothing happens.
Replacing a DOM element loses all event handlers that were attached to the original DOM element. Using .html() or assigning to .innerHTML replaces all the DOM elements within that element, thus losing all their event handlers.
The typical solution to this is to either reinstall the event handlers after replacing the content that you want event handlers on or use delegated event handling from a parent element that is not replaced.
Here are some references on delegated event handling:
JQuery Event Handlers - What's the "Best" method
jQuery .live() vs .on() method for adding a click event after loading dynamic html
Does jQuery.on() work for elements that are added after the event handler is created?
Should all jquery events be bound to $(document)?

TypeError: $ is undefined : $.widget("ui.combobox", {

I use jquery in comboboxes, and I'm not abele to get the comboboxes in the interface to be displayed. The error in firebug is the following :
TypeError: $ is undefined : $.widget("ui.combobox", {
I'm using the following file jquery.ui.combobox.js:
Code :
$.widget("ui.combobox", {
options: {
openDialogButtonText: "+",
dialogHeaderText: "Add option",
saveButtonImgUrl: null,
closeButtontext: "Ok"
},
_create: function() {
var selectBox = $(this.element),
id = selectBox.attr("id"),
self = this;
selectBox.addClass("ui-combobox");
// create HTML to inject in the DOM
this.addHtml(id, selectBox);
// turn dialog html into a JQuery UI dialog component
this.addDialog(id);
// #todo set proper button height (roughly equal to select height)
$("#" + id + "-button-opendialog").bind("click", function() {
$("#" + id + "-editor-dialog").dialog("open");
}).button();
$("#" + id + "-button-save").bind("click", function() {
self.addOption(id, selectBox);
}).button();
this._init();
return this;
},
addHtml: function(id, selectBox) {
var imgHtml = "";
if (this.options.saveButtonImgUrl != null) {
imgHtml = '<img src="' + this.options.saveButtonImgUrl + '" alt="opslaan" />';
}
$(' <button id="' + id + '-button-opendialog">' +
this.options.openDialogButtonText +
'</button>' +
'<div id="' + id + '-editor-dialog" class="ui-combobox-editor">' +
'<input id="' + id + '-newitem" type="text" /> ' +
' <button id="' + id + '-button-save">' +
imgHtml + ' Opslaan' +
' </button>' +
'</div>').insertAfter(selectBox);
},
addDialog: function(id) {
var options = this.options;
$("#" + id + "-editor-dialog").dialog( {
autoOpen: false,
modal: true,
overlay: {
opacity:0.5,
background:"black"
},
buttons: {
// #todo make button text configurable
"Ok": function() {
$("#" + id + "-editor-dialog").dialog("close");
return;
}
},
title: options.dialogHeaderText,
hide: 'fold'
});
},
addOption: function(id, selectBox) {
var newItem = $("#" + id + "-newitem");
// #todo do not allow duplicates
if (newItem !== null && $(newItem).val().length > 0) {
// #todo iterate over options and get the highest int value
//var newValue = selectBox.children("option").length + 1;
var highestInt = 0;
selectBox.children("option").each(function(i, n) {
var cInt = parseInt($(n).val());
if (cInt > highestInt) {
highestInt = cInt;
}
});
var newValue = highestInt + 1;
var newLabel = $(newItem).val();
selectBox.prepend("<option value='" + newValue + "' selected='selected'>" + newLabel + "</option>");
this._trigger("addoption", {}, newValue);
// cleanup and close dialog
$(newItem).val("");
$("#" + id + "-editor-dialog").dialog("close");
} else {
this._trigger("addoptionerror", {}, "You are required to supply a text");
}
},
_init: function() {
// called each time .statusbar(etc.) is called
},
destroy: function() {
$.Widget.prototype.destroy.apply(this, arguments); // default destroy
// $(".ui-combobox-button").remove();
// $(".ui-combobox-editor").remove();
}
});
Can you please help me?
The message "$ is undefined" means that the function called "$" is not defined anywhere on your page. Thus, when this code is executed, it does not know what to do when this line is encountered.
The $ function is defined by jQuery. Therefore, the message is indicating that it hasn't loaded the jQuery library by the time your code is executed. This could be for a number of things
You haven't included the full jQuery library on your page. This may be because you have forgotten to include it or you have only included some extension to jQuery such as jQuery.UI.
If you are unsure, try adding the following line to the top of your head element in your HTML. Make sure you haven't put any JS before this line:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
You have included jQuery but it is failing to load. This may be because the link you are using is incorrect. Double check by using the Net Panel in Firebug.
jQuery is included on your page, but you have included your own JS first. This won't work because the $ function won't get defined until jQuery is loaded, but your code will try and execute first. Check the order in which you are including your JS and make sure that jQuery is first.

Dynamically load image with different GET parameters

I'm trying to load an image (created with PHP) with jQuery and passing a few variables with it (for example: picture.php?user=1&type=2&color=64). That's the easy part.
The hard part is that I've a dropdown which enables me to select background (the type parameter) and I'll have an input for example to select a color.
Here're the problems I'm facing:
If a dropdown/input hasn't been touched, I want to leave it out of the URL.
If a dropdown/input has been touched, I want to include it in the url. (This won't work by just adding a variable "&type=2" to the pre-existing string as if I touch the dropdown/input several times they'll stack (&type=2&type=2&type=3)).
When adding a variable ("&type=2" - see the code below) to the pre-existing URL, the &-sign disappears (it becomes like this: "signature.php?user=1type=2").
Here's the code for the jQuery:
<script>
var url = "signatureload.php?user=<?php echo $_SESSION['sess_id']; ?>";
$(document).ready(function() {
window.setTimeout(LoadSignature, 1500);
});
$("#signature_type").change(function() {
url += "&type="+$(this).val();
LoadSignature();
});
function LoadSignature()
{
$("#loadingsignature").css("display", "block");
$('#loadsignature').delay(4750).load(url, function() {
$("#loadingsignature").css("display", "none");
});
}
</script>
Here's the code where I load the image:
<div id="loadsignature">
<div id="loadingsignature" style="display: block;"><img src="img/loading-black.gif" alt="Loading.."></div>
</div>
I don't know how more further I could explain my problem. If you have any doubts or need more code, please let me know.
Thank you for your help!
EDIT:
Here's the current code:
<script>
var url = "signatureload.php?user=<?php echo $_SESSION['sess_id']; ?>";
$(document).ready(function() {
window.setTimeout(LoadSignature, 1500);
});
$("#signature_type").change(function() {
url = updateQueryStringParameter(url, 'type', $(this).val());
LoadSignature();
});
function LoadSignature()
{
$("#loadingsignature").css("display", "block");
$('#loadsignature').delay(4750).load(url, function() {
$("#loadingsignature").css("display", "none");
});
}
function updateQueryStringParameter(uri, key, value)
{
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i"),
separator = uri.indexOf('?') !== -1 ? "&" : "?",
returnUri = '';
if (uri.match(re))
{
returnUri = uri.replace(re, '$1' + key + "=" + value + '$2');
}
else
{
returnUri = uri + separator + key + "=" + value;
}
return returnUri;
}
</script>
EDIT2:
Here's the code for signatureload.php
<?php
$url = "signature.php?";
$count = 0;
foreach($_GET as $key => $value)
{
if($count > 0) $url .= "&";
$url .= "{$key}={$value}";
}
echo "<img src='{$url}'></img>";
?>
If I understood your question correctly, it comes down to finding a proper way of modifying GET parameters of the current URI using JavaScript/jQuery, right? As all the problems you point out come from changing the type parameter's value.
This is not trivial as it may seem though, there are even JavaScript plugins for this job. You could use a function like this and in your signature_type change event listener,
function updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i"),
separator = uri.indexOf('?') !== -1 ? "&" : "?",
returnUri = '';
if (uri.match(re)) {
returnUri = uri.replace(re, '$1' + key + "=" + value + '$2');
} else {
returnUri = uri + separator + key + "=" + value;
}
return returnUri;
}
$('#signature_type').change(function () {
// Update the type param using said function
url = updateQueryStringParameter(url, 'type', $(this).val());
LoadSignature();
});
Here is a variant where all the data is keept in a separate javascript array
<script>
var baseurl = "signatureload.php?user=<?php echo $_SESSION['sess_id']; ?>";
var urlparams = {};
$(document).ready(function() {
window.setTimeout(LoadSignature, 1500);
});
$("#signature_type").change(function() {
urlparams['type'] = $(this).val();
LoadSignature();
});
function LoadSignature()
{
var gurl = baseurl; // there is always a ? so don't care about that.
for (key in urlparams) {
gurl += '&' + encodeURIComponent(key) + '=' + encodeURIComponent(urlparams[key]);
}
$("#loadingsignature").css("display", "block");
$('#loadsignature').delay(4750).load(gurl, function() {
$("#loadingsignature").css("display", "none");
});
}
</script>
With this color or any other parameter could be added with urlparams['color'] = $(this).val();
Why don't you try storing your selected value in a variable, and then using AJAX post data and load image. That way you ensure there is only one variable, not repeating ones. Here's example
var type= 'default_value';
$("#signature_type").change(function() {
type = $(this).val();
});
then using ajax call it like this (you could do this in your "change" event function):
$.ajax({
type: 'GET',
url: 'signatureload.php',
data: {
user: <?php echo $_SESSION['sess_id']; ?>,
type: type,
... put other variables here ...
},
success: function(answer){
//load image to div here
}
});
Maybe something like this:
<script>
var baseUrl = "signatureload.php?user=<?php echo $_SESSION['sess_id']; ?>";
$(document).ready(function() {
window.setTimeout(function(){
LoadSignature(baseUrl);
}, 1500);
});
$("#signature_type").change(function() {
var urlWithSelectedType = baseUrl + "&type="+$(this).val();
LoadSignature(urlWithSelectedType);
});
function LoadSignature(urlToLoad)
{
$("#loadingsignature").css("display", "block");
$('#loadsignature').delay(4750).load(urlToLoad, function() {
$("#loadingsignature").css("display", "none");
});
}
</script>

Fetch variable in javascript from a link

I am trying to get a PHP variable to send through javascript and I am having trouble. I am using a jQuery popup I found online and when a user clicks an item, I need that item_id variable to be fetchable in the popup where I want to add a form.
My PHP section.
<a href="#?w=500&item_id='.$stock['id'].'" rel="popup1" class="poplight">
and the Javascript.
$(document).ready(function(){
//When you click on a link with class of poplight and the href starts with a #
$('a.poplight[href^=#]').click(function() {
var popID = $(this).attr('rel'); //Get Popup Name
var popURL = $(this).attr('href'); //Get Popup href to define size
//Pull Query & Variables from href URL
var query= popURL.split('?');
var dim= query[1].split('&');
var popWidth = dim[0].split('=')[1]; //Gets the first query string value
var itemID = dim[0].split('=')[2]; //Gets the second query string value
//Fade in the Popup and add close button
$('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('<img src="/layout/close_pop.png" class="btn_close" title="Close Window" alt="Close" />');
//Define margin for center alignment (vertical + horizontal) - we add 80 to the height/width to accomodate for the padding + border width defined in the css
var popMargTop = ($('#' + popID).height() + 80) / 2;
var popMargLeft = ($('#' + popID).width() + 80) / 2;
document.getElementById('popup1').innerHtml = itemID;
//Apply Margin to Popup
$('#' + popID).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
//Fade in Background
$('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
$('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer
return false;
});
//Close Popups and Fade Layer
$('a.close, #fade').live('click', function() { //When clicking on the close or fade layer...
$('#fade , .popup_block').fadeOut(function() {
$('#fade, a.close').remove();
}); //fade them both out
return false;
});
});
I added what I thought you work, but it does not var itemID = dim[0].split('=')[2]; //Gets the second query string value and document.getElementById('popup1').innerHtml = itemID;
Use a sophisticated function to retrieve URL query parameters:
function getParameterByName(name, locationObject)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(locationObject.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
[Adopted from here]
Simply call it like so:
getParameterByName('item_id', someLink);
Working Fiddle: http://jsfiddle.net/ADpYT/
You have a simple oversight in your original code ..
When you obtain your dim variable, you get an array with 2 items split at & . In the above code you get ["w=500", "item_id=some_value"] .So in order to get the itemID you have to use dim[1].
var itemID=dim[1].split('=')[1];

Categories