Refresh page with data from $.post() - javascript

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.

Related

How to get URLs from referring page in jQuery

I need to get URLs from my referring page via jQuery. The URLs are inside an <a> element that looks like this in HTML:
<a href="http://localhost/sr19repairables/vehicles/repairables/2011-chrysler-town-country-touring-minivan-4d/" title="2011 Chrysler Town & Country Touring Minivan 4D">
There are multiple <a> elements on the referring page and I need to get the URLs from all of them and put them in an array. Any help?
I have a button on my second page with this jQuery attached to it:
$(document).ready(function(){
$(".single_vehicle_previous_button").click(function(){
var referrer = document.referrer;
if (document.referrer == "http://localhost/sr19repairables/vehicles/rebuilt-vehicles") {
alert(value=referrer);
};
if (document.referrer == "http://localhost/sr19repairables/vehicles/repairables/") {
alert(value=referrer);
};
if (document.referrer == "http://localhost/sr19repairables/vehicles/") {
alert(value=referrer);
};
});
});
So if my referring page is one of these three, I want it to get the URLs in the anchors on those pages. The alert is just for testing purposes. Does that help clear things up?
If you already know it's on the same site (as you've checked the url), then you shouldn't have the usual problems with loading random pages via ajax.
You can use $.ajax to get the page, then jquery to parse the html returned:
$.ajax(document.referrer)
.done(function(html) {
var urls = $("<div/>").html(html)
.find("a")
.map(function(i, e) { return $(this).attr("href"); }
});

load article inside a page php

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.

Wordpress - Allow older and newer post buttons navigate to a ID

I am looking for a way to modify the below PHP to allow the addition of a ID that once pressed will navigate the user to the start of the blog posts instead of the top of the page.
<div class="post-navigation">
<?php next_posts_link( 'Older Posts', $wp_query ->max_num_pages); ?>
<?php previous_posts_link( 'Newer Posts' ); ?>
</div>
I feel like this is somethign that should be possible without a plugin although I have found a plugin that would allow me to do this piece of functionality.
The intended story would go something like this:
User clicks on 'older' or 'newer' button that would have in the url something like domainName.co.uk/page/2#startofposts
The user then would have the browser refresh and instead of the page being loaded at the top it would be loaded where the ID 'startofposts' would be in the DOM.
Anyone done this without a plugin?
Cheers
jQuery(document).ready(function() {
var startID = '#post-container';
var urlString = window.location;
var caseSearch = '/page/'
if(urlString.indexOf(caseSearch) != -1 {
jQuery(window).scrollTop(jQuery(startID).offset().top);
}
}
this should do the trick. There are better ways to do this but for a quick solution id should be fine.
In the end I appended the wanted ID onto the end of the anchors manually.. preventing me from having to do anything too fancy.
$('.post-navigation a').each(function () {
var current = $(this);
var href = current.attr("href");
current.attr("href", href + '#post-container');
});

Link an external url to the Title in Colorbox

I am trying to add an external link to the Title in the images in colorbox, so that by clicking the title leads to an external page. Have added custom field in the posts( I am using Wordpress) and given key = 'url' and value = an external link, say http://facebook.com. Have around 10 images on my page.
I am calling the following in the jQuery ready function in my home.php, which further calls a loop.php to display the images in hp-thumb format. .
<script type="text/javascript">
jQuery(document).ready(function($) {
var keyValues = new Array();
keyValues = <?php echo get_post_custom_values('url');?>
var newLandingPage = keyValues[0];
$("a[rel='colorbox']").colorbox({title:function() {
return 'Go For This';
}
});
</script>
The problem is this is not displaying the Title at all. Where am I going wrong?
Thanks in Advance.
I got the solution. It was a small syntax mistake in php.
I needed to use:
var newLandingPage = keyValues['0'];
And I am done.

jQuery load local iframe url with escaped characters for disqus commenting

I'm loading a custom page type that is just comments for a post. This is so I can use Disqus threads for easier usability when multiple loop posts are on a single page.
When loading an iFrame with the following structure I keep getting this syntax error. Are my escape characters wrong?
$(".boxyComments a").click(function (event) {
event.preventDefault();
var post_id = $(this).attr("rel");
$(".commentsIframeBig")
.get(0).contentWindow.location.href =
$("<?php echo get_site_url(); ?>","\/ajax-post-fold\/",post_id);
What's happening is the get retrieves the Wordpress hook to print the site url (in this case it prints http://whateverdomainex.com for the 1st call, 2nd should print /ajax-post-fold/ and the last call should print the post ID so the entire url ends up printing as http://whateverdomanex.com/ajax-post-fold/2825.
Instead my Chrome console gives me the following message:
Uncaught Error: Syntax error, unrecognized expression: /ajax-post-fold/
Update
I've put this variable into place and called it rather than the $("<?php echo get_site_url(); ?>","\/ajax-post-fold\/",post_id); as the get reference:
var postLink = $("<?php echo get_site_url(); ?>"+"\/ajax-post-fold\/"+post_id);
Implemented as such:
$(".boxyComments a").click(function (event) {
event.preventDefault();
var postLink = $("<?php echo get_site_url(); ?>"+"\/ajax-post-fold\/"+post_id);
var post_id = $(this).attr("rel");
$(".commentsIframeBig")
.get(0).contentWindow.location.href = postLink;
Which gives me the following Chrome message:
Uncaught Error: Syntax error, unrecognized expression: http://www.theciv.com/ajax-post-fold/28448
The URL that should be in the src attribute for the iFrame looks like it should be fine and good to go, so why is this syntax error still being output?
UPDATE
var postLink = "<?= site_url('\/ajax-post\/'); ?>"+post_id;
$(this).closest(".boxy").find(".commentsIframeBig")
.css("display","block")
.animate({height: "100%"}, 500)
.get(0).contentWindow.location.href = postLink;
With the proper structure above, the custom page is now loading in the iFrame. However the additional construct of +page_id which includes the rel attribute containing the post's id isn't loading properly.
Moreover when calling the new url as it's original custom page template, then adding the post's id does not load the correct page with post id. Confused yet? Read it again. Took me awhile to write that sentence.
In any case, now my mission to have the post id load when adding the custom page and the post_id as an added string for the iFrame's url to load properly.
update
Here is final working code to load Disqus comments into same page, pseudo multiple times.
Basically this is pushing a post id to the end of a custom page type, resulting in the post's content and attributable elements being loaded into the custom page template.
When stripping that custom page template down to just show the comments for the page, you can create a load/unload reaction whereby you are only calling Disqus once, removing that instance and then loading it again when another Load Comments button is clicked within a subsequently loaded post on the same page. Yay. Multiple Disqus commenting on one page with minimal Ajax loading.
Here is the structure et al that is almost working for me. Only 2 bugs left. First is the secondary load when emptying, then reloading the new Disqus page into the Ajax element using the .ajaxComplete() callback function.
What's happening now is the callback is basically not being fired at all. As far as I can tell. Clicking on it a second time however, does make the call. But this is due to the class parameters being met for the else statement.
Second bug left is I'm having a hard time figuring out how to get the appropriate elements to enlarge, while leaving the others the same size.
// Load comments and/or custom post content
$(".boxyComments a").click(function (event) {
event.preventDefault();
$.ajaxSetup({cache:false});
var post_id = $(this).attr("rel"); var excHeight = $(this).closest('.boxy').find('.initialPostLoad').height();
var postHeight = $(this).closest('.boxy').find('.articleImageThumb').height();
var postWidth = $(this).closest('.boxy').find('.articleImageThumb').width();
// close other comments boxes that may already be open
if($('.commentsOpen').length ) {
console.log('comments are open');
$('.bigBoxy').closest('.boxy')
.animate({height:(postHeight + excHeight)}, 500);
$('.showComments')
.removeClass('bigBoxy')
.removeClass('commentsOpen');
$('.commentsAjax')
.empty(function(){
$(this).closest(".boxy").find(".showComments")
.addClass("commentsOpen")
.addClass("bigBoxy");
$(".bigBoxy").find(".commentsAjax ")
.css("display","block")
.animate({height: "500px"}, 500)
.load("http://<?php echo $_SERVER[HTTP_HOST]; ?>/ajax-post/",{id:post_id});
$(this).closest(".boxy")
.ajaxComplete(function() {
var excHeight = $(this).closest('.boxy').find('.initialPostLoad')
.height();
var postHeight = $(this).closest('.boxy').find('.articleImageThumb')
.height();
$(this).closest(".boxy").animate({height: (postHeight + excHeight)}, 500)
});
});
} else {
$(this).closest(".boxyComments").find(".showComments")
.addClass("commentsOpen")
.addClass("bigBoxy");
$(this).closest(".boxy").find(".commentsAjax")
.css("display","block")
.animate({height: "500px"}, 500)
.load("http://<?php echo $_SERVER[HTTP_HOST]; ?>/ajax-post/",{id:post_id});
$(this).closest(".boxy")
.ajaxComplete(function() {
var excHeight = $(this).closest('.boxy').find('.initialPostLoad')
.height();
var postHeight = $(this).closest('.boxy').find('.articleImageThumb')
.height();
$(this).closest(".boxy").animate({height: (postHeight + excHeight)}, 500)
});
}
});
Okay, here's full working code to do what you want. You'll have to swap out a few placeholders for your actual code:
<script>
jQuery(document).ready(function($){$(".boxyComments a").click(function (event) {
event.preventDefault();
var post_id = $(this).attr("rel");
var postLink = "<?= site_url('/path/'); ?>"+post_id;
$("#myFrame").attr('src', postLink);
});
});
</script>
And sample divs & iFrame:
<div class='boxyComments'>
<a href='#' rel='some-url'>test link</a>
</div>
<div class=".commentsIframeBig">
<iframe id='myFrame' height="500px" width="800px" src=''>
</iframe>
</div>
Tested it locally and it worked no problem. You might have been running into issues with it not properly accessing the iFrame. If you can give the iFrame an id that makes it easier.
It's because you're declaring var postlink as a jQuery object. You just need to get it as a string that you can then pass to the iframe.
var post_id = $(this).attr("rel");
var postLink = "<?= site_url('/ajax-post-fold/'); ?>"+post_id;
UPDATE 2
Looks like the string shouldn't be included within the <?= get_site_url() ?> after all.
Instead I've created a few vars to affect it. Code updated below with answer:
var postDir = "\/ajax-post-fold\/";
var postLink = "<?= get_site_url(postDir); ?>"+"\/ajax-post-fold\/"+post_id;

Categories