Reload JavaScript without page reload - javascript

I have a PHP page and I reload one div when filters are used or when a page of pagination is clicked. I have a problem with the pagination because it works only for the first time. I think I need to reload the pagination script when the div's content changes without the page reloading.
This is the function I need to reuse:
$('li.page').on('click', function() {
var clicked = $(this).find('a').text();
var paginations = $('ul.pagination');
var previous = paginations.find('li.page.active');
previous.removeClass('active');
var links = paginations.find('li.page');
links.each(function() {
if ($(this).find('a').text() == clicked) {
$(this).addClass('active');
}
});
$('#page').text(clicked);
showItems();
//location.reload(); //aktualizuje celou stránku
});
The other function that updates the div's content:
function showItems() {
var nazevkat = document.getElementById("nazevkat").innerHTML;
var kategorie = document.getElementById("kategorie").innerHTML;
var podkategorie = document.getElementById("podkategorie").innerHTML;
var razeni = document.getElementById("razeni").value;
vyhledavani = document.getElementById("vyhledavani").innerHTML;
vyhledavani = vyhledavani.replace(/ /gi, "+");
var start = document.getElementById("start-interval-2").value;
var end = document.getElementById("end-interval-2").value;
var vyrobce = $('#vyrobci :checked');
var vyrobci = "";
for (var i = 0; i < vyrobce.length; i++) {
vyrobci += vyrobce[i].value + "+";
}
vyrobci = vyrobci.substring(0, vyrobci.length - 1);
var dostupnosti = $('#dostupnosti :checked');
var dostupnost = "";
for (var i = 0; i < dostupnosti.length; i++) {
dostupnost += dostupnosti[i].value + "+";
}
dostupnost = dostupnost.substring(0, dostupnost.length - 1);
var page = document.getElementById("page").innerHTML;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("page-content-items").innerHTML = xmlhttp.responseText;
}
};
var newUrl = getCutURL(kategorie, podkategorie, razeni, vyhledavani, start, end, vyrobci, dostupnost, nazevkat, page);
history.pushState('', 'Alter URL', newUrl.replace("getItems", "produkty"));
var url = getURL(kategorie, podkategorie, razeni, vyhledavani, start, end, vyrobci, dostupnost, "", page);
xmlhttp.open("GET", url, true);
xmlhttp.send();
}

Changing the trigger works perfectly!
$('.page-content').on('click', 'li.page', function() {
var clicked = $(this).find('a').text();
var paginations = $('ul.pagination');
var previous = paginations.find('li.page.active');
previous.removeClass('active');
var links = paginations.find('li.page');
links.each(function() {
if ($(this).find('a').text() == clicked) {
$(this).addClass('active');
}
});
$('#page').text(clicked);
showItems();
});

