I'm trying to write a function that increments a variable, which will later be stored as post meta for the WordPress post, by clicking the posts title. In other words, I want to a create function that keep track of how many times a post title of a certain post is being clicked.
I'm new to using jQuery so I'm trying to figure out how to get the 2 function in PHP and jQuery to interact. I need to process the data in PHP later, which is why I need to do this.
This is what I have so far (PHP):
function clickScoreMethod($postid){
//$clickScore = 0;
$clickScore = get_post_meta($postid, 'redditclickscore', true);
$clickScore = $clickScore + 0.25;
update_post_meta($postid, 'redditclickscore',$clickScore);
}
$clickScore is the variable I want to increase by 0.25 every time the post title is clicked. I'm using meta to store it easily per post. If it is simpler, I can also increase the score by just incrementing the variable and then dividing it by 4 when I process it in the PHP later.
The jQuery:
$("li.post-item article").each(function(){
$( ".the-post-container .entry-title" ).click(function() {
var clickScore = 0.25;
});
});
.entry-title is the post title and .post-item-article is basically the blog roll.
I have no idea how to get these two to work together so that I increase the number.
Use ajax to do this.
Your jQuery would look something like this:
$("li.post-item article").each(function () {
$(".the-post-container .entry-title").click(function () {
var clickScore = 0.25;
$.ajax({
url: "/path/to/php/file",
type: "POST",
data: { clickScore: clickScore },
success: function () {
console.log("Success!");
}
});
});
});
and you would access the variable and do stuff with it with this (in PHP):
$clickScore = $_POST["clickScore"]
Hope this helps you.
Related
I have this code below that returns an updated value from an API every seconds in an html span tag:
$(document).ready(function(){
setInterval(function(){
$.get('https://api.kraken.com/0/public/Ticker?pair=XXBTZEUR', function(data){
var kraken_btc_eur = data.result.XXBTZEUR.c[0]
$("#kraken_btc_eur").text(kraken_btc_eur);
});
}, 1000);
});
How can I change the css of the <span id="kraken_btc_eur"> depending on whether the value of the variable var kraken_btc_eur changes from a prior value.
I figure I must include an IF statement, create a new variable to compare to the old update and clear the variable for this to be executed in the next second again PLUS different ID for up or down. I am not sure how to implement that.
Thanks all for your guidance.
Try something like:
$(function() {
var kraken_btc_eur_old = 0;
setInterval(function(){
$.get('https://api.kraken.com/0/public/Ticker?pair=XXBTZEUR', function(data){
var kraken_btc_eur = data.result.XXBTZEUR.c[0];
if (kraken_btc_eur_old != kraken_btc_eur) {
// Change css
}
kraken_btc_eur_old = kraken_btc_eur;
$("#kraken_btc_eur").text(kraken_btc_eur);
});
}, 1000);
});
Comparing current to new...
Something like:
if(kraken_btc_eur !== $("#kraken_btc_eur").text()) {
// if different change background and add new text
$("#kraken_btc_eur").css('background', 'red').text(kraken_btc_eur);
}
This way you only update if different, no point updating something with the same value
I´m having several problems with a progress bar in one of my developments.
I have a JavaScript function which launch serveral Ajax calls which call a PHP process, all at the same time. Those Ajax calls represent a percentage of a bigger proccess, so, for example, if I launch 100 ajax calls each one represent a 1% of the process.
The problem is that I can't force re-draw the HTTP DOM via JavaScript when an Ajax call ends.
So, the imports are these:
<link rel="stylesheet" href="(...)/javascript/themes/base/ui.core.css">
<link rel="stylesheet" href="(...)/javascript/themes/base/ui.theme.css">
<script src="(...)/js/jquery-ui-1.7.2.custom.min.js" type="text/javascript"></script>
And the important code is the next one:
Creation of progressbar (before launch Ajax calls):
$("#progressbar").progressbar({max:100, value:0});
$("#progressbar").progressbar("enable");
Every Ajax call will modify a variable when they finish. When I launch all Ajax calls I create an Observer function with JavaScript setTimeout, which looks at that variable and get the percentage:
setTimeout (function(){
(...)
var percentage = Math.round(((proccessedLines)/totalLines)*100);
$("#progressbar").progressbar("value", percentage);
(...)
}, 500);
And, finally, that $("#progressbar") is just a div HTML tag with that name.
So, the problem is that timeout. It supposed to update that progressbar value and update the DOM, it should to be redrawn but It doesn´t work as It should.
Any ideas?
I have to point one more thing: this process was working perfectly 'till 2 days ago; could be some new changes in the browsers?
The setTimeout function is just executed one time after 500ms. Maybe use the setInterval function to execute your function every 500ms or consider this snippet: https://jsfiddle.net/nicolastorre/o35teyq3/32/
// Parameters
var queryList = new Array('code', 'js', 'php');
var lenQueryList = queryList.length;
var percentage = 0;
var proceed = 0;
var totalPercentage = 100;
// Init progress bar
$("#progressbar").progressbar({max:totalPercentage, value:percentage});
$("#progressbar").progressbar("enable");
for(var i = 0; i < lenQueryList; i++) {
/*### setTimeout to make a pause (just for the demo) ###*/
setTimeout(function() {
console.log('just a pause to see slowly!');
console.log(queryList[i]);
// Wikipedia api search
$.ajax({
url: 'https://en.wikipedia.org/w/api.php?callback=?',
data: {
srsearch: queryList[i],
action: "query",
list: "search",
format: "json"
},
error: function() {
console.log('An error occured');
},
dataType: 'json',
success: function(data) {
// Get results
console.log(data);
// Update progress bar
proceed++;
percentage = Math.round((proceed/lenQueryList)*totalPercentage);
$("#progressbar").progressbar("value", percentage);
},
type: 'POST'
});
}, 500 * i); // setTimeout to make a pause (just for the demo)
/*########################################*/
}
I am new at AJAX and JQuery and trying to use them in the part of my website. Basically the website that I have, has this kind of design and currently it is functional (Sorry for my poor paint work :)
The items in the website are created by user. This means item number is not constant but can be fetched by db query.
Each item has a unique URL and currently when you click an item, all page is refreshing. I want to change the system to let the user have a chance to navigate quickly between these items by only chaning middle content area as shown above. However I also want to have a unique URL to each item. I mean if the item has a name like "stack overflow", I want the item to have a URL kind of dev.com/#stack-overflow or similar.
I don't mind about the "#" that may come from AJAX.
In similar topics I have seen people hold constant names for items. For instance
<a href="#ajax"> but my items are not constant.
WHAT I HAVE TRIED
Whats my idea is; while fetching all item's links, I'm holding links in $link variable and using it in <a href="#<?php echo $link; ?>">.
Inside $link it is not actual URL. it is for instance a name like "stack-overflow" as I ve given example above. Until this part there is no problem.
PROBLEM
In this topic a friend suggested this kind of code as an idea and I ve changed it for my purpose.
<script>
$(document).ready(function() {
var router = {
"<?php echo $link ?> ": "http://localhost/ajax_tut/link_process.php"
};
$(window).on("hashchange", function() {
var route = router[location.hash];
if (route === undefined) {
return;
} else {
$(".content-right").load("" + route + " #ortadaki_baslik");
}
});
});
</script>
I'm trying to post the value of $link to the link_process.php and at link_process.php I will get the value of $link and arrange neccessary page content to show.
The questions are;
- How should I change this code to do that?
- I couldnt see someone doing similar to take as an example solve this
issue. Is this the right way to solve this situation?
- Do you guys have a better solution or suggestion for my case?
Thanks in advance.
WHEN your server side AJAX call handler [PHP script - handling AJAX requests at server side] is constant and you are passing item_id/link as GET parameter...
For example:
localhost/ajax_tut/link_process.php?item_id=stack-overflow OR
localhost/ajax_tut/link_process.php?item_id=stack-exchange
Then you can use following code.
<script>
$(document).ready(function() {
var ajax_handler = "localhost/ajax_tut/link_process.php?item_id=";
$(window).on("hashchange", function() {
var route = location.hash;
if (route === undefined) {
return;
} else {
route = route.slice(1); //Removing hash character
$(".content-right").load( ajax_handler + route );
}
});
});
</script>
WHEN you are passing item_id/link as URL part and not parameter...
For example:
localhost/ajax_tut/stack-overflow.php OR
localhost/ajax_tut/stack-exchange.php
Then you can use following code.
<script>
$(document).ready(function() {
var ajax_handler = "localhost/ajax_tut/";
$(window).on("hashchange", function() {
var route = location.hash;
if (route === undefined) {
return;
} else {
route = route.slice(1); //Removing hash character
$(".content-right").load( ajax_handler + route + ".php");
}
});
});
</script>
WHEN Your server side AJAX handler script url is not constant and varies for different items...
For example: localhost/ajax_tut/link_process.php?item_id=stack-overflow OR localhost/ajax_tut/fetch_item.php?item_id=stack-exchange OR localhost/ajax_tut/stack-exchange.php
Then I suggest to change PHP script which is generating item's links placed on left hand side.
<?php
foreach($links as $link){
// Make sure that you are populating route parameter correctly
echo '<a href="'.$link['item_id'].'" route="'.$link['full_ajax_handler_route_url_path'].'" >'.$link['title'].'</a>';
}
?>
Here is Javascript
<script>
$(document).ready(function() {
var ajax_handler = "localhost/ajax_tut/"; //Base url or path
$(window).on("hashchange", function() {
var route = location.hash;
if (route === undefined) {
return;
} else {
route = route.slice(1); //Removing hash character
route = $('a [href="'+.slice(1)+'"]').attr('route'); //Fetching ajax URL
$(".content-right").load( ajax_handler + route ); //Here you need to design your url based on need
}
});
});
</script>
How do I get the function checkViewers(); to work properly? I believe I am calling it wrong within the JS document file and therefore the JS is not reading the function properly.
The current code:
//Content Viewer Information
function checkViewers() {
//Base Variables
var viewer = $('#viewed span.user');
var totalViews = $('#viewed span.user').length;
var shortenViews = $('#viewed span.user').length -1;
if (totalViews === 0) {
$('<span> 0 people have </span>').insertBefore($('#viewed span:last-child'));
}
if (totalViews === 2) {
$('<span> and </span>').insertAfter(viewer.first());
}
if (totalViews >= 3) {
viewer.slice(1).hide();
$('<span> and </span>').insertAfter(viewer.first());
$('<span class="user count"></span>').insertAfter(viewer.eq(2));
$('.count').html(shortenViews + ' more people');
}
}
The function is called towards the bottom of the remaining JS, after the JSON Data has been called.
Ideally, the JSON Data should be inputted into the HTML and the function should catch the number of viewers. This should then effect how the viewers are being shown in the HTML, upon how many viewers are being listed.
View the Plunker.
Making my comment an answer:
Ajax is Asynchronous. You ordered a pizza off the internet and you try to eat the pizza before it gets to your house. You have to wait for the pizza to show up before you eat it. AKA, you can not call your function until the data is there. So when you set the html, you call your function
xhr.onload = function() { //<--Function is called when the Pizza shows up at your door and the doorbell rings
... //removed a bunch of code....
//Update Page With New Content
var viewerSection = $('#viewed');
viewerSection.html(newViewers); //You open up the pizza box
checkViewers(); //<--- MOVE IT HERE, The pizza is here!!!!
}
};
xhr.open('GET', 'data.json', true); //<-- You set up your pizza order
xhr.send(null); //<--You make the pizza purchase
//checkViewers(); <-- PIZZA IS NOT HERE!!!!
Ok I will try to make it simple.
1) I have 3 links that execute an Ajax Request and update a div with some content.
The DIV
<div id="content-to-update"></div>
The 3 links that update #content-to-update
example 1
example 2
example 3
Each link update the div #content-to-update with the content just below with one parameter named CODE
The the div #content-to-update is updated with the code below.
var loading = false;
$(window).scroll(function () {
var winTop = $(window).scrollTop();
var docHeight = $(document).height();
var winHeight = $(window).height();
//if user reach bottom of the page
if (!loading && (winTop / (docHeight - winHeight)) > 0.95) {
loading = true;
//the CODE parameter is different on each call from the links that I
//talked earlier.
$.get("/items/next/?list_name=" + CODE, function(data){
//executing some javascript to display next items
}).done(function() {
loading = false;
})
}
});
});
The problem is that it seams the browser keep all different version of the updated div.
Its like the old content is not erased before the new content is added.
If I click on the first link and scroll I get the right items OK!.
Then if I click on the second link, when I scroll I get the Item twice (duplicated- it calls the code from the previous ajax call)
Then if I click on the third link, when I scroll I get the Item 3 times. (it calls the code from the 2 previous ajax call )
When I use the Chrome debugger I see that it goes first in the code that have received the parameter EXAMPLE_1 then it goes in the code that has received the parameter EXAMPLE_2 etc
But this code should has been overridden by the call of the EXAMPLE_2 link.
It is difficult to explain I don't know if someone understand what Im trying to explain but I give it a try :) and again sorry for my english.
Thanks
I'm a bit picky about POST and GET, so even though Wayne is technically correct, the fact that you are retrieving data makes your use of GET the right way of doing it.
The way around caching is either by using jQuery's ajax method and setting cache to false, like so:
$.ajax({
url: "/items/next/?list_name=" + CODE,
type: 'GET',
success: function(data) {
$('#content-to-update').html(data);
},
cache:false,
error: function(e) {
alert("Server failure! Is the server turned off?");
}
});
You can also trick the browser by adding a random string to the end of the URL, which is what I usually do. Something like this:
$.get("/items/next/?list_name=" + CODE + '&cache_buster=' + (new Date()).getTime().toString(), function(data){
//executing some javascript to display next items
}).done(function() {
loading = false;
})
If you are using .html() to set the content, the error is definitely somewhere else. Ensure that you are not appending the new content to the div, which seems like what you are doing.
Also, your functions should act independently of one another. Your current process seems to support that, but your problem seem to suggest otherwise.
Try the suggestions first and if they don't work, post more code.
Update
Try this:
var loading = false;
function executeSomeAjax(CODE){
$(window).scroll(function () {
var winTop = $(window).scrollTop();
var docHeight = $(document).height();
var winHeight = $(window).height();
//if user reach bottom of the page
if (!loading && (winTop / (docHeight - winHeight)) > 0.95) {
loading = true;
//the CODE parameter is different on each call from the links that I
//talked earlier.
$.get("/items/next/?list_name=" + CODE, function(data){
//executing some javascript to display next items
}).done(function() {
loading = false;
})
}
});
});
}
As you can see, the variable loading is now a global variable. I suspect that it was a local variable in your original function and as a result was set to false anytime the function ran.
Making it a global variable should resolve your issue.
Hope this helps.
UPDATE
Ok this is the final working code thanks to everybody for helping me out !
I think the problem was coming from low memory on my computer. The code you see below was used yesterday and was not working.
Since I rebooted the computer this morning everything works like a charm. I have 4GO of memory and working with Grails 2.2.2 and Intellij IDEA Im often with 100Mo of memory left I guess this should have a side effect. I cant see other explanations.
If That can help anyone to read this post
var loading = false;
function nextProject(){
$('.logo').html('<img src="/images/ajax-loader-transparent.gif">');
$.ajax({
type:'GET',
url: "/project/next/",
data:"list_name=" + CODE,
beforeSend:function(){
console.log("loading : " + loading)
}
}).done(function(data) {
if(data != ""){
var arrayOfObjects = eval(data);
for(var i=0; i < arrayOfObjects.length; i++){
TrackManager.newTrack(btoa(arrayOfObjects[i].base64Params));
var projectMgr = new ProjectManager(arrayOfObjects[i].id);
projectMgr.socialShare();
<sec:ifNotLoggedIn >
projectMgr.runDeny();
</sec:ifNotLoggedIn>
<sec:ifLoggedIn >
projectMgr.runGranted(arrayOfObjects[i].likeUp, arrayOfObjects[i].inPlayList );
</sec:ifLoggedIn>
INC++;
}
loading = false;
$('.logo').html('<img src="/images/soundshare_logo_32.png">');
console.log(INC + "/" + PROJECT_COUNT );
}
}).fail(function(){
console.error("Ajax error!")
});
}
$(window).scroll(function(){
var winTop = $(window).scrollTop();
var docHeight = $(document).height();
var winHeight = $(window).height();
if ((winTop / (docHeight - winHeight)) > 0.95) {
if(INC < PROJECT_COUNT){
if(!loading){
loading = true;
nextProject()
}
}
}
});