WordPress change content without reload - ajax

I have a wordpress theme in which i have to create a page that has a movie that goes loop.
it has 3 menu points which change the div text without reloading the page.
So far no problem.
Click here – put it in content box 2
But when im on a different page and i click for example the second link, it should go to the video page and change the text to the second one.
How can i do this?
Is there a way to do that with?
url/wordpressname/#1

Found a Solution: i found a solution here: http://www.deluxeblogtips.com/2010/05/how-to-ajaxify-wordpress-theme.html
which i changed to fit my needs:
jQuery(document).ready(function($) {
var $mainContent = $("#text"),
siteUrl = "http://" + top.location.host.toString(),
url = '';
$(document).delegate("a[href^='"+siteUrl+"']:not([href*=/wp-admin/]):not([href*=/wp-login.php]):not([href$=/feed/])", "click", function() {
//location.hash = this.pathname;
//return false;
});
$("#searchform").submit(function(e) {
location.hash = '?s=' + $("#s").val();
e.preventDefault();
});
$(window).bind('hashchange', function(){
url = window.location.hash.substring(1);
if (!url) {
return;
}
if (url=="1") {
$mainContent.html('<p>Text1</>');
}
if (url=="2") {
$mainContent.html('<p>Text2</>');
}
if (url=="3") {
$mainContent.html('<p>Text3</>');
}
if (url=="4") {
$mainContent.html('<p>Text4</>');
}
// url = url + "#content";
//$mainContent.animate({opacity: "0.1"}).html('<p>Please wait...</>').load(url, function() {
//$mainContent.animate({opacity: "1"});
//});
});
$(window).trigger('hashchange');
});

Related

Unable to download file with CasperJS

