Fetch variable in javascript from a link - php

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];

Related

How to change html anchor tag query string

It is known that URL with querystring parameter can be rewritten with .htaccess. For example
localhost/mynews/category.php?cat=news&subcat=9
To
localhost/mynews/news/9
But is there any way to customize anchor tag
which is shown in bottom left corner while hovering link.
localhost/mynews/category.php?cat=news&subcat=9
to
localhost/mynews/news/9
PHP, jquery/javascript or htaccess, any way can we customize ?
On hover you can get your anchor href get querystring value rebuild url and set new url using attr in anchor tag.
var link = '';
$("a").hover(function() {
link = $(this).attr('href');
var var1 = $.urlParam('cat', link);
var var2 = $.urlParam('subcat', link);
var url = link.split('?')[0] + '/' + var1 + '/' + var2;
$(this).attr('href', url);
}, function() {
$(this).attr('href', link);
});
$.urlParam = function(name, link) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(link);
if (results == null) {
return null;
} else {
return decodeURI(results[1]) || 0;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hover Me
Note: I take urlParam function from https://stackoverflow.com/a/25359264/965146 and slightly modified it. Rest code are mine.You must reset your url when anchor click may be routing didn't get your new url

How to add extra space to div using Jquery?

I am working on the sticky menu and highlight menu based on div id in WordPress. I have completed code well but I got a problem.
I have a sticky header when I click menu item in side sticky menu title going back to header title not visible.
I want result like this.'
How can I solve this?
My Jquery Code
jQuery(function($) {
/**
* This part causes smooth scrolling using scrollto.js
* We target all a tags inside the nav, and apply the scrollto.js to it.
*/
$("#nav a").click(function(evn){
evn.preventDefault();
$('html,body').scrollTo(this.hash, this.hash);
});
var aChildren = jQuery("#nav li").children(); // find the a children of the list items
var aArray = []; // create the empty aArray
for (var i=0; i < aChildren.length; i++) {
var aChild = aChildren[i];
var ahref = jQuery(aChild).attr('href');
console.log(ahref);
aArray.push(ahref);
} // this for loop fills the aArray with attribute href values
$(window).scroll(function(){
var windowPos = $(window).scrollTop()+70; // get the offset of the window from the top of page
console.log('Window Position:'+windowPos);
var windowHeight = $(window).height(); // get the height of the window
var docHeight = $(document).height();
for (var i=0; i < aArray.length; i++) {
var theID = aArray[i];
//console.log(theID);
var divPos = $(theID).offset().top-150; // get the offset of the div from the top of page
console.log('Div Position:'+divPos);
var divHeight = $(theID).height(); // get the height of the div in question
if (windowPos >= divPos && windowPos < (divPos + divHeight)) {
$("a[href='" + theID + "']").addClass("nav-active");
} else {
$("a[href='" + theID + "']").removeClass("nav-active");
}
}
if(windowPos + windowHeight == docHeight) {
if (!$("#nav li:last-child a").hasClass("nav-active")) {
var navActiveCurrent = $(".nav-active").attr("href");
$("a[href='" + navActiveCurrent + "']").removeClass("nav-active");
$("#nav li:last-child a").addClass("nav-active");
}
}
});
});
You need to offset the height of the heading when you jump to an anchored section.
Are you using the jQuery scrollTo plugin? If you can do something like:
$("#nav a").click(function(evn){
evn.preventDefault();
$('html,body').scrollTo(this.hash, 800, {offset: {top:-80, left:0} });
});
Options for scrollTo found here: http://demos.flesler.com/jquery/scrollTo/

Redirecting and then run function on another page?

So I have the code:
header("Location: ".$config['site_url']."index.php#login-box");
Which is my attempt to trigger the html code for a jquery login form if the user is not logged in:
<li><a class="log" href="#login-box"><span class="hover" style="opacity: 0;"></span></a></li>
But when it runs all it does is add #login-box to then end of my url and doesn't trigger the #login-box href. Pretty lame attempt I know, but any ideas?
This is the jquery script, how would I add the code you mentioned to it properly?
$(document).ready(function() {
$('a.login-window2').click(function() {
//Getting the variable's value from a link
var loginBox = $(this).attr('href');
//Fade in the Popup
$(loginBox).fadeIn(300);
//Set the center alignment padding + border see css style
var popMargTop = ($(loginBox).height() + 24) / 2;
var popMargLeft = ($(loginBox).width() + 24) / 2;
$(loginBox).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
// Add the mask to body
$('body').append('<div id="mask"></div>');
$('#mask').fadeIn(300);
return false;
});
// When clicking on the button close or the mask layer the popup closed
$('a.close, #mask').live('click', function() {
$('#mask , .login-popup').fadeOut(300 , function() {
$('#mask').remove();
});
return false;
});
});
</script>
Here is a little snippet that should do the trick, using jQuery as you mentioned:
$(function(){
$("a.login-window2").click(function(){
//Getting the variable's value from a link
var loginBox = $(this).attr("href");
//Fade in the Popup
$(loginBox).fadeIn(300);
//Set the center alignment padding + border see css style
var popMargTop = ($(loginBox).height() + 24) / 2;
var popMargLeft = ($(loginBox).width() + 24) / 2;
$(loginBox).css({
"margin-top" : -popMargTop,
"margin-left" : -popMargLeft
});
// Add the mask to body
$("body").append("<div id=\"mask\"></div>");
$("#mask").fadeIn(300);
return(false);
});
// When clicking on the button close or the mask layer the popup closed
$("a.close, #mask").live("click", function(){
$("#mask , .login-popup").fadeOut(300, function(){
$("#mask").remove();
});
return(false);
});
// Check the hash
var hash = $(location).attr("hash");
if(hash == "#login-box") {
$("a.login-window2").click();
}
});
Put this in your index.php file and run your code from inside the if statement.
It's a mistake in your code.
Use: name="#login-box"
instead of: href="#login-box"

Fetch particular field from moodialog and pass value to parent screen

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();
}

How can I append a value from the database to an anchor tag's href attribute?

I am using a popup jquery that pops up a static block of code using a href=#?w=300?h=200 but I need apart from the size to pass a variable from a sql database also a href=?prop_id=$id . I have tried to combine both of them but nothing seems to work does anybody has a clue??
thank you
$(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
//Fade in the Popup and add close button
$('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('<img src="to_use/close.png" class="btn_close" title="Close Window" alt="Close" />');
//Define margin for center alignment (vertical horizontal) - we add 80px to the height/width to accomodate for the padding and border width defined in the css
var popMargTop = ($('#' + popID).height() + 80) / 2;
var popMargLeft = ($('#' + popID).width() + 80) / 2;
//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 - .css({'filter' : 'alpha(opacity=80)'}) is used to fix the IE Bug on fading transparencies
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;
});
});
A simpler approach would be to use data- attributes in combination with jQuery's .data() method
HTML
Text
JS
/* in click handler */
var data=$(this).data();
var propId=data.propId;/* same as $(this).data('propId') */
var popWidth=data.w;
/* etc..*/

Categories