how is it possible to achieve this:
http://jennamolby.com/how-to-display-dynamic-content-on-a-page-using-url-parameters/
using php?
let's say that I have the following a url:
http://localhost:8888/index.php?page=pages-folder/works-folder/content-manager?article=my-article
to get there I have a link in pages-folder/works.php :
link
which should open content-manager.php in which inside a div I should load my-article.php
EDITED:
I have an index file in which a load into the div.container all the pages I need, so in this case my works.php file is loaded int the div.container using using:
<?php
$page = $_GET['page'];
if(!empty($page)){
$page .= '.php';
include($page);
}
else {
include('pages/home.php');
}
since I also needed to update the url without reloading the page I use this script:
function ChangeUrl(page, url) {
if (typeof (history.pushState) != "undefined") {
var obj = { Page: page, Url: url };
history.pushState(obj, obj.Page, obj.Url);
}
}
$('ul.menu li a').on('click', function(){
var page = $(this).attr('href');
var pageUrl = page.split("/");
pageUrl = pageUrl[1];
$('.container').load(page + '.php', function(){
//fadeout old content
//fadein new content
});
ChangeUrl('Page1', '?page=' + page);
return false;
})
once I have my works.php loaded into the div.container I have the above mentioned link which should lead me to: pages-folder/works-folder/content-manager.php
it is in this page where I'd like to load my-article.php inside the main div of content-manager.php
I thought that adding the ?article= variable would have worked using the same system as above:
$article = $_GET['article'];
if(!empty($article)){
$article .= '.php';
include($article);
}
else {
...
}
but it doesn't...
how can I achieve this?
Why you don't just add you article as a query param ?
http://localhost:8888/index.php?page=pages-folder/works-folder/content-manager&article=my-article
and make a link like this
link
This is just an exemple to understand what you want to do, don't use this kind of code in production, he is vulnerably to CSRF attack
EDIT: with echo it's better sorry
I haven't answered your question per se but this is the sort of code you are looking for:
<?php if (isset($_GET["page"]) && strtolower($_GET["page"]) == "1") { ?>
<p>You are on page one</p>
Back
<?php } elseif (isset($_GET["page"]) && strtolower($_GET["page"]) == "2") { ?>
<p>You are on page two</p>
Back
<?php } else { ?>
<p>You have not selected a page. Click one of the links:</p>
Page one
Page two
<?php } ?>
Explanation
How does $_GET work?
$_GET is a super global variable - meaning it can be accessed from anywhere.
It is a an associative array of variables passed to the current script via the URL parameters.
These are specified following a question mark (?) in the URL. To specify multiple parameters you must use the ampersand (&) character between each one.
$_GET must be specified at the end of the URL after everything else.
http://www.example.com/thisPage.php?page=a
http://www.example.com/thisPage.php?page=a&theme=light
The first URL will produce a $_GET with one element which can be accessed as: $_GET["page"] and would return a string of one character a.
The second will produce:
$_GET["page"]; // returns "a"
$_GET["theme"]; // returns "light"
Notice that for each parameter a new key-value pair is created.
I wrote a comprehensive explanation of superglobals on SO Documentation, but that has since been deprecated. RIP my hard work :P
Showing differing content
As you can see from my answer above. You can use simple if statements to check what the value is.
Firstly, ensure that $_GET isset and then check the value.
I have converted the value of the array to lowercase since "A" is not the same as "a".
The example you linked to really over-complicates things. There is honestly no need for all that regular expressions, and it also relies on JavaScript which is not necessarily a good idea.
With my example at the top, there is no difference between user experience as PHP is server sided thus all the content is worked out and then served to the user.
One step further
Using this you can go that extra step and have an event listener and combine it with AJAX.
Altering my initial example you can have the following.
I have used the jQuery library as it is a lot easier to implement.
<div id="test">
<?php if (isset($_GET["page"]) && strtolower($_GET["page"]) == "1") { ?>
<p>You are on page one</p>
Back
<?php } elseif (isset($_GET["page"]) && strtolower($_GET["page"]) == "2") { ?>
<p>You are on page two</p>
Back
<?php } else { ?>
<p>You have not selected a page. Click one of the links:</p>
Page one
Page two
<?php } ?>
</div>
function myAJAX() {
$("a").on("click", function(e) {
e.preventDefault();
// get the clicked page number
if (this.href.indexOf("&") > -1) {
var d = this.href.substring(this.href.indexOf("page=") + "page=".length, this.href.indexOf("&"))
} else {
var d = this.href.substr(this.href.indexOf("page=") + "page=".length)
}
$.ajax({
method: "GET",
url: "t.php",
data: "page=" + d,
success: function(data, textStatus, jqXHR) {
// change the content of the #test div
$("#test").html($($.parseHTML(data)).filter("#test")[0]);
myAJAX();
}
});
});
}
myAJAX();
Notice that the HTML is not being wrapped in <div id="test"> which is so that the JavaScript can find that element and change it in the function.
$("#test").html($($.parseHTML(data)).filter("#test")[0]); is the line that is fetching the HTML and changing it with the data from the page you tried to click on.
I also call the function inside itself so that it will reattach on the anchor links. If you remove this line then the page will redirect as normal.
The good thing about this implementation is that if your user does not have JavaScript then the page will act as normal and there will be a normal reload of the site.
No need for any extra work on your part.
Related
I know this is almost duplicated, a lot of people asked that and a lot answered them by PHP Form but I really didn't find anything for my problem.
I have a page called platforms.php and this page has a group of image-links which are: Windows,Mac, Android and iOS.
So what I want is when somebody clicks the Windows link (as an example) they go to a page called download.php and the page should say You are using Windows!.
Please not that I don't want to create a page for every link, I want it to be one page only.
Thanks in advance!
Make URL like that
<a href = "http://example.com/download.php?device=window" >Window</a>
<a href = "http://example.com//download.php?device=mac" >Mac</a>
On your page download.php
if(isset($_GET['device'])) {
$device = $_GET['device'];
}
if ($device == 'window' ) {
// window message here
} elseif ($device == 'mac' ) {
// mac message here
}
send an extra parameter in your url and then in the same single page use the condition like:
let the parameter name be 'pagetype'.
download.php
if ($_REQUEST['pagetype'] == 'windows')
{
//your output for windows
}
else if ($_REQUEST['pagetype'] == 'mac')
{
//your output for mac
}
else if(..)
{
.
.
.
Note:
You can replace $_REQUEST, with $_GET or $_POST, depending on method you use to post data to this page
You can have an HTML link and send the data through GET parameters. Something like (in platforms.php):
<a href="download.php?os=Windows >Windows</a>
<a href="download.php?os=Mac >Mac</a>
<a href="download.php?os=Android >Android</a>
<a href="download.php?os=iOs >iOs</a>
And then in downloads.php, getting the variable "os" and do whatever you want with it:
if ( isset($_GET['os'] ) ) {
echo "You are using " . $_GET['os'];
}
you can add image like
<img src="window.jpg"/>
<img src="ios.jpg"/>
and on download.php page you can check
$value = $_GET['key'];
if(value== 'window')
if(value== 'ios')
etc
hope this is what you want.
I am trying to send data to a index page when a link on that page is clicked. the index.php page looks like this:
include "../app/bootstrap.php";
include ("../src/controllers/DisplayContentsController.php");
$data = new DisplayContentsController();
$link = (isset($_POST['link']) ? $_POST['link'] : null);
if ($link != null)
{
$data->show($twig, $starting_file_path . '/' . $link);
$starting_file_path = $starting_file_path . '/' . $link;
}
else
{
$data->show($twig, $starting_file_path);
}
and on the Twig template that is loaded I have this:
<script>
jQuery('.show_content').click(function(e)
{
e.preventDefault();
var href = jQuery(this).attr('href');
jQuery.post(window.location, { link: href });
});
</script>
I want to reload the page with the new link that way it loads the correct directory. But when I do the jQuery.post() the content that is displayed does not change. Can someone help my find out what is going wrong and how I can accomplish this?
The output from the POST request would be returned on the success handler function. For example, you would need to do something like this:
jQuery('.show_content').click(function(e)
{
e.preventDefault();
var href = jQuery(this).attr('href');
jQuery.post(window.location, { link: href } , function(data){
//data will have the new HTML after the page posted back. You can use that
//HTML to load if onto an element on the page. Something like:
$('#content_result').html(data);
});
});
Assuming you have a div with "id = content_result" -or something like that- that you can use to load the HTML into it.
If you want to append the result to the existing HTML already displayed inside #content_result then simply do:
$('#content_result').html($('#content_result').html()+data);
Now, keep in mind that this will return everything - the full page - and if you blindly keep appending things, you'll end up with a page that does not conform to valid HTML -for example, a page with more than 1 <head>,<body> sections, etc. The best thing to do is to extract the section that you really care about, and append only that section such that you always end up with a valid HTML document.
jQuery offers plenty of options to do this sort of thing.
EDIT:
Adding the following to the code below:
alert(LogoutURL);
shows the URL is coming across to the JS variable incorrectly. Is seems to be "encoded" once passed to the JS var.
I know this from executing in my PHP the following:
<?php echo wp_logout_url('/') ?>
as this writes the correct URL to the page. Any help is appreciated. Thanks
I am sure this one is straightforward but I have not been able to find how to do this. Maybe I have asked the question wrong... I am trying to insert the "logout with no confirmation" link in WordPress but the URL I pass the menu does not resolve correctly. The menu is part of a theme so I cannot easily modify it.
As such I am using a combination of JS and PHP to generate the link for the current logged in user, by changing the "href" in the "a" item containing "Logout" text, to the output of "wp_logout_url" as follows:
<script type="text/javascript">
jQuery( document ).ready(function() {
/*** change Logout URL if logged in ***/
var LogoutURL = "<?php echo wp_logout_url('/') ?>";
jQuery('a').filter(function(index) { return jQuery(this).text() === "Logout"; }).attr("href", LogoutURL);
My resolved menu code:
<li id="menu-item-5516" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-5516">
Logout
</li>
When the JS inserts the resolved URL it seems to add "amp;" to it in places where it found "&". I even tried without success to use "encodeURI()" function.
How can I pass the URL to the HREF "as is"?
The issue seems to be that wp_logout_url is correctly changing & to &, and then jQuery must be again changing & to & resulting in &.
The hacky solution is to simply do
jQuery('a').filter(function(index) { return jQuery(this).text() === "Logout"; })
.attr("href", LogoutURL.split("&").join("&"));
Also, if you parent li elements id doesn't change, it would be far more efficient to do
$("#menu-item-5516").find("a").attr("href", ...);
Rather than run a filter on all of the a elements. If not I would still find a better way to select that element, checking every link in the document is overkill.
Note: You SHOULD have one amp; after every & in a link. That is CORRECT. If you DON'T want that, you can do
jQuery('a').filter(function(index) { return jQuery(this).text() === "Logout"; })
.attr("href", LogoutURL.split("&").join("&"));
Well this did it... still not sure why this is required. Am I pulling into the JS the url incorrectly?
var LogoutURL = "<?php echo wp_logout_url('/') ?>";
jQuery('a').filter(function(index) { return jQuery(this).text() === "Logout"; }).attr("href", LogoutURL.replace(/&/g, "&"));
This is my solution to place a logout link in my menu's list item with class "logout". The link now carries me through to the login page without the "oops ... do you really want to logout?":
PHP - replacing & with &:
$logouturl = str_replace('&','&',wp_logout_url(home_url() . "/wp-login.php?loggedout=true"));
jQuery - replacing href in li.logout a:
logoutUrl = '<?php echo $logouturl; ?>';
jQuery('li.logout a').attr('href',logoutUrl);
Is there a way to call a (jquery action/write an html text) to a div of a new page after calling the window.location command?
Im trying to make an ajax form submit where the user will be redirected to a new page upon submit,
and in that new page a hidden div will appear with text inside of it
currently this is my code
script.js
$.ajax({
url:url,
type:'POST',
data:datastr,
success:function(result){
if(result=="duplicate"){
$("#status").attr('class', 'span12 alert alert-error');
$("#status").show();
$("#status").html("<h4><center>Duplicate Username</center></h4>");
$("#dept_name").closest(".control-group").attr('class', 'control-group');
$("#username").closest(".control-group").attr('class', 'control-group error');
$("#password").closest(".control-group").attr('class', 'control-group');
$("#username").focus();
}
else{
$("#dept_name").closest(".control-group").attr('class', 'control-group');
$("#username").closest(".control-group").attr('class', 'control-group');
$("#password").closest(".control-group").attr('class', 'control-group');
window.location = base + 'admin/departments/edit_dept/' + result;
}
}
});
i want to make this block of code below work on the page where window.location is going
$("#status").attr('class', 'span12 alert alert-error');
$("#status").show();
$("#status").html("<h4><center>Successfully added Department</center></h4>");
is it possible?
thanks
You can use CI session flash data.
http://ellislab.com/codeigniter/user-guide/libraries/sessions.html
Before triggering window.location, set the message in flashdata. On the landing/redirected-to page, check to see if flashdata has a value (success/failure). If so, display (or trigger a js method to show) the message.
You could add a parameter with your window.location, like:
window.location = base + 'admin/departments/edit_dept/' + result + '?showMessage=12'
Then on the next page, have a jquery script that looks for that parameter and shows the message. See this question.
Or you can do it in on the server. But with jquery it works with static html too.
This is a patchup, May require some tuning though.
window.location = base + 'admin/departments/edit_dept/' + result+'/err'; //changed to catchup with the view part
In the Controller:
<?php
if($this->uri->segment(4) == "err"){
$data['err'] = true; #will reflect that we need to show the js in the view
$this->load->view('view', $data);
}
?>
In the view part:
<?php if(isset($err)){ ?>
<script type="text/javascript">
$("#status").attr('class', 'span12 alert alert-error');
$("#status").show();
$("#status").html("<h4><center>Successfully added Department</center></h4>");
</script>
<?php } ?>
i am trying to call a external HTML page to be displayed on website based on javascript conditions.
The code is like this
<script language="JavaScript" src="http://j.maxmind.com/app/country.js"></script>
<script type="text/javascript">
var country = geoip_country_code();
if (country == "US")
{
document.write("http://www.mywebsite.com/1.html");
}
else if (country == "GB")
{
document.write("<a href='#'><img src='http://www.image2.com' ><a/>");
}
else
{
document.write("<a href='#'><img src='http://www.image3.com' ><a/>");
}
</script>
Now, instead of showing the content of HTML page to US visitors, it just display "http://www.mywebsite.com/1.html" as plain text.
I am missing a function to call external HTML. Can someone help? Thanks
Do you mean the <iframe> element?
document.write('<iframe src="http://www.mywebsite.com/1.html"></iframe>');
Since <iframe> cannot resize itself to match the size of its content, be sure to give it a width/height attribute or style (if you know the actual size of content).
Spitting the text of a URL into a page doesn't magically grab the contents of that page. This type of activity usually happens on the SERVER where your server will fetch the content from another page and serve it up as part of YOUR page. JavaScript is the wrong tool for this job.
this kind of thing is really better to do server-side with stuff like php but here's a function I use in a lot of my commercial jobs. Again, I don't condone the use of this function for loading entire pages, but it's a really handy one to have in your toolbox. If anyone says you have to use JQuery to do this, kick them for me. ^_^
function fetchHTML(url)
{
if( 'undefined' == typeof(url) ) return false;
if( document.all ){
p = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
p = new XMLHttpRequest();
}
rnd = Math.random().toString().substring(3);
if( url.indexOf('?') > -1 )
{
url+='&rnd='+rnd;
}
else
{
url+='?rnd='+rnd;
}
p.open("GET",url,false);
p.send(null);
return p.responseText;
}
well, you are giving a string to document.write() function, and that's why it is displaying the string that it was supposed to display. If you want to display content of some other page you have two choices either you can use an <iframe> or use ajax.