AJAX/PHP – callback after finished loading data - php

(Not sure if I missed an already similar answered question…)
On click of a button, I'm loading various images from a database via PHP/MySQL and appending it to the body (the actual images are of course not stored in the database, the correct selection of the images is based on a posted variable).
My goal is to display a loading indicator after pressing the button and hiding the indicator after all the image data has completely loaded and displayed. This may be an easy to solve callback issue but I'm just getting started with AJAX. :)
The following is the code I currently managed to come up with. I'm guessing the load() function is not really the right one here?
Thanks for your help!
$("#somebutton").click(function(){
alert("fetching…");
$.post('loadmore.php', {
somevariable: somevariable
},
function(data){
$("body").append(data);
$(window).load(function(){
alert("finished loading…");
});
});
});

The function you have with the finished loading... alert is a success callback, so it gets executed once the AJAX call has finished. This means you don't need to use $(window).load.
Also, you can use the html method on an element to change its contents and display a message.
Something like this would work fine:
$("#somebutton").click(function(){
$('#divID').html('Loading...');
$.post('loadmore.php', {
somevariable: somevariable
},
function(data){
$("body").append(data);
$('#divID').html('');
});
});

Read the docs http://api.jquery.com/jQuery.ajax/
Use the success callback to append the body and then the complete and error callbacks to clear things up correctly.
$("#somebutton").click(function(){
alert("fetching…");
$.post('loadmore.php', {
somevariable: somevariable
})
.success(function(data){$("body").append(data)})
.error(function(){alert("oh dear")})
.complete(function(){alert("finished loading…")});
});
Remember to always have a fallback for removing the loader - nothing worse than just having a loader and no way to remove it from the page and continue using the application / web site.

I managed to solve my problem by reading and tweaking the code in the following article.
The function load() with the equation containing the self-explanatory variables [imagesLoaded >= imageCount] did the trick.
Know when images are done loading in AJAX response

Related

jQuery scrollbar plugin not working on Ajax loaded content

The problem is this:
I have a simple, two fields form which I submit with Ajax.
Upon completion I reload two div's to reflect the changes.
Everything is working perfect except a jQuery plugin. It's a simple plugin that can be called with simple
function(){
$('.myDiv').scrollbars();
}
It's simple and easy to use, but it doesn't work on Ajax loaded content. Here is the code I use to post form and reload div's:
$(function() {
$('#fotocoment').on('submit', function(e) {
$.post('submitfotocoment.php', $(this).serialize(), function (data) {
$(".coment").load("fotocomajax.php");
}).error(function() {
});
e.preventDefault();
});
});
I've tried creating a function and calling it in Ajax succes:, but no luck. Can anyone show me how to make it work ? How can that simple plugin can be reloaded or reinitialized or, maybe, refreshed. I've studied a lot of jQuery's functions, including ajaxStop, ajaxComplete ... nothing seems to be working or I'm doing something wrong here.
If you're loading elements dynamically after DOM Document is already loaded (like through AJAX in your case) simple binding .scrollbars() to element won't work, even in $(document).ready() - you need to use "live" event(s) - that way jQuery will "catch" dynamically added content:
$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+
Source: jQuery Site
Even if I am totally against using such plugins, which tries to replicate your browser's components, I'll try to give some hints.
I suppose you are using this scrollbars plugin. In this case you may want to reinitialize the scrollbars element, and there are many ways to do this. You could create the element again like in the following example
<div class="holder">
<div class="scrollme">
<img src="http://placekitten.com/g/400/300" />
</div>
</div>
.....
$('.scrollme').scrollbars();
...
fakedata = "<div class='scrollme'>Fake response from your server<br /><img src='http://placekitten.com/g/500/300' /></div>";
$.post('/echo/html/', function(response){
$('.holder').html(fakedata);
$('.scrollme').scrollbars();
});
If you want to update the contents of an already initialized widget instead, then things gets more complicated. Once your plugin initialize, it moves the content in some custom wrappers in order to do its 'magic', so make sure you update the correct element, then trigger the resize event on window, pray and hopefully your widget gets re-evaluated.
If it doesn't help, then try to come up with some more details about your HTML structure.
I want to thank everyone of you who took their time to answer me with this problem I have. However, the answer came to me after 4 days of struggle and "inventions" :), and it's not a JS or Jquery solution, but a simple logic in the file.
Originally, I call my functions and plugins at the beginning of the document in "head" tag, like any other programmer out here (there are exceptions also ).
Then my visitors open my blog read it and they want to post comments. But there are a lot of comments, and I don't want to scroll the entire page, or use the default scroll bars, simply because they're ugly and we don't have cross browser support to style that, just yet.
So I .post() the form with the comment, and simply reload the containing all of them. Naturally .scrollbars() plugin doesn't work. Here come the solution.
If I put this :
<script>$('.showcoment').scrollbars();</script>
in the beginning of my loaded document (with load() ), will not work, because is not HTML and it's getting removed automatically. BUT !!! If i do this:
<div><script>$('.showcoment').scrollbars();</script></div>
at the same beginning of loaded document, MAGIC .... it works. The logic that got me there I found it in the basics of javascript. If your script is inside an HTML element, it will be parsed without any problem.
Thank you all again, and I hope my experience will help others.
If I understand you correctly, try this:
var scrollelement = $('.myDiv').scrollbars();
var api = scrollelement.data('jsp');
$(function () {
$('#fotocoment').on('submit', function (e) {
$.post('submitfotocoment.php', $(this).serialize(), function (data) {
$(".coment").load("fotocomajax.php");
api.reinitialise();
}).error(function () {
});
e.preventDefault();
});
});
reinitialise - standart api function, updates scrolbars.

