Execute JavaScript code with PHP $_GET - javascript

I have a bit of coding that displays div's when requested through a link, now I want to be able to link to that page, and execute the JavaScript with the parameter given through the url in PHP.
The JavaScript displays and closes div's when requested through links.
Link example:
Click here for div1
Click here for div2
Click here for div3
JavaScript code:
$('.selectType').on('click', function(e){
e.preventDefault();
var targetDiv = $($(this).attr('href'));
if(!targetDiv.is(':visible')){
$('.hide').slideUp();
targetDiv.slideDown();
}else{
$('.hide').slideUp();
}
});
css for div:
.hide{display:none;}
div code:
<div id="div1" class="hide">Text in div1</div>
<div id="div2" class="hide">Text in div2</div>
<div id="div3" class="hide">Text in div3</div>
I want to give the URL a link like so:
http://www.example.com/pages/index.php?pageid=div2
When that page is visited, the JavaScript will execute as if the link "Click here for div2" was pressed, so that div2 pops up.
I have no idea where to get started, as in, I do know how to grab the $_GET['pageid'] variable, but no clue how to combine it with the JavaScript into displaying the requested div.
Thanks ahead!

First change your hide/show into a function to save repeating code... ie:
var toggleSelectType = function(target) {
var targetDiv = $(target);
if (!targetDiv.is(':visible')) {
$('.hide').slideUp();
targetDiv.slideDown();
} else {
$('.hide').slideUp();
}
};
$('.selectType').on('click', function(e){
e.preventDefault();
toggleSelectType($(this).attr('href'));
});
Add a function that helps you grab query string values such as:
(How can I get query string values in JavaScript?) ** credit
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
Then when the page loads check for the value of pageid and run your function:
var pageId = getParameterByName('pageid');
toggleSelectType('#'+pageId);

Related

My Script load too late

