JQuery: Why is this Load More Functionality not working? - php

Trying to implement a simple "load more" functionality with jquery. The idea is to use it in the same way as one does pages. Click and a certain number of posts loaded from the database show up.
I have the following javascript:
$(function(){
var count = 0;
var num = 20;
$("#contents").load("posts.php");
$("#more").click(
function(){
var count = 0;
var num = 20;
$("#contents").load("posts.php");
$("#more").click(
function(){
$(".loading").show("fast");
count += num;
$.post("posts.php", {'page': count}, function(data){
$("#contents").append(data);
$(".loading").hide("slow");
});
}
);
and the following file posts.php
<?
echo "hello";
?>
And I have another file page.php with
<div id="contents"></div>
<div class="loading"><span style="text-decoration: blink;">LOADING...!</span></div>
<button id="more">More..</button>
When i click the "More Button" though nothing happens even though I'm just trying to print out a simple hello world here. I have loaded the javascript in the head of the file like
<script type ="text/javascript" src ="javascript/load.js"></script>
Other javascript functionality I've implemented is working fine. Is there something to add to the "loading" or "contents" elements in page.php?

Your javascript lacks basic syntactic structure, and must be issuing a syntax error, unless you messed it up while posting here. Try this:
$(function(){
var count = 0;
$("#more").click(loadPosts);
loadPosts();
function loadPosts() {
var num = 20;
$(".loading").show("fast");
count += num;
$.post("posts.php", {'page': count}, function(data){
$("#contents").append(data);
$(".loading").hide("slow");
});
}
});
UPDATE
Edited the code above and removed $("#contents").load("posts.php");. It was not necessary, and redundant.

Related

Conflicting jquery functions

I have built two functions which work separately (when the other is deleted) but do not work together. The overall aim is that when a person selects the number of results they want to see per page, this then reloads the page, and the value is put in the url and then retrieved using get in php; and then on the new page the selected value in the drop down menu to is the value what triggered the reload.
Jquery
$(document).ready(function(){
//the first section takes the value from the php script and then selects the option if it's not null - this works fine on it's own
var data = "<?php echo $rp;?>";
if (data){
$("#bo2 option[value="+data+"]").attr('selected', 'selected');
}
//this too works fine on it's own but not with the above
$('#bo2').change(function(){
var opt = $(this).val();
var url = "sales.php?results=";
var newurl = url + opt;
window.location.replace(newurl);
});
});
Together, the first works fine, in that it re-selects the right value if, say, I put ?results=50 after sales.php but then the jQuery to trigger the reload doesn't work. What am I doing wrong?
Just to clarify. The first page is called "sales.php" and the drop down menu has the currently selected value of "10", with 25 and 50 being other options. When I click on another number the jquery doesn't work. However should I type into the url the ending "?result=50", for example, it does work; and the drop down menu now shows 50; when i click on ten, the url updates, and the drop down shows ten also; the problem then is they seem to conflict only at the start, as it were.
It would seem the problem may concern how jquery deals with php. Take for example the following first example which works, and then the second which doesn't:
1)
$(document).ready(function(){
$('#bo2').change(function(){
var opt = $(this).val();
var url = "sales.php?results=";
var newurl = url + opt;
window.location.replace(newurl);
});
});
2) This change function however will not trigger a reload of the page because of the inclusion of the php defined jquery variable.
$(document).ready(function(){
var data = "<?php echo $rp;?>";
$('#bo2').change(function(){
var opt = $(this).val();
var url = "sales.php?results=";
var newurl = url + opt;
window.location.replace(newurl);
});
});
This achieves what I want (I don't know if the php posed a problem or not). The function is from here - Get url parameter jquery Or How to Get Query String Values In js.
Also, I'm surprised nobody more experienced than me didn't point out what also seems to have made a difference; the "first" function in the original post needs to in fact be second.
So the below will reload a new page, when a user clicks on an option in a select menu with pre-defined options for how many results they want to see per page; this value will then show in the url, and, importantly, the current select value of the select menu will now be this value also; this is important so that if the user goes back to the original number of views, the change() function works still.
$(document).ready(function(){
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
var data = getUrlParameter('results');
$('#bo2').change(function(){
var opt = $(this).val();
var url = "sales.php?results=";
var newurl = url + opt;
window.location.replace(newurl);
});
if (data)
{
$("#bo2 option[value="+data+"]").attr('selected', 'selected');
}
});

Extract div id to php variable to multiply

I have a script Ajax/jQuery this autoupdate a statistics in my site this is the code:
<!--Jquery/AJAX script-->
<script type="text/javascript">
function updateStats(stat)
{
var stat = ["online","newestPlayer","cuentas","personajes","guilds"];
var url = "template/Next/stats_do.php";
$.each(stat, function(i, key){
$.post(url, {stats: key}, function(data) {
$("#" + key).text(data);
});
});
}
setInterval('updateStats("updateStats")', 500);
</script>
Work all fine. for the results i use. for example...
But i have a ProgressBar with php. The code for work is (a part)
<?= round (HERE MY RESULT*100/$pBar2max); ?>%
The problem is that putting the does not allow multiplication in order to get the percentage
and i try
$onlines = <span id="online">
and insert a echo in the code, but not work, any solutions? i need extract a number in text for multiply with *100

Select changes not triggering if added by JQuery

I have a multi level select chain, where by the value of the first select generates the options for the next select list. And within the second list some of the values will cause a div to display with another input.
My codes (below) seem to work just fine when tested on static content (ie: the second select is hard coded in the html). But when I add it with JQuery, the second level no longer triggers the .change function.
<script type="text/javascript">
$(document).ready(function() {
$dts = $("select[name='tourdes']");
$dts.change(function() {
var dtsValue = $(this).val();
var dtsString = '?tourdes=' + dtsValue;
$('#dateSelect').show();
$('#dateSelect').load('include/avdates.php' + dtsString).append();
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$tags = $("select[name='tourcode']");
$tags.change(function() {
if ($(this).val() == "private") {
$(".prvcal").css({"visibility":"visible"});
}
});
});
</script>
I am guessing something needs to be re-initialized, but I am getting no where with my experiments.
If you're using jQuery 1.7 you'll want to use on, as both live and delegate are deprecated.
$(document).on("change", "select[name='tourcode']", function() {
var dtsValue = $(this).val();
var dtsString = '?tourdes=' + dtsValue;
$('#dateSelect').show();
$('#dateSelect').load('include/avdates.php' + dtsString).append();
});
docs for on()
You are probably using dynamically-generated HTML elements. If that is the case, you need to use .delegate() to handle them:
$('select').delegate("[name='tourdes']", 'change', function() {

Generic jquery structuration question

please take a look of this:
$(function () {
$("#add").click(function() {
val = $('#add_lang').val();
val1 = $('#add_lang_level').val();
listitem_html = '<li>';
listitem_html += val + ' <strong>('+ val1 + '/100)</strong>';
$.ajax({ url: 'addremovelang.php', data: {addname: val,addlevel: val1}, type: 'post', success: function(output) { alert(output); }});
listitem_html += 'Remove'
listitem_html += '</li>';
$('#langs').append(listitem_html);
});
$('.remove_lang').live('click', function(e) {
e.preventDefault();
$(this).parent().remove();
$.ajax({ url: 'addremovelang.php', data: {delname: val}, type: 'post', success: function(output) { alert(output); }});
});
});
This simple jquery script adds strings to a html list when the user hits the button with the id add. Also, it puts a remove link to each line, so when the user hits remove it triggers the function remove_lang and the string is deleted.
When the users add a string, this text comes from a text field, and i stored it on the variable val (as you can see on the 5 line of the code). Then i call a php script via Ajax to add this info to my mysql database.
But, when the user remove the string, i dont know how to know what string was removed, i mean, the name of this one, that i need to send to my php script in order to remove it from the database.
Take a look of this version of my code without the ajax call: http://jsfiddle.net/wnFsE/
Thanks for any help!!!
When you click remove you can do something like this:
val = $(this).parent().find('input').val();
That will get the value from hidden input you added:
Demo Here
You need to think about the string as instead a group of elements:
var li = $('<li/>');
var strong = $('<strong/>', { text: '(' + val1 + '/100)' });
var link = $('<a/>');
link.click(function()
{
// Insert code here for the link click
});
li.append(strong).append(link);
$('#langs').append(li)
There are other patterns that would work too, like:
$(listitem_html').find('a').click(function()
{
// Insert code here for the link click
});
Just get a reference to the element, and then attach the click event handler.
An Object Oriented Programming approach would help keep the actions very organized. You basically store the actions for each given language in an object, modifying the action for that language whenever it's removed or added.
Here's a live example that will print that "storage" object out to the console every time you add or remove a language so that you can clearly see what's going on.
And here's just the JS code (you'll notice that I barely changed a thing):
languageActions = {}
$(function () {
$("#add").click(function() {
val = $('#add_lang').val();
listitem_html = '<li>';
listitem_html += val;
listitem_html += '<input type="hidden" name="languages[]" value="' + val + '" /> ';
listitem_html += 'Remove'
listitem_html += '</li>';
$('#langs').append(listitem_html);
//now add it to our object
languageActions[val] = 'add';
console.log(languageActions);
});
$('.remove_lang').live('click', function(e) {
e.preventDefault();
val = $(this).prev().val();
$(this).parent().remove();
//now change it's value in languageActions
languageActions[val] = 'remove';
console.log(languageActions);
});
});
The only other thing I'll point out is that you don't really need that hidden input element since you're doing this via AJAX rather than a standard form submit. Instead, you could just do <li><span>Spanish</span><a class="remove_lang">Remove</a></li> for your HTML and then the click event on .remove_lang would do $(this).prev().text() rather than $(this).prev().val(). Not a huge deal, but you're HTML will be a little cleaner.
I guess that would be a simple:
$i = 1;
while(xxx){
//get the list with a different value for each element
echo '<div id="add_' . $i . '>$whatever</div>';
$i++;
}

jQuery - Using :contains for instant search with nested divs/classes?

I have a search box. I'm using jQuery and keyup to filter repeating divs.
Each div looks like this:
<div class="searchCell" id="searchCell' . $id . '">';
<div class="friendName">
// someNameOutputWithPHP.
</div>
</div>
Now, I want to filter based on the name text. If someNameOutputWithPHP contains the search query, the entire searchCell should show(). If it doesn't, the entire searchCell should hide().
This doesn't work, though:
<script type="text/javascript">
$(document).ready(function() {
$("#searchbox").keyup(function() {
var searchValue = $(this).val();
if(searchValue === "") {
$(".searchCell").show();
return;
}
$(".searchCell").hide();
$(".searchCell > .friendName:contains(" + searchValue + ")").show();
});
});
</script>
EDIT
New problem: I got the divs show() to show how I want. But the :contains isn't working exactly right.
For instance: say one of the name's is Ryan. When I search for 'Ryan', I get nothing. But when I search for 'yan' I get the Ryan div.
What's wrong?
Here's the :contains code:
$(".friendName:contains(" + searchValue + ")").parent().show();
That is because you are hiding the .searchCell and then showing its children .friendName divs, which though get display property will not show up because parent is hidden.
Try this:
<script type="text/javascript">
$(document).ready(function() {
$("#searchbox").keyup(function() {
var searchValue = $(this).val();
if(searchValue === "") {
$(".searchCell").show();
return;
}
$(".searchCell").hide();
//$(".searchCell:has(.friendName:contains(" + searchValue + "))").show();
// OR
//$(".friendName:contains(" + searchValue + ")").parents(".searchCell").show();
// OR
$(".friendName:contains(" + searchValue + ")").parent().show(); // If .searchCell is always a direct parent
});
});
</script>
Your selector
$(".searchCell > .friendName:contains(" + searchValue + ")")
will select all .friendName divs that contain the text from searchValue. That works just fine, but you need to .show() the parent element. Just invoke the .parent() method for that:
$(".searchCell > .friendName:contains(" + searchValue + ")").parent().show();
Demo: http://jsfiddle.net/d3ays/3/
And by the way, you HTML markup looks messed up too. There is a ; behind your div.searchCell for instance.

Categories