Jquery get() method working in random - javascript

I have a div call load-ajax-hotels in which I am trying to load php files after the click event has been fired.
Say that I am trying to load alpha.php, beta.php, gamma.php ... delta.php
$("span.dessert-make").click(function(){
/* Load Initial Data */
$(".ajax-load-hotels").load("./php/alpha.php");
$.get("./php/beta.php", function(data){
$(".ajax-load-hotels").append(data);
});
$.get("./php/gamma.php", function(data){
$('.ajax-load-hotels').append(data);
});
$.get("./php/delta.php", function(data){
$('.ajax-load-hotels').append(data);
});
});
But this call is not working properly. I mean that at each instance of the click event I get different results. Some times just alpha.php and beta.php gets displayed some times every php files duplicate comes along. Its random every time. Can some one tell me what the problem is?
And also how do I make php files load as the user scrolls down to bottom of the page. How to implement the scrollTo() method for this. x and y pos becomes different once window resizes.
Sorry. That I might have overlooked. I corrected it.

Assuming you are trying to load these sequentially (syncronously), I would probably go with something like this:
function load_pages(index, pages) {
$.get("./php/" + pages[index] + ".php", function(data) {
$(".ajax-load-hotels").append(data);
if (index + 1 < pages.length) {
load_pages(index + 1, pages);
}
})
}
$("span.dessert-make").click(function(){
load_pages(0, ["alpha", "gamma", "delta"]);
});