Updating the dynamic PHP in a jQuery Mobile site after updating the database

Let's say I have 2 pages in a jQuery Mobile website.
Page1 - shows data from a database using inline PHP.
Page2 - inserts new data into the database.
The problem is that page1 is not updated when going back, after page2 adds something to the database. I can get it updated by pressing F5, but how can I achieve the same update using jQuery?
I think you're showing data in Page 1 using the pageinit event. This will fire only once and won't update your data every time you add new data.
You need to use pagebeforeshow event of Page 1 to get data from database. This way, new data will be brought every time, which is what you need. Here's a syntax :
$(document).on("pagebeforeshow", "#page1", function() {
//call to server
});
If you're not using pageinit, you must be using document.ready event to get data. Well, thats the way thats done. You must not use ready with jquery mobile. DOM ready will initialize the whole document which will make the ajax page change feature of jQM pointless & useless.
It was late last night and I missed that I should just get my inline php content using Ajax.
So this is how I solved it:
Moved everything contain dynamic content using PHP in a separate file.
Add an Ajax call to the bottom of the page that loads the PHP file as follows:
$(document).on('pagebeforeshow', function(){
$.ajax({
type: "GET",
url: "includes/db/ajax_show_php_content.php",
success: function(html) {
$("#page1").html(html); //Insert PHP content
$("#page1").trigger('create'); //Apply jQuery Mobile style to it.
});
});
Thanks to #hungerpain and #anglinb for their help in figuring this out.
I'm not extremely familiar with jQuery Moblie but here's what I found:
function refreshPage()
{
jQuery.mobile.changePage(window.location.href, {
allowSamePageTransition: true,
transition: 'none',
reloadPage: true
});
}
I think the reloadPage to true should do the trick.
If that doesn't work, check out this answer: jQuery Mobile Page refresh mechanism
Hope this helps!

JS not working on echoed PHP

So I have a form that is submitted via an Ajax POST request. After the send button is clicked, the form is removed and a processing graphic is put in its place. The form data is sent to my PHP script, validated, and a thank you message returns to replace the processing graphic if everything checks out. But if there is a validation error, I have a copy of the entire form echoed back to the div where the original form was at showing where the errors are in the form. This all works fine except when the copy of the form is echoed back, the JS for the form doesn't work? Neither the JS for the send button or for my focus/blur functions on the inputs. Thank you for any help.
When you remove the form from the DOM, the events are cancelled as well. You can have a function that sets these events and call it when there are errors in the response.
Did you try to just hide your form and display the processing graphic instead of removing the form ? And when you have an error, hide the graphic and display the form again.
With this solution, error handling will be a little more difficult, but you will not have your form at 2 places in your project !
When you insert HTML mixed Javascript into some node, eg a div, it isn't the same as serving it the first time as part of the whole document. It isn't considered a script when inserted as innerHTML or some textnode.
You have a few options:
** Switch visibility and encode the errorresponse (in JSON for example)
Create 2 divs, one holding the form, the other the PROCESSING image.
Switch display to none for the form when processing, and the image to block.
When you have processed the form and you have an error, encode it somehow (JSON, eg) and send that back, and let an EXISTING script on the page interpret the response.
You can for example create some structure that holds each formelementname, and the error associated with it, so you can easily highlight them in your form if you create an empty span next to each formelement where you can display the error.
When the answer arrives from the server, you can display the form again, and display:none the PROCESSING div.
** Interpret your response (WITH JAVASCRIPT)
This is more difficult, but also more elegant.
I once needed this (Javascript that returned from an XHR request), and Randy Webb helped me out with a smart approach.
It is too much to explain here.
Read this thread for a more detailed approach, and links to the script of Randy:
http://tinyurl.com/6pakdu
$.ajax({
url: 'mypage.html',
success: function(){
alert('success');
**<ADD YOUR CUSTOM CODE AFTER AJAX SUCCESS - JS CODE>**
},
error: function(){
alert('failure');
}
});
You can also ref.
http://docs.jquery.com/Ajax_Events
$.ajax({
beforeSend: function(){
// Handle the beforeSend event
},
complete: function(){
// Handle the complete event
}
// ......
});

php ajax within ajax

I have some ajax that loads php script output into a div. I would like the user then to be able to click on links in the output and rewrite the div without reloading the whole page. Is this possible in principle? Imagine code would look like:
html
<div id="displayhere"></div>
php1 output
echo 'ChangeToNew';
JS
function reLoad(par1,par2,par3) {
...
document.getElementById("displayhere").innerHTML=xmlhttp.responseText;
xmlhttp.open("GET","php2.php?par1="+par1 etc.,true);
xmlhttp.send();
php2
$par1 = $_get['par1'];
change database
echo ''.$par1.'';
Could this in principle work or is the approach flawed?
Thanks.
What you describe is standard, everyday AJAX. The PHP is irrelevant to the equation; the JS will simply receive whatever the server sends it. It just happens that, in your case, the server response is being handled by PHP. The JS and PHP do not - cannot - have a direct relationship, however.
So the principle is fine. What you actually do with it, though, will of course impact on how well it works.
Things to consider:
what will the PHP be doing? This may affect the load times
what about caching responses, if this is applicable, so the PHP doesn't have to compute something it's previously generated?
the UI - will the user be made aware that content is being fetched?
Etc.
I'm used to using jQuery so will give examples using it.
If you create your links as
Click Me
You could then write your code as
<script>
$("#do_this").live('click', function(){
var link_url = $(this).attr('href');
$.ajax({
url: link_url,
success: function(data) {
$('#displayhere').html(data);
}
return false;
};
</script>
If you use jQuery, make sure you use the .live('click', function(){}) method versus the .click(function(){}) method, otherwise it won't recognize dynamically created elements. Also make sure you do a return false.

jQuery.get() - How do I use the entire result?

I read this question, and I'm pretty sure it's 90% of what I need, but I'm after something more than just this, and my success formulating my query in Google has been less than stellar.
What I'd like to do
I have a form on a site that, when submitted, needs to connect with a database, and then the user needs to be apprised of the result. I'm trying to get the result page to load in a modal jQuery dialog instead of forcing a full page reload. At present, I'm just trying to create a jQuery dialog that replaces the contents of a <div> with the product of a PHP file. I know I will get the PHP file's execution result this way. That's what I'm after, but it currently is not working.
My code currently looks like this:
$(document).ready(function() {
$("#dialog").get('include.php', function(data) {
$("div#dialog").html(data);
});
});
And include.php is simply:
<?
echo "<h1>Loaded</h1>";
?>
When I load the page, the original contents of #dialog are still there. I have a strong suspicion that what I'm failing to grasp isn't major, but I've had bad luck finding the fix. I'm a web dev newbie. How do I wwebsite as on the internet?
You are calling get on a jQuery result. That'a a different method than $.get, the one you should be using:
$(document).ready(function() {
$.get('include.php', function(data) {
$("div#dialog").html(data);
});
});
i have been using Ajax call for the same purpose. So try this :
$(document).ready(function() {
$.ajax('include.php',
success : function(data) {
$("#dialog").html(data);
});
});
If you want to replace the entire contents of the #dialog DOM object with the HTML you load, then you probably want to use .load():
$(document).ready(function() {
$("#dialog").load('include.php', function(data) {
// no need to set the html here as .load() already does that
});
});

Categories