Maybe is solve your problem
$.fn.myClick= function (callback) {
$(document).on('click', $(this).selector, function(event) { // this (jQuery) method is working
callback($(this));
event.preventDefault();
});
return $;
};
$('li.page').myClick(function($this){
var clicked = $this.find('a').text();
var paginations = $('ul.pagination');
var previous = paginations.find('li.page.active');
previous.removeClass('active');
var links = paginations.find('li.page');
links.each(function() {
if ($this.find('a').text() == clicked) {
$this.addClass('active');
}
});
$('#page').text(clicked);
showItems();
//location.reload(); //aktualizuje celou stránku
});
for using heavenPG, you need to read documentation
https://github.com/rachmanzz/heavenPG
first: define heavenPG Construct
var pagination = heavenPG({
id : 'ul.pagination',
total:10, // total page
current:3, // current page active
onclick:function(page){
console.log('current page :'+page); // page number clicked
}
});
pagination.execute();
Make Paginition List (using bootstrap component L http://getbootstrap.com/components/#pagination )
<ul class="pagination">
</ul>
and don't forget to load jQuery and boostrap libary
example : http://rachmanzz.github.io/heavenPG/

Related

How to add class to element if inner value changes on ajax request?

I want to write a piece of code which requests some cryptocurrency prices by ajax, it will request a FIAT currency price as well.
So, I want to add "increased" class when the price goes up & "decreased" class when the price goes down. The script runs every 3 seconds to check the new prices.
I've tried to define a variable on the innerHTML of the price element, and an if/else on what should the script do when the price changes. Here is a sample code:
var btn = document.querySelector("#refreshprice");
var price = document.querySelector("#price-text");
var btcirr = document.querySelector("#btcirrrealtime");
var currency_symbol = document.querySelector("#currency-symbol");
var usdirrinner = usdirr.innerHTML;
var priceinner = price.innerHTML;
window.onload = function(){
var USDIRR = getUSDIRRRequest();
USDIRR.send();
var XHR = getXHRRequest();
XHR.send();
var BTCIRR = realtimeirr();
};
setInterval(function(){
var USDIRR = getUSDIRRRequest();
USDIRR.send();
var XHR = getXHRRequest();
XHR.send();
var BTCIRR = realtimeirr();
},3000);
function getUSDIRRRequest(){
var USDIRR = new XMLHttpRequest();
USDIRR.open("GET","http://call2.tgju.org/ajax.json");
USDIRR.onreadystatechange = function(){
if(USDIRR.readyState == 4 && USDIRR.status == 200){
var parsedData = JSON.parse(USDIRR.responseText);
dollarrealtimeprice = parsedData.current.price_dollar_realtime.p.replace(",", "");
var dollarrealtimepricetoman = dollarrealtimeprice/10;
usdirr.innerHTML = dollarrealtimepricetoman;
if(usdirrinner >= dollarrealtimepricetoman){
usdirr.classList.add("increased");
}
else {
usdirr.classList.add("decreased");
}
}
}
return USDIRR;
}
function getXHRRequest(){
var XHR = new XMLHttpRequest();
XHR.open("GET","https://api.coindesk.com/v1/bpi/currentprice.json");
XHR.onreadystatechange = function(){
if(XHR.readyState == 4 && XHR.status == 200){
var parsedData = JSON.parse(XHR.responseText);
price.innerHTML = parseFloat(parsedData.bpi.USD.rate_float).toFixed(2);
if(priceinner >= parseFloat(parsedData.bpi.USD.rate_float).toFixed(2)){
price.classList.add("increased");
}
else {
price.classList.add("decreased");
}
currency_symbol.innerHTML = parsedData.bpi.USD.symbol;
}
}
return XHR;
}
It was expected to change the class to "increased" when the price goes up. but it just remains decreased.

How to dynamically load photos to dynamically loaded divs?

I wrote this code, which creates divs depending on the amount of text files in local directory.
Then I tried to write additional code, which appends photos to each of these divs. Unfortunately, this code doesn't append any photos...
function liGenerator() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
var n = (xmlhttp.responseText.match(/txt/g) || []).length;
for (var i = 1; i < n; i++) {
$.get("projects/txt/"+i+".txt", function(data) {
var line = data.split('\n');
var num = line[0]-"\n";
var clss = line[1];
var title = line[2];
var price = line[3];
var content = line[4];
$("#list-portfolio").append("<li class='item "+clss+" show' onclick='productSelection('"+num+"')'><img src='projects/src/"+num+"/title.jpg'/><div class='title'><h1>"+title+"</h1><h2>"+price+"</h2></div><article>"+content+"</article></li>");
$("#full-size-articles").append("<li class='product "+num+"'><div><div class='photo_gallery'><div id='fsa_img "+num+"'><div width='100%' class='firstgalleryitem'></div></div></div><article class='content'><h1 class='header_article'>"+title+"</h1><h2 class='price_article'>"+price+"</h2><section class='section_article'>"+content+"</section></article></div></li>");
});
}
}
}
};
xmlhttp.open("GET", "projects/txt/", true);
xmlhttp.send();
}
function pushPhotos() {
var list = document.getElementById("full-size-articles").getElementsByTagName("li");
var amount = list.length;
for(var i=1;i<=amount;i++) {
var divID = "#fsa_img "+i;
var where = "projects/src/"+i+"/";
var fx = ".jpg";
loadPhotos(where, fx, divID);
}
}
function loadPhotos(dir, fileextension, div) {
$.ajax({
url: dir,
success: function (data) {
$(data).find("a:contains(" + fileextension + ")").each(function () {
var filename = this.href.replace(window.location, "").replace("http://", "");
$(div).append("<img src='"+dir+filename+"' class='mini_photo'/>");
});
}
});
}
Any ideas on why this code is not working as intended?
The main issue is the space between "#fsa_img" and "i". When I changed it to '"#fsa_img_"+i', the code started work as intended.