I am trying to download a file with CasperJS. If using browser, the download begins when user clicks a button and the response headers look like this:
I have tried these two methods with no luck:
1) https://stackoverflow.com/a/26334034
With this approach, the code block inside the if-statement is never executed. If I remove the condition, a bunch of resources are being saved, such as css files and so on. So the event listener is working, but for some reason not triggering when I use CasperJs click function to click the button that should start the download.
2) https://stackoverflow.com/a/30122021/692695
File.csv is saved but it's the web sites sourcecode, not the csv-file I get when I click the button on the website.
All of my code:
'use strict';
var utils = require('utils');
var casper = require('casper').create({
//verbose: true,
//logLevel: "debug",
clientScripts: ["node_modules/jquery/dist/jquery.min.js"]
});
function writeHtml(filename) {
var fs = require('fs');
var content = casper.getHTML();
fs.write(filename, content, 'w');
}
function getUrl() {
var url;
url = $('.tableofcontent_link:contains("Väestö työmarkkina-aseman, sukupuolen ja iän mukaan")').parent().attr('href');
return url;
}
casper.selectOptionByValue = function(selector, valueToMatch){
this.evaluate(function(selector, valueToMatch){
var select = document.querySelector(selector),
found = false;
Array.prototype.forEach.call(select.children, function(opt, i){
if (!found && opt.value.indexOf(valueToMatch) !== -1) {
select.selectedIndex = i;
found = true;
}
});
// dispatch change event in case there is some kind of validation
var evt = document.createEvent("UIEvents"); // or "HTMLEvents"
evt.initUIEvent("change", true, true);
select.dispatchEvent(evt);
}, selector, valueToMatch);
};
var link;
var url = 'http://pxnet2.stat.fi/PXWeb/pxweb/fi/StatFin/StatFin__tym__tyti/?table';
casper.start(url);
casper.userAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X)');
casper.then(function () {
this.echo("Now at: " + this.getCurrentUrl());
link = 'http://pxnet2.stat.fi' + casper.evaluate(getUrl);
});
casper.then(function () {
this.open(link);
});
casper.then(function() {
this.echo("Now at: " + this.getCurrentUrl());
// Select all data for each item
casper.click('#ctl00_ContentPlaceHolderMain_VariableSelector1_VariableSelector1_VariableSelectorValueSelectRepeater_ctl01_VariableValueSelect_VariableValueSelect_SelectAllButton');
casper.click('#ctl00_ContentPlaceHolderMain_VariableSelector1_VariableSelector1_VariableSelectorValueSelectRepeater_ctl02_VariableValueSelect_VariableValueSelect_SelectAllButton');
casper.click('#ctl00_ContentPlaceHolderMain_VariableSelector1_VariableSelector1_VariableSelectorValueSelectRepeater_ctl03_VariableValueSelect_VariableValueSelect_SelectAllButton');
casper.click('#ctl00_ContentPlaceHolderMain_VariableSelector1_VariableSelector1_VariableSelectorValueSelectRepeater_ctl04_VariableValueSelect_VariableValueSelect_SelectAllButton');
casper.click('#ctl00_ContentPlaceHolderMain_VariableSelector1_VariableSelector1_VariableSelectorValueSelectRepeater_ctl05_VariableValueSelect_VariableValueSelect_SelectAllButton');
});
casper.then(function() {
// casper.selectOptionByValue('#ctl00_ContentPlaceHolderMain_VariableSelector1_VariableSelector1_OutputFormats_OutputFormats_OutputFormatDropDownList',
// 'FileTypeExcelX');
// Select the format of the file from the select option list at the bottom
casper.selectOptionByValue('#ctl00_ContentPlaceHolderMain_VariableSelector1_VariableSelector1_OutputFormats_OutputFormats_OutputFormatDropDownList',
'FileTypeCsvWithHeadingAndSemiColon');
});
casper.then(function () {
// just for debugging
writeHtml('page1.html');
});
casper.then(function() {
//casper.click('#ctl00_ContentPlaceHolderMain_VariableSelector1_VariableSelector1_ButtonViewTable');
});
casper.then(function() {
// FIRST ATTEMPT TO LOAD THE DATA TO a file called file.csv
var formData = casper.evaluate(function(){
return $('form#aspnetForm').serialize();
});
//this.echo("Params: " + formData);
var targetFile = 'file.csv';
casper.download(link, targetFile, 'POST', formData);
});
casper.then(function () {
// just for debugging
writeHtml('page2.html');
});
// SECCOND ATTEMPT TO LOAD THE DATA TO a file called stats.csv
casper.on('resource.received', function (resource) {
if ((resource.url.indexOf('tyti_001') !== -1) ) {
this.echo(resource.url);
var file;
file = "stats.csv";
try {
this.echo("Attempting to download file " + file);
var fs = require('fs');
casper.download(resource.url, fs.workingDirectory + '/' + file);
} catch (e) {
this.echo(e);
}
}
});
casper.run(function () {
this.echo('End').exit();
});
And my package.json:
{
"scripts": {
"test": "dotest"
},
"pre-commit": ["test"],
"dependencies": {
"jquery": "^3.3.1"
},
"devDependencies": {
"pre-commit": "^1.2.2"
}
}
Explanation of the code:
First visit this page: http://pxnet2.stat.fi/PXWeb/pxweb/fi/StatFin/StatFin__tym__tyti/statfin_tyti_pxt_001.px/?rxid=bd4d5dc1-358d-407e-ae47-13266b79bfd0
There, dynamically pick a specified link and move there.
Select all data by clicking the V-shapen icon (look at the attached screenshot) and then select the format of the file.
I've faced this issue earlier with all versions except phantomjs 2.0.0. I also tried the solutions you shared from SO a year ago and they didn't work as well.
I'm going to assume you're using a phantomjs version other than 2.0.0.
Here's the link to download it
https://bitbucket.org/ariya/phantomjs/downloads/
With it, you will have access to onFileDownload method which you can override and use like below
casper.page.onFileDownload = function(status){
console.log('onFileDownload(' + status + ')');
return "newfile.csv";
};
onFileDownload will be called whenever a file is downloaded as a result of clicking a button (ajax) or as a result of sequential get/post requests.
All you have to do is, trigger the click on the button/link that will initiate download.
Note : My solution is assuming that everything else (site is not blocking phantomjs and your request headers/cookies are as expected)