You missed a }) at
$.get("./php/2.php", function(data){
$(".ajax-load-hotels").append(data); // here is missed });
$.get("./php/3.php", function(data){
$('.ajax-load-hotels').append(data);
});
Correct:
$.get("./php/2.php", function(data){
$(".ajax-load-hotels").append(data);
});
$.get("./php/3.php", function(data){
$('.ajax-load-hotels').append(data);
});
EDIT 1:
And, $.get is asynchronous.
To make it synchronous (I provided just an example):
$.ajax({
url: urltophp,
async: false,
success: function(data) { $(".ajax-load-hotels").append(data) },
dataType: 'html'
});

Related

What is the proper way of doing long polling using jQuery and AJAX

I have a project which involves live notification. So I stumbled upon using socket io but I didn't have enough time to learn it yet. So I tried doing it with AJAX and jQuery. Below is my code structure and I was wondering if this is gonna work with no drawbacks?
setInterval(function(){
if( !element.hasClass('processing') ){
element.addClass('processing');
$.ajax({
type: 'post',
dataType: 'json',
url: ajaxurl,
data: {},
success: function( response ){
/* Success! */
element.removeClass('processing');
}
});
}
}, 2500);
Some Extra Info
The way you described will work. From Experience I would just like to point out some things.
I usually do a recursive function, allows you to wait your interval between ajax calls and not a fixed rate. //OPTIONAL BUT DOES GIVE THE SERVER SOME BREATHING ROOM.
Use window.setTimeout() with an isActive flag. //ALLOWS YOU TO STOP POLLING FOR WHATEVER REASON, AND BECAUSE FUNCTION IS RECURSIVE START UP AGAIN IF NEED BE
For Sake of being thorough, I found it is always a good idea to handle the error case of the $.ajax() post. You could perhaps display some message telling the user he is no longer connected to the internet etc.
Some Sample Code:
var isActive = true;
$().ready(function () {
//EITHER USE A GLOBAL VAR OR PLACE VAR IN HIDDEN FIELD
//IF FOR WHATEVER REASON YOU WANT TO STOP POLLING
pollServer();
});
function pollServer()
{
if (isActive)
{
window.setTimeout(function () {
$.ajax({
url: "...",
type: "POST",
success: function (result) {
//SUCCESS LOGIC
pollServer();
},
error: function () {
//ERROR HANDLING
pollServer();
}});
}, 2500);
}
}
NOTE
This is just some things I picked up using the exact method you are using, It seems that Web Sockets could be the better option and I will be diving into that in the near future.
Please refer :
Jquery : Ajax : How can I show loading dialog before start and close after close?
I hope this could help you
$("div.add_post a").click(function(){
var dlg = loadingDialog({modal : true, minHeight : 80, show : true});
dlg.dialog("show");
$.ajax({
url : "/add.php",
complete : function (){
dlg.dialog("hide");
}
});
return false;
});
//--Loading dialog
function loadingDialog(dOpts, text = "пожалуйста подождите, идет загрузка...")
{
var dlg = $("<div><img src='/theme/style/imgs/busy.gif' alt='загрузка'/> "+text+"<div>").dialog(dOpts);
$(".ui-dialog-titlebar").hide();
return dialog;
}

Get More Table Data On Page Scroll AJAX

I am populating table data with PHP and JQUERY
The problem is that the scroll function is not firing off. I do not have any errors.
I thought maybe I did not load Jquery in the page correctly so I did,
alert( "This means you have JQUERY" );
The alert function did fire off. This is a wordpress site I am working with a plugin and a template file that I wrote.
Is there any reason why the scroll effect might not work? I have never used this before. Could I possible need to load additional libraries or something of that nature?
$(document).ready(function(){
function getresult(url) {
$.ajax({
url: url,
type: "GET",
data: {rowcount:$("#rowcount").val()},
beforeSend: function(){
$('#loader-icon').show();
},
complete: function(){
$('#loader-icon').hide();
},
success: function(data){
$("#productResults").append(data);
},
error: function(){}
});
}
$(window).scroll(function(){
if($(document).height() <= $(window).scrollTop() + $(window).height()) {
if($(".pagenum:last").val() <= $(".total-page").val()) {
var pagenum = parseInt($(".pagenum:last").val()) + 1;
alert.function('Hey the scroll effect works.');
getresult('../wuno-search/inventory-search.php?page='+pagenum);
}
}
});
});
Also I am confused exactly how to add PHP to this function
getresult('../wuno-search/inventory-search.php?page='+pagenum);
For example if I wanted to change the url path to a variable like this,
getresult('<?php echo $assetPath ?> ?page='+pagenum);
Is that correct?

Execute ajax when html element visible on user screen

I have this script which makes ajax request when user reaches the end of the page. It is based on scroll event. At page load I am showing only 16 products on the user screen and when he scrolls down I wish to load another 16 products. My script is working but it executes more than one ajax request which is not what I want. The idea is just to show another set of 16 products. The script is:
$(window).scroll(function() {
if ($(window).scrollTop() + $(window).height() > $('.made').offset().top) {
//here I count how many products I have shown already
var productsshown = $(".productcell").length;
$('.made').hide();
$.ajax({
type: "post",
url: "./ajax/get_more_products.php",
data: {
"product": productsshown
},
dataType: 'json',
cache: false,
success: function(data) {
$("#bcontent").html(data);
$('.made').show();
}
});
}
});
As you can see I have a div which I am using as controler and when user see this div - the ajax is being executed. The result from ajax is being loaed into another div with id="content"
How to avoid scroll event to execute the ajax call more than once? I tried by hiding my controller div .made and upon ajax responce I am showing it again so it can be executed for another 16 products when user goes down to it again.. but ajax is always called executed more than once as I want it..
hmm, Here is a small addition to your code, adding a flag swiched whenever you load more items:
var _itemsLoading = false;
if ((!_itemsLoading) && ($(window).scrollTop() + $(window).height() > $('.made').offset().top)) {
//here I count how many products I have shown already
var productsshown = $(".productcell").length;
$('.made').hide();
_itemsLoading = true;
$.ajax({
type: "post",
url: "./ajax/get_more_products.php",
data: {
"product": productsshown
},
dataType: 'json',
cache: false,
success: function(data) {
$("#bcontent").html(data);
$('.made').show();
_itemsLoading = false;
}
});
}
Simple store the timestamp then you fire your ajax request and reset it then it returns or after 2 seconds.... then the timestamp is set don't fire your requests.
I don't handle the scroll event. I use setInterval() and I test if the position has changed since previous tic.
I just replaced
if ($(window).scrollTop() + $(window).height() > $('.made').offset().top) {
with:
if($(window).scrollTop() + $(window).height() == $(document).height()){
and used the page bottom as ajax controller.. It works now, thanks !

Ajax / Javascript Trouble. Looping previous requests

I have a nifty little piece of Ajax code that loads in PHP.
http://www.moneyworrier.com/client-stories/
What happens is that when you click on a menu item on the left-hand navigation, it reloads a Div with content appropriate.
What it does however is loop through previous requests, which is bothersome (Click on any left hand item 3x and you will see what I mean). I think I need to find a function that does the equivalent of exit; and clears any post data.
My call in code is:
Video
And my JS looks like:
$(document).ready(function () {
$('a.media').click(function () {
var usr = $(this).attr('rel');
$("#displaystories").html('Retrieving..');
$.ajax({
type: "POST",
url: "/client-stories/media.php",
data: "showcode=" + usr,
success: function (msg) {
$("#displaystories").ajaxComplete(function (event, request, settings) {
$(this).html(msg);
});
}
});
});
});
You're binding a new listener to ajaxComplete on every click. Your success callback should just be:
success: function(msg) {
$("#displaystories").html(msg);
}

jQuery plugin bsmSelect doesn't update its values when it is called again and its select options have changed

I'm using bsmSelect jQuery plugin. Basically, what it does is changing the way a select-multiple is rendered to make easier to pick up the options. It hides the select element and shows a list instead.
So, first of all I'm applying the plugin function to my select-multiple element:
$(document).ready(function() {
...
$('#my_select_multiple').bsmSelect({
plugins: [$.bsmSelect.plugins.sortable()],
title: 'Add',
removeLabel: 'Remove'
});
...
});
On the other way, I have another select element (this one is simple) which has an ajax request bind to its change event. This ajax request get new #my_select_multiple options depending on the select simple value. Ajax response is the new HTML for #my_select_multiple options. So I have:
function getNewOptions(val) {
var r = $.ajax({
type: 'GET',
url: /*My URL*/
}).responseText;
return r;
}
...
$(document).ready(function() {
...
$('#my_select_simple').change() {
$('#my_select_multiple').html(getNewOptions($(this).val()));
}
...
});
AJAX is working as expected. New options are got correctly and they are inserted into #my_select_multiple (which is hidden by bsmSelect plugin, but I can check it with Firebug). But bsmSelect didn't realize new changes and doesn't get updated.
So, I think what I want is to reapply $('#my_select_multiple').bsmSelect(); with its new options.
I've been looking around a little bit and here is what I have tried.
1. I've tried to call again the funcion with the success and complete (one at time) of the AJAX request. Didn't work:
function getNewOptions(val) {
var r = $.ajax({
type: 'GET',
url: /*My URL*/,
success: function() { $('#my_select_multiple').bsmSelect(); }
}).responseText;
return r;
}
2. I've tried to bind the function with the on jQuery function. Didn't work:
$('#my_select_simple').on('change', function() {
$('#my_select_multiple').bsmSelect();
});
3. I've tried 1 and 2 removing previosly the HTML generated by bsmSelect. Didn't work.
Thank you very much.
UPDATE: The exact code
First I have a global.js file which apply bsmSelect plugin to some select multiples (.quizzes):
$('.quizzes').bsmSelect({
plugins: [$.bsmSelect.plugins.sortable()],
title: 'Add',
removeLabel: 'Remove'
});
And then, in the php file I define the updateQuizzes function and bind it to the select simple (project_id) change event:
<script type="text/javascript">
function updateQuizzes(project_id) {
var r = $.ajax({
type: 'GET',
url: '<?php echo url_for('event/updateQuizzes')?>'+'<?php echo ($form->getObject()->isNew()?'':'?id='.$form->getObject()->getId()).($form->getObject()->isNew()?'?project_id=':'&project_id=')?>'+project_id,
success: function() { $('.quizzes').bsmSelect({
plugins: [$.bsmSelect.plugins.sortable()],
title: 'Add',
removeLabel: 'Remove'
}); }
}).responseText;
return r;
}
$('#project_id').change(function(){
$('.quizzes').html(updateQuizzes($(this).val()));
});
</script>
As I told, the AJAX request works without problems, but not the calling bsmSelect the second time...
Not sure if this is what the problem is, but you could try
$('#my_select_simple').change() {
$('#my_select_multiple').html(getNewOptions($(this).val())).trigger('change');
}
This triggers a change event on select_multiple, and might fire bsmSelect. I'm not sure what the problem here is exactly, but that's the best I can come up with.
I think you want to set your HTML in the success of the Ajax call, something like:
function loadNewOptions(val) {
$.ajax({
type: 'GET',
url: /*My URL*/,
success: function(data) {
$('#my_select_multiple').html(data).bsmSelect();
}
});
}
And then calling like:
$('#my_select_simple').change() {
loadNewOptions($(this).val());
}
$(document).ready(function() {
$('#my_select_simple').change() {
$('#my_select_multiple').load("your Url", function(){
$('#my_select_multiple').bsmSelect();
});
}
});
something like this should work.
.load will put whatever your url returns into #my_select_multiple
the first parameter is the url to load, and the 2nd is a function to call when it is done. which is where you need to set up your fancy selector.
Ok, I opened a ticket and bsmSelect developer has answered me in minutes. Great!
To let bsmSelect know about its select changes, you have to trigger a change event on the select. There is no need to call bsmSelect again.
So it can be that way:
function loadNewOptions(val) {
var r = $.ajax({
type: 'GET',
url: /*My URL*/,
success: function(data) {
$('#my_select_multiple').html(data).trigger('change');
}
}).responseText;
return r;
}
$('#my_select_simple').change(function() {
loadNewOptions($(this).val());
});

Categories