mediawiki api can not display the results from array

Hello you wonderful people, I am trying to build JavaScript file to extract information from Wikipedia based on search value in the input field and then display the results with the title like link so the user can click the link and read about it. So far I am getting the requested information in(JSON)format from Mediawiki(Wikipedia) but I can't get it to display on the page. I think I have an error code after the JavaScript array.
I'm new at JavaScript any help, or hint will be appreciated.
Sorry my script is messy but I am experimenting a lot with it.
Thanks.
var httpRequest = false ;
var wikiReport;
function getRequestObject() {
try {
httpRequest = new XMLHttpRequest();
} catch (requestError) {
return false;
}
return httpRequest;
}
function getWiki(evt) {
if (evt.preventDefault) {
evt.preventDefault();
} else {
evt.returnValue = false;
}
var search = document.getElementsByTagName("input")[0].value;//("search").value;
if (!httpRequest) {
httpRequest = getRequestObject();
}
httpRequest.abort();
httpRequest.open("GET", "https://en.wikipedia.org/w/api.php?action=query&format=json&gsrlimit=3&generator=search&origin=*&gsrsearch=" + search , true);//("get", "StockCheck.php?t=" + entry, true);
//httpRequest.send();
httpRequest.send();
httpRequest.onreadystatechange = displayData;
}
function displayData() {
if(httpRequest.readyState === 4 && httpRequest.status === 200) {
wikiReport = JSON.parse(httpRequest.responseText);//for sunchronus request
//wikiReport = httpRequest.responseText;//for asynchronus request and response
//var wikiReport = httpRequest.responseXML;//processing XML data
var info = wikiReport.query;
var articleWiki = document.getElementsByTagName("article")[0];//creating the div array for displaying the results
var articleW = document.getElementById("results")[0];
for(var i = 0; i < info.length; i++)
{
var testDiv = document.createElement("results");
testDiv.append("<p><a href='https://en.wikipedia.org/?curid=" + query.pages[i].pageid + "' target='_blank'>" + query.info[i].title + "</a></p>");
testDiv.appendChild("<p><a href='https://en.wikipedia.org/?curid=" + query.info[i].pageid + "' target='_blank'>" + query.info[i].title + "</a></p>");
var newDiv = document.createElement("div");
var head = document.createDocumentFragment();
var newP1 = document.createElement("p");
var newP2 = document.createElement("p");
var newA = document.createElement("a");
head.appendChild(newP1);
newA.innerHTML = info[i].pages;
newA.setAttribute("href", info[i].pages);
newP1.appendChild(newA);
newP1.className = "head";
newP2.innerHTML = info[i].title;
newP2.className = "url";
newDiv.appendChild(head);
newDiv.appendChild(newP2);
articleWiki.appendChild(newDiv);
}
}
}
//
function createEventListener(){
var form = document.getElementsByTagName("form")[0];
if (form.addEventListener) {
form.addEventListener("submit", getWiki, false);
} else if (form.attachEvent) {
form.attachEvent("onsubmit", getWiki);
}
}
//createEventListener when the page load
if (window.addEventListener) {
window.addEventListener("load", createEventListener, false);
} else if (window.attachEvent) {
window.attachEvent("onload", createEventListener);
}
Mediawiki api link
https://en.wikipedia.org/w/api.php?action=query&format=json&gsrlimit=3&generator=search&origin=*&gsrsearch=
You are wrong some points.
1)
var articleW = document.getElementById("results")[0];
This is wrong. This will return a element is a reference to an Element object, or null if an element with the specified ID is not in the document. Doc is here (https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById)
The correct answer should be :
var articleW = document.getElementById("results");
2)
var info = wikiReport.query;
for(var i = 0; i < info.length; i++) {}
The info is object . it is not array , you can't for-loop to get child value.
wikiReport.query is not correct wiki data. The correct data should be wikiReport.query.pages. And use for-in-loop to get child element
The correct answer:
var pages = wikiReport.query.pages
for(var key in pages) {
var el = pages[key];
}
3) This is incorrect too
testDiv.appendChild("<p><a href='https://en.wikipedia.org/?curid=" + query.info[i].pageid + "' target='_blank'>" + query.info[i].title + "</a></p>");
The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. You are using the method to adds a string . This will cause error. Change it to node element or use append method instead
I have created a sample test.You can check it at this link below https://codepen.io/anon/pen/XRjOQQ?editors=1011