Can I make another ajax request inside an ajax container?

I'm using ajax to pull in content to create a light box type content page. It also has a next and prev button once loaded so hence the use of ajax.
I wanted to use Ajax for the page navigation too. But if someone clicks a page link and then tries to use the light box feature both the jquery and ajax requests no longer work within the loaded area.
I've read a lot about bind and delegate but not sure how to use them in this context
Here's my main pieces of code:
// This gets called on document ready
function clicky() {
$link.click(function(e) {
e.preventDefault();
var linkPage = $(this).attr('href');
if ($(this).hasClass('pages')){
// PAGE specific code
if ($('body').scrollTop() != 0) {
$('body').animate({ scrollTop: 0 }, 500, function(){
pageLoad(linkPage);
});
} else { pageLoad(linkPage); }
console.log('page');
} else {
// PRODUCT specific code
if ($('body').scrollTop() != 0) {
$('body').animate({ scrollTop: 0 }, 500, function(){
productLoad(linkPage);
});
} else {
productLoad(linkPage);
}
}
});
}
Here's my ajax for the two different areas:
// Ajax stuff going on for pages
function pageLoad(linkPage) {
// Page stuff fades out
history.pushState(null, null, linkPage);
$("#page-content").load(linkPage + " #guts", function(){
// Loads in page content
});
}
// Ajax stuff going on for Products
function productLoad(linkPage) {
// Page stuff fades out
history.pushState(null, null, linkPage);
$("#product-content").load(linkPage + " #guts", function(){
// Shows an overlay/lightbox and loads in content
});
}
Edit: This worked for me
$(document).on('click', '.link' , function(){
console.log('this worked');
return false;
});
This worked:
$(document).on('click', '.link' , function(){
console.log('this worked');
return false;
});

Preload ajax loaded content

