AJAX call not always loading when user interacts - php

I am having a couple of problems involving PHP & AJAX using jQuery. To make the whole explanation easier I am going to simply give a link to the site I am working on and if you use the "quote calculator" tab and follow the steps you should hopefully understand my problem
http://bothrealities.very-dev.co.uk/green-it
Just in case you do not, here is an explanation:
When I am clicking on a radio button; the radio buttons in the model section (which calls back data from a PHP file and db through AJAX), the info box to the right does not always populate, sometimes it seems as if the data is stuck in the cache. You can click on a model and then when you click again the model you choose prior populates in the info-box (as if it is one click behind)
Now I am not sure if it is a case of the speed in which the user clicks the buttons, thus breaking to original AJAX call?
I don't know if I need to have the page disable/grey out and have a loading wheel until the data comes back, so users cannot interfere with the process, or not?
Apologies if the above explanation is confusing, I do urge you visit the link above and try it for yourself, it is so much easier to understand that way.
Thank you very very much in advance anyone who can sort this out, I might even pop a small bounty on this post.
Thanks,
Dan.
P.s Am not sure how to add a bounty yet, sorry.
EDIT :::
function productString(product, box) {
$.get("http://<? echo ROOT; ?>includes/forms.php", { product: product }, function(data) {
$("#loadingModel").append(data);
});
$.get("http://<? echo ROOT; ?>includes/forms.php", { box: box }, function(data) {
$("#content-right").empty();
$("#content-right").append(data);
$("#content-right").jScroll();
});
}
function modelString(model, boxModel) {
$.get("http://<? echo ROOT; ?>includes/forms.php", { model: model }, function(data) {
$("#loadingData").empty().append(data);
});
$.get("http://<? echo ROOT; ?>includes/forms.php", { boxModel: boxModel }, function(data) {
$("#boxModel").empty().append(data);
});
}

Sometimes your http://bothrealities.very-dev.co.uk/includes/forms.php?boxModel=1 ends before the http://bothrealities.very-dev.co.uk/includes/forms.php?model=xxxxx has ended so the returned data from the second request isn't what you want to get.
You can try by passing model parameter in the second "GET" too.

