I load content of a page by jQuery AJAX as
$(document).ready(function(){
$('#next').click(function(event){
$.ajax({
url: "load.php?start="+$('#lastid').text(),
success: function(html){
$("#results").append(html);
$("#lastid").empty().load('html #start');
}
});
});
});
In the current document, I have <div id="lastid"></div> and in the external php file <div id="start"></div>
The value for id="start" is updated from database, and it will be transferred to id="lastid". However, this code only works for FIRST click. For default <div id="lastid">1</div>, when clicking the button (id="more") it will read load.php?start=1 and updates the current document to <div id="lastid">11</div> (it's visible). But the second click will not load load.php?start=11
It seems that $('lastid') well reads the default value of <div id="lastid"></div>, but NOT when it has been updated by $("#lastid").empty().load('html #start')
How can I modify this code to work for subsequent clicks?
Wow, what a mess! Let's clean up a bit :)
You need to get rid of the id, as an id has to be unique and if you load another div with id lastId into your site, jQuery will not know which id to get. If you have many divs, each containing the id, you can just read the last id by using ('div:last').text();
So your ajax would look like this:
$(document).ready(function(){
$('#next').click(function(event){
$.ajax({
url: "load.php",
data: "start="+$('div:last').text()
success: function(html){
$("#results").append(html);
}
});
});
});
I also don't know what you do with the last line in the success, as load should be used to load data from the server with ajax, what is what you do by using $.ajax(). Also load() takes at least an url as parameter, see here.
try .live() function instead of .click()
Mate,
What I see from you code is that you are attaching an event once the page is loaded. And this creates a static call with static values that don't get updated as you continue.
My suggestions is to use a function that will feed an Id dynamically to your ajax call as follows:
$(document).ready(function(){
$(document).on("click", '#next', function(event){
$.ajax({
url: buildurl(),
success: function(html){
$("#results").append(html);
$("#lastid").empty().load('html #start');
}
});
});
});
function buildurl()
{
return "load.php?start="+ $('#lastid').text();
}
This will force your event to always call this function and the function to get a fresh value from lastid.
Regards
you have to change your success function because you have multiple #lastid when clicking twice.
try something like:
success: function(html){
$("#lastid").removeAttr("id"); // remove's the id from #lastid
$("#results").append(html); // appends the new one
$("#lastid").empty().load('html #start');
}
Related
Forms have an action attribute to specify where (for example a .php file) to post to. Do <input> elements have the action attribute?
The answer is most likely no. But I wish to know what concept am I getting wrong here?
Is there a equivalent of action for <input>?
The reason I am asking this is that I have a few checkboxes, and I wish to use AJAX to fire something to a PHP file, such that a div changes when the checkboxes are ticked (I don't want a whole page reload). How should I go about doing this?
I am still drafting the code at this stage, but an example can be seen here.
Appreciate your suggestions!
Based on comments it really sounds like you want something to be sent when any number of checkboxes might be changed.
Add an event handler to all of them, serialize() the form and post it whenever any one of them changes
var $form =$('#myForm');
$form.find(':checkbox').change(function(){
var formData = $form.serialize();
$.post('/someFile.php', formData, function(response){
// do something with response
}).fail(function(){
alert("Oops something bad happened');
});
});
Use jQuery AJAX Methods:
AJAX is the art of exchanging data with a server, and update parts of a web page - without reloading the whole page.
EX:
$(document).ready(function(){
$("button").click(function(){
// You can call ajax on any event of html element like checkbox checked, dropdown changed
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});
});
});
$(document).on('change', '#checkboxid', function() {
if ($(this).is(':checked')) {
$('#container').load('pages/somephpfile.php');
}
});
Use .load() on change of checkbox
you cant set which php file to load based on the checkbox status.
Also try
$(document).on('change', '#checkboxid', function() {
$.ajax({
type: 'POST',
url: 'somephp.php',
dataType: "html",
success: function(data) {
$('#container').html(data) //load the data from somephp.php here
}
});
});
I'm banging my head here trying to figure out why this isn't working, so I finally created a simplified version of what I'm going on jsFiddle, and of course it works there.
What I'm doing - a simple AJAX call on hover over an element, and putting that response in a DIV. Here's the code on my site that is NOT working...
HTML
<div class="profileimage">
<a href="#">
<img src="/profilepics/img.jpg" />
<p>Test Here</p>
</a>
<div class="profileInfo"></div>
</div>
jQuery
$(document).ready(function() {
$('.profileimage').hover(function() {
$.ajax({
url:"getProfile.php",
success:function(HTML){
$(this).find('.profileInfo').html(HTML);
}
});
});
});
Also, for reference, all that's in getProfile.php currently is:
<p>RESULTS FROM AJAX</p>
What DOES work is that the AJAX request happens, the result is returned okay. If I replace the line in the success function with alert(HTML), I can see the response. What does NOT work is that the response never makes it in to the profileInfo child element.
I assumed my locator was incorrect, so I created a jsFiddle (HERE) to test. Turns out, the locator works just fine.
So I guess my question here is... if the locator works okay in the jsFiddle, but not in the AJAX request... is there something about the way it's used in an AJAX call that I need to change? I don't see why $(this).find('.profileInfo').html(HTML); shouldn't work just fine regardless of whether I'm using it in an AJAX response or not.
Any thoughts / suggestions are appreciated...
The this is not the right context. To fix this you have multiple options:
You can use context option:
$.ajax({
url:"getProfile.php",
context: this,
success:function(HTML){
$(this).find('.profileInfo').html(HTML);
}
});
or you could use a different selector:
$.ajax({
url:"getProfile.php",
success:function(HTML){
$('.profileimage').find('.profileInfo').html(HTML);
}
});
or you could use jQuery's bind to ensure the correct context:
$.ajax({
url:"getProfile.php",
success: $.proxy(function(HTML){
$(this).find('.profileInfo').html(HTML);
}, this)
});
or you can use closure like this (my favorite):
var self = this;
$.ajax({
url:"getProfile.php",
success: function(HTML){
$(self).find('.profileInfo').html(HTML);
}
});
Try this less elegant but educational approach...
$(document).ready(function() {
$('.profileimage').hover(function() {
var that = $(this);
$.ajax({
url:"getProfile.php",
success:function(HTML){
that.find('.profileInfo').html(HTML);
}
});
});
});
I have some code that calls in a new html file, to be added into a div. I'm wondering why the content in the div is replaced rather than just added in. Once I understand the "why" Id like to know how I would add in external markup into a div while preserving what was already in that div to begin with.
$.ajax({
url: 't3.html',
success: function(data) {
$('.ajax').html(data);
}
});
Instead of:
$('.ajax').html(data);
use:
$('.ajax').append(data);
try .append
$.ajax({
url: 't3.html',
success: function(data) {
$('.ajax').append(data);
}
});
Because you are replacing the whole HTML of .ajax div with data. If you want to preserve the existing HTML of that control use the following
$('.ajax').html($('.ajax').html() + data);d
Here is my full JS code:
var timeOutId;
function ft(){
$.get("progress.txt", null, function(data){
if(data.substr(0,10) == "MSG::MSG::"){
$("#box").html(data);
window.clearTimeout(timeOutId);
}else{
$("#box").html(data);
}
});
};
$(document).ready(function(){
$("#box").corner('20px');
$("#progress").hide();
});
$("#newm").click(function(){
$("#progress").show();
$("#list").html = $.ajax({
url: "action.php",
global: false,
type: "POST",
data: ({keyword : $("#keyword").value()},{format: $("#format").value()},{filename: $("#filename").value()},{list: $("#list").value()}),
dataType: "html"
});
timeOutId = window.setTimeout("ft()", 10000);
});
and there is a hyperlink with ID "newm" on page but clicking on the link doesnt trigger the ajax request. Can anyone tell me what is wrong?
Description
I have tryed your code and recognize that your binding to click is not working because the DOM element is not available at this time.
You should bind it under $(document).ready() to ensure the DOM is fully loaded before binding javascript / jquery to that.
This will enusre that your link will work, but its hard to help you without the html source.
If this will not help, please post the html.
My site has a form which insert records in a database using ajax, at the same time, it "refreshes" a table also using AJAX in the same page showing this new record.
So I have the JS code
// New Record Div
$('button[type=submit]').click(function() {
// Read all the form content
var creditor = $('#selCreditor').val();
var reason = $('#txtReason').val();
var value = $('#txtValue').val();
var debtor = $('#selDebtor').val();
$.ajax({
type: 'POST',
url: 'index/insert/creditor/'+creditor+'/reason/'+reason+'/value/'+value+'/debtor/'+debtor,
success: function() {
$('#status').slideDown();
$('#latestRecords').fadeOut();
$.ajax({
type: 'POST',
url: 'index/latest',
success: function(html) {
$('#latestRecords').fadeIn();
$('#latestRecords').html(html);
}
});
}
});
return false;
});
Basically, it inserts a new record in the database, then on success, it requests a page which contains only the table and populate the div with the returned data. It's sort of a refresh when the data is submitted. Everything is done using AJAX.
I've uploaded the situation image for a better understanding. image
The Problem
Everything goes fine until you try to delete a "refreshed" table row. Without the AJAX (only press F5) I can delete any row I want through the delete button, but when I insert a row and the try to delete any row in the table won't do. This is the Delete button code
// TR Fading when deleted
$('.delete').click(function() {
$.ajax({
type: 'POST',
url: 'history/delete/id/'+$(this).attr('id')
});
$(this).closest('tr').fadeOut('slow', function() { $(this).remove(); });
$('#latest')
return false;
});
I suspect that the problem is $(this) which not refers to the delete button element once the table is refreshed, but I don't know how to fix it.
If the entire table is being reloaded then .click() wont work as it will have lost the elements it was applied to. Try using .live() instead.
e.g.
$('.delete').live('click',function(){...});
Also assign $(this) to a variable and use the variable instead, it can help make the code a bit clearer I think. e.g. var $deleteButton = $(this);
take a look at jquerys live, i think this is what you're looking for.
In addition to Nalums anwser, Who stated that you can use .live() — which will work even if you add dynamic elements through jQuery — you should instead use for most occasions the newer .delegate() (version added: 1.4.2)
Could be used in this fashion:
$("table").delegate("td", "hover", function(){
$(this).toggleClass("hover");
});
Or check out api.jquery.com/delegate/ for more information.