On my site I use one core/frame PHP file. If user hit one of my link (like contact, our about..etc..) the content loaded via ajax. I use the following snippet to achieve this:
var AjaxContent = function(){
var container_div = '';
var content_div = '';
return {
getContent : function(url){
$(container_div).animate({opacity:0},
function(){ // the callback, loads the content with ajax
$(container_div).load(url, //only loads the selected portion
function(){
$(container_div).animate({opacity:1});
}
);
});
},
ajaxify_links: function(elements){
$(elements).click(function(){
AjaxContent.getContent(this.href);
return false;
});
},
init: function(params){
container_div = params.containerDiv;
content_div = params.contentDiv;
return this;
}
}
}();
I need help how to integrate a preloading, so if visitors hit one of my link (for example the gallery menu) will see a little loading image, because now they see the big white nothing for long - long seconds.
Add loading image beforing ajax call and after you get response from server simply replace that image with data like the one below
function(){ // the callback, loads the content with ajax
$(container_div).html("<img src='loading.gif' />");//add image before ajax call
$(container_div).load(url, //only loads the selected portion
function(){
$(container_div).html(data);//replace image with server response data
$(container_div).animate({opacity:1});
}
Try this
var AjaxContent = function(){
var container_div = '';
var content_div = '';
return {
getContent : function(url){
$(container_div).html('Loading...'); //replace with your loading img html code
$(container_div).load(url, //only loads the selected portion
function(){
$(container_div).css({opacity:0});
$(container_div).animate({opacity:1});
});
},
ajaxify_links: function(elements){
$(elements).click(function(){
AjaxContent.getContent(this.href);
return false;
});
},
init: function(params){
container_div = params.containerDiv;
content_div = params.contentDiv;
return this;
}
}
}();

casperjs click() a form element to submit, wait, run queries on next page?

I would like to click a submit button, wait for the next page to load, then obtain html on that second page.. I do the start, then and run, but the then step is still run on the first page. Any ideas?
var casper = require('casper').create();
var site = 'http://www.example.com';
var data = {};
casper.start(site, function() {
this.evaluate(function() {
$('input[type="submit"]:first').click();
});
});
casper.then(function() {
data.body = this.evaluate(function() {
var rows = $('#content table:first tbody tr');
var listings = rows.eq(3).text();
var count = rows.eq(4).text();
return {
listings: listings,
count: count
};
});
});
casper.run(function() {
this.echo(data.body.listings);
this.exit();
});
This only partially solves your problem, but you can confirm that you've made it to the second page using waitFor. For example:
this.waitFor(function check() {
return (this.getCurrentUrl() === PAGE_2_URL);
},
function then() { // step to execute when check() is ok
this.echo('Navigated to page 2', 'INFO');
},
function timeout() { // step to execute if check has failed
this.echo('Failed to navigate to page 2', 'ERROR');
});
Its a good idea use waitForResource to wait the page load finished, see documentation here documentation
example:
casper.waitForResource(function checkAuth(validcredentials) {
return validcredentials;
}, function onReceived() {
if (authTitle !== this.getTitle()) {
this.log('Autenticação realizada com sucesso, aguarde...');
} else {
// this.capture('pic3.png');
this.log('Usuario ou senha invalidos!', 'ERROR');
this.die('User or password invalids!', 1); }
});
I have a similar problem with doubleclick. Make sure the click event is actually fired. I suspect this is the cause of running the next step within the same content.

Ajax load multiple divs (WordPress)

I'm using a ajax script to load content from other pages, without having to reload the browser.
For now I'm retrieving the content of the #inside div, but I'm using a full-background slideshow (#full) wich needs to be loaded as wel.
Maybe this can be achieved by loading the content of the #full div also, but I don't know how I could do that.
This is my code:
// Self-Executing Anonymous Function to avoid more globals
(function() {
// Home link isn't dynamic, so default set class name to it to match how dynamic classes work in WordPress
$(".home li.home").removeClass("home").addClass("current_page_item");
// Add spinner via JS, cuz would never need it otherweise
$("body").append("<img src='http://themeclubhouse.digwp.com/images/ajax-loader.gif' id='ajax-loader' />");
var
$mainContent = $("#wrapper"),
$ajaxSpinner = $("#ajax-loader"),
$searchInput = $("#s"),
$allLinks = $("a"),
$el;
// Auto-clear search field
$searchInput.focus(function() {
if ($(this).val() == "Search...") {
$(this).val("");
}
});
$('a:urlInternal').live('click', function(e) {
// Caching
$el = $(this);
if ((!$el.hasClass("comment-reply-link")) && ($el.attr("id") != 'cancel-comment-reply-link')) {
var path = $(this).attr('href').replace(base, '');
$.address.value(path);
$(".current_page_item").removeClass("current_page_item");
$allLinks.removeClass("current_link");
$el.addClass("current_link").parent().addClass("current_page_item");
return false;
}
// Default action (go to link) prevented for comment-related links (which use onclick attributes)
e.preventDefault();
});
// Fancy ALL AJAX Stuff
$.address.change(function(event) {
if (event.value) {
$ajaxSpinner.fadeIn();
$mainContent
.empty()
.load(base + event.value + ' #content', function() {
$ajaxSpinner.fadeOut();
$mainContent.fadeIn();
});
}
var current = location.protocol + '//' + location.hostname + location.pathname;
if (base + '/' != current) {
var diff = current.replace(base, '');
location = base + '/#' + diff;
}
});
})(); // End SEAF
try to repeat the procedure:
// Fancy ALL AJAX Stuff
$.address.change(function(event) {
if (event.value) {
//load ajax image
$ajaxSpinner.fadeIn();
$mainContent.empty().load(base + event.value + ' #content', function() {
$ajaxSpinner.fadeOut();
$mainContent.fadeIn();
});
// repeat here
//load another div
$mainContent.empty().load(base + event.value + ' #mydiv1', function() {
$mainContent
});
//load another div
$mainContent.empty().load(base + event.value + ' #mydiv2', function() {
$mainContent
});
}
let me know if it works, Ciao! :)

Resources