"loading wheel" will certainly help out the user (on what's going on).
I haven't looked at the code but here's how you can debug this.
"erase" the box on right before the AJAX call.
in the callback function, use console.log(ajaxcontent) to make sure, you got the intended content from ajax. (this is nice feature of firebug -- a firefox plugin)
update the box.
I hope this helps.

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.

AJAX/PHP – callback after finished loading data

(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

Issues with posting with ajax from a PHP generated poll

I will try to walk you through this very slow. I am trying to make a poll that are subject to change often so I have to make it dynamical. I also need to have this without page reload, so I would need to use Ajax to submit the form. So what I did was to create a PHP script that will echo the poll for me. This works nicely and I get the poll just the way I want it. Oh yeah, forgot to tell that it is a multi step poll. I navigate through 2-4 questions at a time by hiding/showing divs within a JQM 'page'. And by that I mean:
<div data-role='page'>
At the last page I do have a submit button instead of a next button since the poll obviously has no "next" div to show. This submit button does in no way, shape or form work, and thus is the issue here.
$("#submit").click(function()
{
if ($("#form").validate())
{
$.ajax(
{
type:'POST',
url:'add.php',
data:$('#form').serialize(),
success:function(response)
{
$("#answers").html(response);
}
});
}
else
{
return false;
}
})
This is supposed to send my form data to another PHP file that is named add.php, when then is supposed to post it to the div shown abit underneath. (It's really supposed just to save to database but I try to echo it until I see that it works). Now, the twist is that I did another identical piece of code on a non-dynamical form that was not created through PHP, but merely plotted down in HTML. This was also a multi step poll that span out over 3 divs/'pages'. And this had no problems submitting at all.
So to summarize: I had 2 different projects that each handled half my problem. One generated the form dynamically and the other saved a static form that I made. Both forms consisted of a variety of checkboxes, radiobuttons and textareas. Problem is, they won't work together. When I click the submit button I expect the form to echo out the answers into this div (the one you read about a few lines up):
<div data-role="content" id="answers">
Answers comes here:
</div>
Nevertheless, this div remains the same. I stripped down the $("#submit").click(function()) to alert('test'); and I still could not get a reaction. I've quadrillion-checked the variable names and div names and any other names that are relevant, and I've made various minor adjustments on each separate part (both generating the poll and posting it with ajax) as well as to my attempt to combine them without success. So, the million dollar question is what could be wrong? My last remaining hypothesis is that somehow the JavaScript function for $("#submit").click ... is loaded before the script that generates the poll. This would make sense that when the submit click function is declared it would not be linked up to any button like shown here:
<input type="button" id="submit" name="Submit"/>
Does anyone have any clue on how I can make this submit button to work, or even have a clue as to why it does not work? Thanks to anyone who read this far and I hope you posess and are willing to share some knowledge that could help me. Also thanks to the creators of Stack Overflow for implementing an alt+z function for this as I accidentally clicked alt+a then random letters while writing the sentence before this one. Have a nice day!
EDIT: Tried this after a tip from Kevin an answer below, but even the first alert button doesn't react:
$("#submit").click(function()
{
alert("it works");
if ($("#form").validate())
{
$.ajax(
{
type:'POST',
url:'add.php',
data:$('#form').serialize(),
success:function(response)
{
$("#answers").html(response);
return false;
}
});
}
else
{
return false;
}
})
});
You need a return false; under $("#answers").html(response); inside the scope of the success function. Let me know if this works. Good luck, Kevin
I just tried the script above without the post and it worked fine. Do you have jquery loaded before this script executes, and/or do you have or do you have any javascript errors in your console?

POSTing data to the server, behind the scenes

I'm building a website which has a page that users can add content to, and they can rearrange the divs to whichever position and size they want. I'd like to have a save button which saves the current position of each div; however, I don't want the page to refresh each time (I'm also going to have an auto-save, which will have to save the information in the background).
I can't figure out how to post the data to the server though, without causing the page to reload. I figure I need some kind of AJAX request, but can't find anything that tells me how to do that (all the AJAX examples I can find seem to be about reading data from the server). I think I'm just starting to go round in circles now, but I can't get my head around this at all - I know it's probably not a hard thing to do, but I keep getting confused by the different examples.
So, first of all, is this the best way to do it? And, if so, can someone point me to a straightforward example of posting data via AJAX? I'm already using jQuery, so can use that for the Ajax as well.
Thanks.
Super simple AJAX with jQuery:
$.ajax({
url: '/save-the-stuff-url',
type: 'POST',
data: {
// information about your divs, etc.
'foo' : 'bar'
},
success: function(response) {
// if the AJAX call completes successfully, this function will get called.
alert('POST successful!');
}
});
Give it a shot!
Here, try this for AJAX:
$.post("example.php", {
from : "ajax", // put some info in these - they are the params
time : "2pm",
data : "save"
},
function(data) { // callback function - data always passed to it
$("#success").html(data); // do something with that data
}
);
And put this somewhere:
<span id='success'></span>
And then, try this example for example.php:
<?php
if(isset($_POST['from']) and $_POST['from'] == 'ajax'){
echo "<span style='color: green;'>Saved!</span>";
}
else {
echo "<span style='color: red;'>Failure!</span>";
}
?>
And then just modify these to fit your needs, probably changing the file of target. Whatever the script outputs is what is given to the ajax request. This means that if this was my PHP script:
<?php echo "Aloha!"; ?>
And this was my javascript:
$("#output").load("myScript.php");
Then #output would have "Aloha!" in it.
Hope this helps!
Please go through the Jquery site for various examples of post.
HTH
and the jQuery docs pages are a great way to learn jQuery.. the page for post is http://docs.jquery.com/Post
you may also want to look at jQuery draggables if you're not using that yet..
http://docs.jquery.com/UI/API/1.8/Draggable
you can fire a save tied to your draggable object being let go rather easily with
$( ".selector" ).draggable({
stop: function(event, ui) { ... }
});

jQuery AJAX timing issue

In my backend I'm using jquery 1.4.1 and the newest UI 1.8rc1. I defined a couple of buttons that do things... one is create a certain type of page using serialize functions calling a php file and then reloading the entire page. locally this always works like a charm! but as soon as i put it on my providers webserver, it only works in about 5% of times. Heres the code:
buttons: {
'Seite erstellen': function() {
$.post("webadmin/pages.create.serialize.php",$("#page-form").serialize());
$(this).dialog('close');
location.reload(true);
},
'Abbrechen': function() {
$(this).dialog('close');
}
},
Where it gets interesting is, when I put in an alert just before the location.reload part - it will always work. So there seems to be a timing issue that the serializing is executed but can't finish before the page reloads. i know the meaning of using the serialzing is not to have to reload the page, but i build a navigation etc. so i need to reload. (thinking about that now... i could really serialize everything... anyway) Is there a simple solution to this? is there something like a little timer i could build in to make it wait until the serialization is done? is this a normal behaviour?
You need to take advantage of the callback in the $.post() method:
$.post(
"webadmin/pages.create.serialize.php",
$("#page-form").serialize(),
function(data, textStatus, xhr) {
alert("I'm done loading now!");
}
);
Not exactly sure what "this" refers to inside of the callback function so I'll leave the implementation as an exercise to the reader. :-)

Categories