I have created a ajax load more button to grab more data from my database, which all works fine. I am now trying to do a count, so the button displays how many results are left to display. Here is my jQuery code that is fired when the button is clicked:
jQuery(document).ready(function(){
jQuery(document).on('click','.show_more',function(){
var ID = jQuery(this).attr('id');
var count = jQuery(".singleproduct").length;
var totals = jQuery('.totalleft').text();
var finaltotal = totals - count;
//jQuery('.show_more').hide();
jQuery('.loding').show();
jQuery.ajax({
type:'POST',
async: true,
crossDomain : true,
url:'example.com/data.php',
data:'count='+count,
success:function(html){
//jQuery('#show_more_main'+ID).remove();
jQuery('.retailitems').append(html);
jQuery('html, body').animate({scrollTop: jQuery(".site-info").offset().top}, 1000);
}
});
jQuery( ".totalleft" ).replaceWith( finaltotal );
});
});
And here is the code for the button:
<span id="<?php echo $result['id']; ?>" class="show_more" title="Load more posts">Load <span class="totalleft"><?php echo $loadmore;?></span> more</span>
When clicked for the first time, the button updates with the correct remaining results. When clicked a second time, the news results populate, but the count remains the same.
Do i have things in the right order above?
Thanks
EDIT
So i found the issue. The calculations were correct, but when updating the count on the button i was actually removing the class of 'totalleft' with this:
jQuery( ".totalleft" ).replaceWith( finaltotal );
So i replaced this with:
jQuery( ".totalleft" ).text( finaltotal );
and all is fine, thanks for all the help.
parse the text() in .totalleft to get an integer value
var totals = parseInt(jQuery('.totalleft').text());
if your calculations are correct, you should get the right number back
EDIT
because ajax is async you are re-updating the value of .totalleft before the ajax is complete.
make sure that you are doing that in the ajax callback:
success:function(html){
//jQuery('#show_more_main'+ID).remove();
jQuery('.retailitems').append(html);
jQuery('html, body').animate({scrollTop: jQuery(".site-info").offset().top}, 1000);
jQuery( ".totalleft" ).replaceWith( finaltotal );
}
finally, I'm not sure what var count = jQuery(".singleproduct").length; is so make sure that the values you are expecting are correct by console logging before and after the subtraction
EDIT #2
var count = jQuery(`.singleproduct`).length;
console.log('count :' + count);
var totals = jQuery('.totalleft').text();
console.log('totals :' + totals);
are you getting numbers on the above logs? if not, then you might be replacing some part of your html with the ajax request and singleproduct or totalleft may not be there anymore
Related
I'm making some early attempts at educating myself in AJAX and trying to speed pages rather than relying on PHP to show results. I have hit a hurdle.
I essentially have 3 tiers of data. With 3 database tables.
The first tier of data is pulled via a PHP loop and displayed upon page load.
The second tier of data is loaded via AJAX when A is clicked and then appended to the page via jQuery.
The third tier (where I'm having trouble) is loaded via AJAX when the second tier is clicked...and appended within the previously appended B data.
Like so....
<!-- language: lang-html -->
<!-- PHP loop to pull list if Item A data upon page load -->
<p>Item A</p>
<!-- click Item A -> AJAX pull B data and append results to .a-results -->
<div class="a-results">
<p>Item B</p>
<!-- click Item B -> AJAX and append results to .b-results -->
<div class="b-results">
<p>B resultrow</p>
<p>B resultrow</p>
<p>B resultrow</p>
<p>B resultrow</p>
</div>
</div>
Ajax examples:
<!-- language: lang-js -->
$('a.a-call').click( function (e) {
e.preventDefault();
var sid = $(this).attr('data');
$.ajax({
url: 'secondtier.php',
type: 'POST',
dataType: 'json',
data: ({sid: sid}),
success: function(rows) {
for (var i in rows) {
var row = rows[i];
var id = row[0];
var name = row[1];
var type = row[2];
$('.a-result').append("<p><a href='#' id='s"+id+"' data='"+id+"' class='b-call'>id: " + id + " name: " + name + " type: " + type + "</a></p><div class='b-data'></div>");
}
}
});
});
$('a.b-call').click( function (e) {
e.preventDefault();
var bid = $(this).attr('data');
$.ajax({
url: 'thirdtier.php',
type: 'POST',
dataType: 'json',
data: ({bid: bid}),
success: function(rows) {
for (var i in rows) {
var row = rows[i];
var id = row[0];
var data = row[1];
var cost = row[2];
$(this).next('.b-data').append("<p>date: " + date + " cost: " + cost + "</p>");
}
}
});
});
My AJAX calls work in themselves, however I can't get the B call to append results within the A results. The Item B AJAX works just fine if it's hard coded into the HTML, it's only when it's appended that I can't get it work. No console errors anywhere. Just nothing happening on the page.
I'm not totally current on jQuery usage. I tried .live('click', function() for the Item B click, however the console is telling me it's not valid. I assumed jQuery dropped that at some point.
Using google to link to jquery 1.9.1
<!-- language: lang-html -->
<script language="Javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Am I going about this wrong? Can I get the appended anchor in B to call another ajax function and append more to the previously appended div?
I don't want to load all this data at once. This is my very reason for learning AJAX. The page currently loads everything via PHP and due to the amount of datasets within datasets it's a slow page load. I'm trying to get specific data to only load upon a click.
You need to use delegate() , because .b-call elements does not exist on page load, so jQuery doesnt know where those elements are. So you need to delegate an event to an element that will exist after page load.
$('.a-result').delegate('.b-call','click',function (e) {
e.preventDefault();
var bid = $(this).attr('data');
$.ajax({
url: 'thirdtier.php',
type: 'POST',
dataType: 'json',
data: ({bid: bid}),
success: function(rows) {
for (var i in rows) {
var row = rows[i];
var id = row[0];
var data = row[1];
var cost = row[2];
$(this).next('.b-data').append("<p>date: " + date + " cost: " + cost + "</p>");
}
}
});
});
I think the problem is due to the fact that the link for fetching the B data is created when A is fetched.
The click event handler ($('a.b-call').click) is registered before the actual DOM element exists and therefore it does not get triggered.
To get this event handler working you need to change your code. The a-results div exists on page load, so you can attach the event handler to this element and simply specify the selector for a.b-call:
Example:
$('.a-results').on('click', 'a.b-call', function(e) {
// your B load code here
}
I really don't know how to explain this. I have a table and I am using tablesorter to make columns sortable.
at the end of each row i have a button that has a jquery listener to fire off an ajax call. For debugging purposes, all that called script does is print_r($_POST). This ajax call only works after I click on a column to sort table. IF i don't, i get no response from ajax call. In firebug, if i dont click on column to sort, I get a red http:Post response, if i click on a table column, i get the response i would expect.
//tablesorter call
$('#pendingItems').tablesorter();
//dialog setup
$('#removeItem').dialog(
{
autoOpen:false,
width: 500,
modal: true,
resizable: false,
closeOnEscape: true,
buttons:
{
"Ok": function()
{
//window.location.replace('items.php');
}
}
});
//listener for button click
$('.removeItem').click (function()
{
var attrId = $(this).attr('id');
var gid = attrId.split('_');
var itemId = gid[1];
$.ajax({
type: "POST",
url: "removeItems.php",
data: "itemId="+itemId,
success: function(result)
{
alert('hi');
$('#removeItem').html(result);
$('#removeItem').dialog('open');
}
});
});
and in the table.
<input type='image' src='images/trashcan2.png' id='remove_" . $r['id'] . "' name='remove_" . $r['id'] . "' class='removeItem'>
where $r['id'] is a number.
in firebug:
looking at net tab. on failed attempt, the post goes to items.php (the original page). if i click on table column, and then the button, the post goes to the removeItems.php (the correct page)......
Maybe (probably...) tablesorter is modifying the DOM, causing your bindings to disappear.
To see if that is the problem - and to solve it - just change:
$('.removeItem').click (function()
to:
$('.removeItem').on('click', function()
Note that on() requires jQuery 1.7+
Also in POSt type, data should be like: data: {temId: itemId},
So i found that input type image submits the form. Adding return false; to the click event fixed the problem.
I am trying to implement a small chat application where user can text chat with any one of the online users.
My logic behind this is some thing like the following:
Login first.
Fetch the users who are online from DB and show them as list of online users.
Click on the users, then another small window is opening for text chatting.
Create a form(two hidden fields- one is for sender id and another is for receiver id, one textarea and a button for submitting) for this chatting.
Through jQuery, fill the value of receiver id.
By session id, fill the value of sender id.
After submitting the button, I call a page through ajax jquery which is responsible to insert and show the current data from DB.
My code for the ajaxJquery is like :
$(document).ready(function(){
$('#send_btn').click(function(){
var receiver_id = $('#hide_receiver_id').val();
var sender_id = $('#hide_sender_id').val();
var messagebox = $('#messagebox').val();
$.ajax({
type:"POST",
url:"chat_history.php?receiver_id="+receiver_id+"&sender_id="+sender_id+"&message="+messagebox,
success:function(result){
$('#history').html(result);
}
});
$('#messagebox').val('');
});
});
</script>
Up to this, its working fine. But I need to autoload the <div id="history"></div> portion. For that also I am thinking to do by using setInterval() in jQuery. My code is like :
<script type="text/javascript">
var auto_refresh = setInterval(
function (){
$('#history').load("chat_history.php?receiver_id=''&sender_id=<?php echo $_SESSION['id']?>&message=").fadeIn("fast");
}, 1000); // refresh every 1000 milliseconds
</script>
But in this scenario, how to pass the value of receiever_id in load() which is necessary to find out the respective data from DB?
Please let me know whether the requirement is cleared to you or not.
Thanks in advance.
<script>
$(function () {
// function wide variables
var receiver_id = $('#hide_receiver_id').val();
var sender_id = $('#hide_sender_id').val();
var messagebox = $('#messagebox').val();
// button click
$('#send_btn').click(function () {
receiver_id = $('#hide_receiver_id').val();
sender_id = $('#hide_sender_id').val();
messagebox = $('#messagebox').val();
$.ajax({
type : "POST",
url : "chat_history.php?receiver_id=" + receiver_id + "&sender_id=" + sender_id + "&message=" + messagebox,
success : function (result) {
$('#history').html(result);
}
});
$('#messagebox').val('');
});
var auto_refresh = setInterval(function(){
$('#history').load("chat_history.php?receiver_id="+receiver_id+"&sender_id=<?php echo $_SESSION['id']?>&message=").fadeIn("fast");
}, 1000); // refresh every 1000 milliseconds
});
</script>
I'm using the jEditable plugin and the following code to toggle between On and Off for a series of settings on a page.
$(document).ready(function() {
$('.editable_select').editable(''http://someexamplepage.com/save.php', {
indicator: '<img src="/images/spinner.gif">',
data : " {'✓':'✓','✗':'✗'} ",
tooltip : 'Click to Edit',
type : 'select',
onblur : 'submit',
style : 'inherit'
});
});
And then this in the html:
<b class="editable_select" id="setting1" style="display:inline">✓</b>
When the checkmark indicating On is clicked, it produces a dropdown menu with checkmark for On and the X for Off in it, which the user can then select. What I would prefer is that clicking the check/X not open a dropdown, but instead send the current On or Off setting to the save.php file. I could then just write the save.php file to return the opposite value, so that clicking just toggles between the two without opening any kind of edit window. I tried the following code:
$(document).ready(function() {
$('.editable_select').editable('http://someexamplepage.com/save.php', {
indicator: '<img src="/images/spinner.gif">',
tooltip : 'Click to Edit',
onclick : 'submit',
style : 'inherit'
});
});
But clicking the text still opens a little editing window, which I don't want. I'm still new to JavaScript and jQuery, so any help is greatly appreciated!
I wouldn't use a plugin for this, but rather a very simple bit of jQuery to run on the ready event.
I would include the current state as a data attribute on the DOM, so change your tags to:
<b class="editable_select" id="[ID FOR ITEM]" data-state="checked">ઙ</b>
Then do something like:
$(function(){
var update_dom = function(data){
var item_id = data.id;
var state;
data.state === 'checked' ? state = '✓' : state = '✗';
$('#'+item_id).data('state', data.state).html(state);
};
var selected = function(evt){
var item_id = $(this).attr('id');
var state = $(this).data('state');
$.ajax({
url: PATH_TO_SCRIPT,
data: {id: item_id, state: state},
type: "POST",
success: update_dom
});
}
$('.editable_select').click(selected);
});
This binds the click event to everything that has a class of editable_select. When you click on it, it'll call the selected function, which wil get the data from the DOM, and call your script. When your script is complete, it should send back a response (JSON would be good here), and, the success handler will update the DOM and display the state back to the user.
I'm new to Javascript/Jquery and struggling with a certain issue.
In the process of adding a job to a database, the users have an option to update the contents of dropdown lists with new options. Adding the new options is handled through a greybox which posts data with PHP through to the database.
After adding the new option it does not display in the dropdown list. As such they need to be able to click a button to refresh the contents of the dropdown list. Has anyone accomplished this before, and can show me some sample source code? Or is there a more elegant solution fo this issue?
I've been researching pretty much non-stop and cannot find a solution, any help is appreciated. n.n
Edit:
<script type="text/javascript">
function getbrands(){
new Ajax.Request('ajax/brand.php',{
method: 'get',
onSuccess: function(transport){
var response = transport.responseText;
$("brand").update(response);
}
});
}
It works... sometimes. Highly unstable. Also has a bad habit of conflicting with other scripts on the page. (mainly the greybox)
Any suggestions will be taken on board at this stage. :X
Use ajax to post the data to your php file, echo the html for the new dropdown back to the javascript, and then use jquery to put in the new contents. http://api.jquery.com/jQuery.ajax/
Assuming your using jQuery, you could do the following..
//in a php file that your gonna use to fetch new dropdown values
<?php //pathToPhpFile.php
header("Content-Type: application/json");
//here you'd perform a database query
//heres a dummy dataset
$data = array(
array( "id" => "dropdown1", "label" => "Dropdown #1"),
array( "id" => "dropdown2", "label" => "Dropdown #2"),
);
echo json_encode( $data );
exit;
?>
javascript code: sould be wrapped in $(document).ready( function(){ }); block to ensure the button is ready to accept events
//attach refresh event to button
$("#refeshButtonId").click( function() {
var dropdown = $('#idOfTheDropdown');
//fetch the key/values pairs from the php script
jQuery.getJSON( "pathToPhpFile.php", function( data ) {
//empty out the existing options
dropdown.empty();
//append the values to the drop down
jQuery.each( data, function(i, v) {
dropdown.append( $('<option value="'+ data[i].id +'">'+data[i].label+'</option>');
});
});
});
refined code :)
<script type="text/javascript">
$(document).ready( function(){
$("#refeshButtonId").click( function() {
//fetch the key/values pairs from the php script
jQuery.getJSON( "pathToPhpFile.php", function( data ) {
var dropdown = $('#idOfTheDropdown');
//empty out the existing options
dropdown.empty();
//append the values to the drop down
jQuery.each( data, function(i, v) {
dropdown.append( $('<option value="'+ i +'">'+ v +'</option>') );
});
});
});
});
</script>
no sample code but I guess it goes like this
after the posting, create a callback
that updates the DOM, particularly
the options for the select box
maybe it goes something like this in code
in jquery:
$.ajax({
method: 'POST',
data : $('#newjobfield').val(),
dataType: 'text'
success : function(data){
$('#selectbox').append('<option value="' + data + '">' + data + '</option>')
}
});
in php
function getNew()
{
if ($_POST)
{
// update database
// then echo the record's 'name' (or whatever field you have in there)
echo $newInsertedJobName;
}
die();
}
Now this code sucks, so just tell me if something does not work (I haven't tested it, cuz I made it a few minutes ago, while at work :P)