I try to use a script for prefilter ISOTOPE from an other page, but my Isotope script doesn't load my value with the filter value.
You can test by yourself here : http://aprime-industries.com/
Just click on "Nos Références" and click on ENTI for exemple.
You will see my dropdown list is "ENTI" selected but the filter is not active, I need to click on "Indifférent" and click again on ENTI for activate the filter and the data-filter-value.
<option value="ENTI" data-filter-value=".ENTI">ENTI</option>
I will give you my script for link the value from the dropdown list :
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
And
$(document).ready(function(){
var preSelected = getParameterByName("filter");
if(preSelected == "ENTI") {
$('select[name="societe"]').val("ENTI");
}
else if(preSelected == "S2MI") {
$('select[name="societe"]').val("S2MI");
}
else if(preSelected == "JBM41") {
$('select[name="societe"]').val("JBM41");
}
});
And my href link :
<img src="img/entilogo.png" class="" alt="icone ENTI">
<img src="img/s2milogo.png" class="" alt="icone S2MI">
<img src="img/jbm41logo.png" class="" alt="icone JBM41">
I make a jsfiddle for my isotope script JSFIDDLE
Bump ! my deadline is tomorrow :(
it is loading too late because it is inside $(document).ready(function(){}. Window will load first and then the code inside $(document).ready(function(){} will be executed.
So loose $(document).ready(function(){} and keep the script in header to load it before body part loads.
But it is highly recommended to keep the scripts in footer and inside $(document).ready(function(){} since it will load the script at the end of window load and load your html elements faster.

How would I create an HTML page where multiple versions of a div could be shown depending on appeneded URL parameters

What I'm trying to achieve is showing different messages based on something like "?HELLO" being appended onto the URL of a page. For the purpose of this question, the page content could be something as simple as this:
<!doctype html>
<html>
<head>
<title>Dynamic Content</title>
<style>
#container {width:100%height:100px;background:#000;}
#container div {text-align:center;color:pink;}
</style>
</head>
<body>
<div id="container">
<div id="hello">How are you</div>
<div id="goodbye">See you later</div>
<div id="whoAreYou">Get Out</div>
</div>
</body>
</html>
Also I would be interested in knowing how to do this using a single div and getting element by ID. I'm not sure which would work better for me in the end. I might want to add other elements based on the parameters like links or images. A client of mine has an eCommerce site and is considering implementing something like this for customers who land on the site with promocodes which will look like "?SourceCode=HELLO" but I'm assuming a string is a string.
Here is a fiddle although i don't think it will help for testing the URL jsfiddle.net/stormbloom/caqfxx46
Updated
I'm updating the answer to include implementation. It seems that you really want to just change the messaging based on the value of the query string. It's best to then store your messages in a scalable fashion and then just change a single div out.
Step 1 - Get the query parameter value
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var parameter = getParameterByName('SourceCode');
Step 2 - Store Your Messages
var messages = {
hello: "Hi",
goodbye: "Goodbye",
default: "Who are You?"
}
Step 3 - Change Message Based on Value of Query
var changeMessage = function(queryValue) {
var container = $('#container');
container.html(messages[queryValue]);
}
Here's a fiddle: https://jsfiddle.net/wf2x6yua/2/
Here's an example based on #Phillip Chan 's answer and your jsfiddle.
$(document).ready(function() {
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
function setContainerByParam(parameter) {
// hide all divs inside "container"
$("#container > div").hide();
// show divs, based on the given parameter
if (parameter === "hello") {
$("#hello").show();
} else if (parameter === "goodbye") {
$("#goodbye").show();
} else if (parameter === "whoAreYou") {
$("#goodbye").show();
} else {
$("#unknown").show();
}
}
// try to get param "SourceCode" and set divs
var url_param = getParameterByName('SourceCode');
setContainerByParam(url_param);
// try to set divs by simulating different parameters
setTimeout(function(){ setContainerByParam('hello'); }, 2000);
setTimeout(function(){ setContainerByParam('goodbye'); }, 4000);
setTimeout(function(){ setContainerByParam('whoAreYou'); }, 6000);
});
#container {width:100%height:100px;background:#000;}
#container div {text-align:center;color:pink;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="container">
<div id="hello">How are you</div>
<div id="goodbye">See you later</div>
<div id="whoAreYou">Get Out</div>
<div id="unknown">unknown parameter</div>
</div>

How can I search iframe content (text) using an input field that is on the parent page?

Yes, I know something like this has been asked over here before and I have searched but the one that is closest to what I'm trying to achieve doesn't have an answer ( Search iframe content with jquery and input element on parent page ) and the one that does is making use of nested iframes ( Access the content of a nested Iframe ) and I didn't quite understand the solution (VERY new with javascript so please bear with me). Honestly, it's getting a bit frustrating (it's quite late over here) so I thought I might as well ask.
I have an iframe that displays a page from my site therefore the page is from the same domain. What I would like to do is to search the iframe for some text using javascript (not jquery). The search input box, however, is on the parent page.
I've done something similar to this before by putting the search input box in the page displayed in the iframe instead ( I followed this tutorial: http://help.dottoro.com/ljkjvqqo.php ) but now I need to have the search input box on the parent page because I going to make it "sticky" so that it will follow the user as they scroll down the page. I've resized the parent page height to be the same as the length of the page in the iframe by also using javascript.
So, my question is: How can I use javascript to search text that is in the iframe by using a search input box that is on the parent page?
My HTML so far:
<input type="text" name="page_no" size="3"/>
<input type="submit" name="goto" value="Go"/>
<iframe id='iframe2' src="http://example.com/files/<?php echo $filename;?>" frameborder="0" style="text-align:center; margin:0; width:100%; height:150px; border:none; overflow:hidden;" scrolling="yes" onload="AdjustIframeHeightOnLoad()"></iframe>
<script type="text/javascript">
function AdjustIframeHeightOnLoad() { document.getElementById("iframe2").style.height = document.getElementById("iframe2").contentWindow.document.body.scrollHeight + "px"; }
function AdjustIframeHeight(i) { document.getElementById("iframe2").style.height = parseInt(i) + "px"; }
Not sure how to move on from there. I'd really appreciate some help.
Thanks in advance!
EDIT:
The search works now (saw that I put the javascript above the html so I put it under it to get it working) so this is what I want to do with the search results:
I intend to use the search box to enter a page number such that when the user clicks "Go" the search will look for that page and scroll the user down to where the result (that is, the page number) is.
EDIT 2: I just thought I'd mention that my page numbers are written like this: -2- for page 2, -3- for page 3, etc.
I believe this is the solution you need,
HTML:
<!--added an id of search to the input element-->
<input id="search" type="text" name="page_no" size="3"/>
<!--changed input type to button and added an id of go-->
<input id="go" type="button" name="goto" value="Go"/>
<iframe id='iframe2' src="iframe.html" frameborder="0" style="text-align:center; margin:0; width:100%; height:150px; border:none; overflow:hidden;" scrolling="yes" ></iframe>
Javascript(make sure the iframe is in the same domain):
//on click event for the button with an id of go
var go = document.getElementById("go").onclick = function(){//begin function
//get the search value
var search = document.getElementById("search").value;
//get the html of the iframe(must be in the same domain)
var iframe = document.getElementById("iframe2").contentDocument.body;
/*create a new RegExp object using search variable as a parameter,
the g option is passed in so it will find more than one occurence of the
search parameter*/
var result = new RegExp(search, 'g');
//set the html of the iframe making the found items bold
iframe.innerHTML = iframe.innerHTML.replace(result,"<b>" + search + "</b>" );
};//end function
Here is a link that will explain some additional flags you can use with the RegExp object. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
Below is an improved version of Javascript to scroll to Page Number.
Place it inside of your on click event for the go button. The code requires that you place an id with the page number inside of an element at the top of each page. Example <h3 id="3">Page 3</h3>.
//get the search value
var search = document.getElementById("search").value;
//get the id of the search term
var iframe = document.getElementById("iframe2");
//the url of the page loaded in the iframe
var iframeURL = "iframe.html";
//set the source of iframe appending a link to an element id
iframe.src = iframeURL + "#" + search;
Solved! Thanks Larry Lane for your help.
Here is the present Javascript. Hope it helps someone.
<script type="text/javascript">//on click event for the button with an id of go
var go = document.getElementById("go").onclick = function(){//begin function
//get the search value
var search = document.getElementById("search").value;
//put hyphens for the page number
var pagehyph = '-' + search + '-';
//get the html of the iframe(must be in the same domain)
var iframe = document.getElementById("iframe2").contentDocument.body;
//remove the hash from the iframe src if there is one
var url = document.getElementById("iframe2").src, index = url.indexOf('#');
if(index > 0) {
var url = url.substring(0, index);
}
var newurl = url + "#" + search;
/*create a new RegExp object using search variable as a parameter,
the g option is passed in so it will find more than one occurrence of the
search parameter*/
var result = new RegExp(pagehyph, 'g');
//set the html of the iframe and add a page anchor
iframe.innerHTML = iframe.innerHTML.replace(result,"<a id='" + search + "'>" + search + "</a>" );
//set new src for the iframe with the hash
document.getElementById("iframe2").src = newurl;
};//end function
</script>
As you can see from the code, I've added a page anchor so the page scrolls to the page anchor when they click 'Go'.
function myFunction(x) {
var att = document.querySelector("iframe[id=iframe2]").getAttribute(x);
alert(att);
}
<input type="text" name="page_no" size="3"/>
<input type="submit" name="goto" onclick="myFunction(document.querySelector('input[name=page_no]').value)" value="Go"/>
<hr />
<iframe id='iframe2' src="https://www.example.com" frameborder="0" style="text-align:center; margin:0; width:100%; height:150px; border:none; overflow:hidden;" scrolling="yes" ></iframe>

jQuery insert/remove text at specific position in input field/textarea

I am trying to do similar thing as YouTube has when you are embeding a video and you want to get a code. You can click on checkboxes or select size and it dynamically changes the value of input field.
Does somebody have idea how to do it?
I managed to write a code that is replacing the width correctly, but I dont know how to make a code that would add &scheme=XXX at the end of the link or remove it if user selects no color scheme.
This is the code for width,I dont think its best one, but works:
$("#width").on("change keyup", function(){
var width = $(this).val();
if (width){
$("#embed-text").val($("#embed-text").val().replace(/ (width\s*=\s*["'])[0-9]+(["'])/ig, ' width=\''+width+'\''));
}
});
Here is textarea which I am trying to change and inputs I'm using for it:
The ID is taken from PHP, in actual textarea that jQuery sees the ".$id." is actual number
<textarea class='clean' id='embed-text'><iframe src='http://my.url/embed/?r=".$id."' width='600' height='".$height."' frameborder='0' marginwidth='0' marginheight='0' allowtransparency='true'></iframe></textarea>
<div style='padding-right: 10px; display: inline-block;'>
Color scheme:
<select id='schemes' class='clean'>
<option value='-'>None</option>
<option value='xxx'>Xxx</option>
</select>
</div>
<div style='padding-right: 10px; display: inline-block;'>
Width: <input type='number' min='250' max='725' value='600' id='width' class='clean'>
</div>
When user does not select any scheme (or changes from XXX to None), I want link in textarea (iframes src) to be like this:
http://my.url/embed/?r=X
But when he selects any scheme, i would like it to look like this:
http://my.url/embed/?r=X&scheme=XXX
I actually have no idea how to do this. Tried googling for more than hour, but I don't know what the ID will be (to identify position where to add the string), thats PHP value and I cant pass it to external script file, so I tried to find if I can insert something at specific position (ie.: 15th character from start) with JS, but could not find anything.
Thanks.
I separate some functions in order to keep the code clean check this I think that is what you were looking for JsFiddle
var generateUrl = function(id,colorScheme) {
var baseUrl = "http://my.url/embed/?";
var url = baseUrl.concat("r="+id);
if (colorScheme != null && colorScheme != '')
url = url.concat("&scheme="+colorScheme);
return url;
};
var changeUrl = function(id, colorScheme) {
var url = generateUrl(id, colorScheme);
var srcPattern = "src='(.*?)'";
var embedText = $("#embed-text").val();
var newEmbedText = embedText.replace(new RegExp(srcPattern),"src='"+url+"'");
$("#embed-text").val(newEmbedText);
};
var changeWidth = function(newWidth) {
var widthPattern = "width='([0-9]*)'";
var embedText = $("#embed-text").val();
var newEmbedText = embedText.replace(new RegExp(widthPattern),"width='"+newWidth+"'");
$("#embed-text").val(newEmbedText);
};
var getURLParameter = function(url,parameterName) {
return decodeURIComponent((new RegExp('[?|&]' + parameterName + '=' + '([^&;]+?)(&|#|;|$)').exec(url)||[,""])[1].replace(/\+/g, '%20'))||null
};
var getId = function() {
var urlPattern = "src='(.*?)'";
var embedText = $("#embed-text").val();
var url = embedText.match(new RegExp(urlPattern))[1];
var id = getURLParameter(url, 'r');
return id;
};
$("#width").on("change keyup", function(){
var width = $(this).val();
var colorScheme = $(schemes).val();
changeWidth(width);
changeUrl(getId(),colorScheme);
});
And i removed the value '-' for the first option just leave it in blank.

button doesn't dissapear onClick (JavaScript)

I have the following code for making the button not visible and it works for a second and then button comes again. The links on navigates on the same page
I have tried "return false;" but then my navigation doesn't work.
What to do for keeping the button hidden?
JavaScript
function btn_hide(){
document.getElementById("btn_shfaqe").style.display="none";
}
html
test1
You have to do two things; Return the function and return false, like this:
javascript
function btn_hide(){
document.getElementById("btn_shfaqe").style.display="none";
return false;
}
html
test1
Here's a DEMO
EDIT according to comment
You are better off hiding the button serverside, but if you really want to use javascript you can do this on page load:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
window.onload = function() {
var vid_id = getParameterByName('vid_id');
if (vid_id == 0 || vid_id == 5) {
document.getElementById("btn_shfaqe").style.display="none";
}
}
It is an anchor tag . I will navigate you to another page .
If you don't want to navigate to another page you may use
javascript:void(0)
as
<a href="javascript:void(0)" onclick="btn_hide();">
Try this fot javascript :
<script>
function visibilite() {
var targetElement = document.getElementById(\'div_connexion\');
targetElement.style.display = "none";
}
</script>
and this in the html :
<div id="div_connexion"><a class="connexion" href="javascript:visibilite();">Connexion</a></div>
I have this on my website and when I click on the div it desapear until the user refresh the page.
The links on navigates on the same page I have tried "return false;" but then my navigation doesn't work.
You want to hide the link and still be able to navigate?
There are two ways of solving the problem:
Server-side: add a parameter to your url, like so: ?tip=fin&vid_id=0&hideButton=1 and on server side apply the display: none; style to your element if it is set. If you're using PHP, something along the lines of the following should do the trick:
<?php if (isset($_GET['hideButton'])) { echo 'style="display: none;"'; }
Client-side: write some flag value to localStorage when button is clicked. When the page is loaded, check if the flag is set. If it is set - hide the anchor.
// Onclick handler:
myButton.addEventListener('click', function () {
localStorage.setItem('hideButton', 'yes');
}, false);
// Onload handler:
window.addEventListener('load', function () {
if (localStorage.getItem('hideButton') === 'yes') {
myButton.style.display = 'none';
}
});
Using one of these ways will hide the link while keeping navigation working. You don't even need to hide the button in the onclick event handler.
Please try with thw below code snippet.
<head runat="server">
<title></title>
<script type="text/javascript">
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
function btn_hide() {
document.getElementById("btn_shfaqe").style.display = "none";
}
</script>
</head>
<body>
<div>
<button id="btn_shfaqe" style="display: none">
jayesh</button>
test1
<script type="text/javascript">
if (getParameterByName("tip") == "") {
document.getElementById("btn_shfaqe").style.display = "";
}
</script>
</div>
</body>
</html>

Categories