A piece of javascript in footer.php wordpress does work on PC but not on mobile

I have the following code in my footer.php on my wordpress website
var myForm = document.getElementById("questionnaire");
if (myForm) {
myForm.onsubmit = function() {
var questionDiv = document.getElementById('question-div');
var busyDiv = document.getElementById('busy');
var resultDiv = document.getElementById('result-div');
var resultList = document.getElementById('result-list');
var xhr = new XMLHttpRequest();
var url = "https://script.google.com/macros/s/xxxxx/exec";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
var result = response.result;
for (var i in result) {
var e = result[i];
if (e) {
var li = document.createElement('li');
if (e.url) {
var a = document.createElement('a');
a.href = e.url;
a.textContent = e.name;
li.appendChild(a);
} else {
li.textContent = e.name;
}
resultList.appendChild(li);
}
}
busyDiv.hidden = true;
resultDiv.hidden = false;
}
}
var form = document.getElementById('questionnaire');
var formData = new FormData(form);
var fields = ['name','email','yob','gender','xxx','yyyy'];
var params = [];
for (var i in fields) {
var field = fields[i];
params.push(field + "=" + formData.get(field));
}
xhr.send(params.join('&'));
questionDiv.hidden=true;
busyDiv.hidden=false;
return false;
};
}
</script>
This has allowed me to write and quote data from a google sheet
Now all this works on PC but it delivers 404 not found error on mobile site and the website itself is preset to be mobile responsive.
Can somebody help please?
Jane
What does your form html look like? I suspect that your mobile browser is trying to submit the form via the standard - non AJAX way and therefore is directing the browser to the url in the "action" attribute of your form. Try the following to stop this default behaviour
var myForm = document.getElementById("questionnaire");
if (myForm) {
myForm.onsubmit = function(evt) {
evt.preventDefault();

How do get param from a url

As seen below I'm trying to get #currentpage to pass client params
Can someone help out thanks.
$(document).ready(function() {
window.addEventListener("load", windowLoaded, false);
function windowLoaded() {
chrome.tabs.getSelected(null, function(tab) {
document.getElementById('currentpage').innerHTML = tab.url;
});
}
var url = $("currentpage");
// yes I relize this is the part not working.
var client = jQuery.param("currentpage");
var page = jQuery.param("currentpage");
var devurl = "http://#/?clientsNumber=" + client + "&pageName=" + page ;
});
This is a method to extract the params from a url
function getUrlParams(url) {
var paramMap = {};
var questionMark = url.indexOf('?');
if (questionMark == -1) {
return paramMap;
}
var parts = url.substring(questionMark + 1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
Here's how to use it in your code
var url = "?c=231171&p=home";
var params = getUrlParams(url);
var devurl = "http://site.com/?c=" + encodeURIComponent(params.c) + "&p=" + encodeURIComponent(params.p) + "&genphase2=true";
// devurl == "http://site.com/?c=231171&p=home&genphase2=true"
See it in action http://jsfiddle.net/mendesjuan/TCpsD/
Here's the code you posted with minimal changes to get it working, it also uses $.param as it's intended, that is to create a query string from a JS object, this works well since my suggested function returns an object from the url
$(document).ready(function() {
// This does not handle arrays because it's not part of the official specs
// PHP and some other server side languages support it but there's no official
// consensus
function getUrlParams(url) {
var paramMap = {};
var questionMark = url.indexOf('?');
if (questionMark == -1) {
return paramMap;
}
var parts = url.substring(questionMark + 1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
// no need for the extra load listener here, jquery.ready already puts
// your code in the onload
chrome.tabs.getSelected(null, function(tab) {
document.getElementById('currentpage').innerHTML = tab.url;
});
var url = $("currentpage");
var paramMap = getUrlParams(url);
// Add the genphase parameter to the param map
paramMap.genphase2 = true;
// Use jQuery.param to create the url to click on
var devurl = "http://site.com/?"+ jQuery.param(paramMap);
$('#mydev').click( function(){
window.open(devurl);
});
});

Categories

Resources