Error Loading AJAX on Document Ready Using JQuery - javascript

I'm trying to create a PHP page that periodically updates values of several elements on the page. I'm using a host that limits my hits per day, and each hit to any page they're hosting for me counts against my total. Therefore, I'm trying to use JQuery/AJAX to load all of the information that I need from other pages at one time.
I'm calling the following index.php. This method achieves the desired affect exactly the way I want it, but results in three hits (dating.php, dgperc.php, and pkperc.php) every two seconds:
var focused = true;
$(window).blur(function() {
focused = false;
});
$(window).focus(function() {
focused = true;
});
function loadData() {
if (focused) {
var php = ["dating", "dgperc", "pkperc"];
$.each(php, function(index, value) {
$('#'+this).load(this+'.php');
});
}
}
$(document).ready(function() {
loadData();
});
setInterval(function() {
loadData();
}, 2000);
I'm calling the following index1.php. This is where I'm at as far as a method that only results in one hit every two seconds. My workaround is that I have combined the three php pages that I was loading into one, dating1.php. I load this into a div element, #cache, all at once. This element is set to hidden using CSS, and then I just copy its inner HTML into the appropriate elements:
var focused = true;
$(window).blur(function() {
focused = false;
});
$(window).focus(function() {
focused = true;
});
function loadData() {
if (focused) {
var php = ["dating", "dgperc", "pkperc"];
$('#cache').load('dating1.php');
$.each(php, function(index, value) {
$('#'+this+'1').html($('#'+this).html());
});
}
}
$(document).ready(function() {
loadData();
});
setInterval(function() {
loadData();
}, 2000);
Dating1.php will produce different outputs every time it's run, but here is an example of the output:
<span id = "dating">4 years, 7 months, 3 weeks, 10 seconds ago.</span>
<span id = "dgperc">21.9229663059</span>
<span id = "pkperc">22.2121099923</span>
On document ready, index1.php does not function properly: the #cache element isn't filled at all, so the other elements don't get filled either. However, after two seconds, the loadData() function runs again, and then the #cache element is filled correctly, and so are the other elements. For some reason, this isn't a problem on my index.php page at all, and I'm not sure why there's a difference here.
How can I get #cache to load the first time so that the page loads correctly? Or is there a better way to do this?

Each AJAX call is basically a page visit in the background. Like telling your assistant three different times to get you one coffee. Or telling them one to get you three coffees.
If you don't want to combine your three PHP pages into one - thus keeping code separate and easier to maintain. Consider creating one "cache.php" script and inside it:
cache.php:
$outputData = array('dating' => false, 'dgperc' => false, 'pkperc' => false);
foreach($outputData as $file => &$data)
{
//buffer output
ob_start();
//run first script (be smart and file_exists() first)
include_once($file . '.php');
$data = ob_get_clean();
}
//output JSON-compliant for easy jQuery consumption
echo json_encode($outputData);
Then in your javascript:
function loadData() {
if (focused) {
//call ajax with json and fill your spans
$.ajax({
async: true,
cache: false,
dataType: 'json',
success: function(data, textStatus, jqxhr) {
$('#dating').html(data.dating);
$('#dgperc').html(data.dgperc);
$('#pkperc').html(data.dgperc);
// NOTE... do a console.dir(data) to get the correct notation for your returned data
},
url: 'cache.php'
});
}
You are calling cache.php once every two seconds, saving on the 3-hits of calling the php files individually. Using a middle-man file you keep your scripts separate for maintainability.

Related

AJAX on Button Click runs incrementally

I've implemented a simple AJAX call that is bound to a button. On click, the call takes input from an and forwards the value to a FLASK server using getJSON. Using the supplied value (a URL), a request is sent to a website and the html of a website is sent back.
The issue is the AJAX call seems to run multiple times, incrementally depending on how many times it has been clicked.
example;
(click)
1
(click)
2
1
(click)
3
2
1
Because I am sending requests from a FLASK server to another website, it effectively looks like I'm trying to DDOS the server. Any idea how to fix this?
My AJAX code;
var requestNumber = 1; //done for testing purposes
//RUNS PROXY SCRIPT
$("#btnProxy").bind("click", function() . //#btnProxy is the button
{
$.getJSON("/background_process", //background_process is my FLASK route
{txtAddress: $('input[name="Address"]').val(), //Address is the input box
},
console.log(++requestNumber), //increment on function call
function(data)
{$("#web_iframe").attr('srcdoc', data.result); //the FLASK route retrieves the html of a webpage and returns it in an iframe srcdoc.
});
return false;
});
My FLASK code (Though it probably isn't the cause)
#app.route('/background_process')
def background_process():
address = None
try:
address = request.args.get("txtAddress")
resp = requests.get(address)
return jsonify(result=resp.text)
except Exception, e:
return(str(e))
Image of my tested output (I've suppressed the FLASK script)
https://snag.gy/bikCZj.jpg
One of the easiest things to do would be to disable the button after the first click and only enable it after the AJAX call is complete:
var btnProxy = $("#btnProxy");
//RUNS PROXY SCRIPT
btnProxy.bind("click", function () //#btnProxy is the button
{
btnProxy.attr('disabled', 'disabled');//disable the button before the request
$.getJSON("/background_process", //background_process is my FLASK route
{
txtAddress: $('input[name="Address"]').val(), //Address is the input box
},
function (data) {
$("#web_iframe").attr('srcdoc', data.result); //the FLASK route retrieves the html of a webpage and returns it in an iframe srcdoc.
btnProxy.attr('disabled', null);//enable button on success
});
return false;
});
You can try with preventDefault() and see if it fits your needs.
$("#btnProxy").bind("click", function(e) {
e.preventDefault();
$.getJSON("/background_process",
{txtAddress: $('input[name="Address"]').val(),
},
console.log(++requestNumber),
function(data)
{$("#web_iframe").attr('srcdoc', data.result);
});
return false;
});
Probably you are binding the click event multiple times.
$("#btnProxy").bind("click", function() { ... } );
Possible solutions alternatives:
a) Bind the click event only on document load:
$(function() {
$("#btnProxy").bind("click", function() { ... } );
});
b) Use setTimeout and clearTimeout to filter multiple calls:
var to=null;
$("#btnProxy").bind("click", function() {
if(to) clearTimeout(to);
to=setTimeout(function() { ... },500);
});
c) Clear other bindings before set your calls:
$("#btnProxy").off("click");
$("#btnProxy").bind("click", function() { ... } );

Two ajax forms not working at the same time

I have two boxes, one box is called min amount and another is called max amount. When you put 100 in the max amount, it will find products that are less then $100. But when you put lets says later $50 in the min amount, it wont work unless you refresh the page
My question is, how do I make this script work for both of my boxes as if I use one box for the ajax the other ones doess not work without refreshing.
I'm sorry if I sound a bit confusing but this is what I tried so far and it still doesn't work.
<script>
//on keyup, start the countdown
$('#maxprice').keyup(function(){
doneTyping();
});
function doneTyping() {
var value = $('#maxprice').val();
$.post("script/limitedfetcher/maxprice.php",
{
name: value
},
function(data, status){
$("#loader").empty();
$('#loader').html(data);
});
}
</script>
<script>
$('#minprice').keyup(function(){
doneTyping();
});
function doneTyping() {
var value = $('#minprice').val();
$.post("script/limitedfetcher/minprice.php",
{
name: value
},
function(data, status){
$("#loader").empty();
$('#loader').html(data);
});
}
</script>
Use this!!
Pass the element where keyup occurs to the function.
Then, based on which of the two it is... decide about the URL... The rest of the function is the same, no need to define it twice.
<script>
//on keyup, start the countdown
$('#minprice, #maxprice').keyup(function(){
doneTyping(this);
});
function doneTyping(element) {
var value = $(element).val();
if($(element).attr("id")=="maxprice"){
url = "script/limitedfetcher/maxprice.php";
}else{
url = "script/limitedfetcher/minprice.php";
}
$.post(url,{
name: value
},
function(data, status){
$("#loader").empty();
$('#loader').html(data);
});
}
</script>

JQuery event is being overtaken by another

I have a form which in fact consists of two forms. Each form is a reservation form. There are two dropdowns in both forms - destination from and destination to. There is an even handler, which calls AJAX to get possible destinations to when destination from is being selected/changed.
Another event handler (round trip checkbox) fills second form dropdowns by switching destinations from first form.
So if the first form has:
destination one: France
destination two: Austria
Then, if round trip is checked, the second form is immediately filled:
destination one: Austria
destination two: France
The problem is that this two events don't cooperate correctly.
When this code is executed:
id_form_1_destination_from.val(destination_to_0.val());
id_form_1_destination_to.val(destination_from_0.val());
id_form_1_destination_from.change();
id_form_1_destination_to.change();
The first line calls another handler which fills second form (this is the only case when it's not needed). Since it's AJAX, the second line overtakes this AJAX, so now, the second form is correctly filled (switched destinations from first form), but when AJAX is done, it changes the selection of the destination two field.
Is there a way how to avoid this? For example to turn off the event handler or better make JQuery wait until the AJAX is done and then continues. I can't just do .off() on destination to field because I use select2 plugin.
Here is my JQuery:
$(document).ready(function () {
var destination_from_0 = $("#id_form-0-destination_from");
var destination_to_0 = $('#id_form-0-destination_to');
var ride_two = $('#ride_two');
$('.class-destination-from').on('change', function () {
destination_from_changed.call(this);
});
$("#id_round_trip").on('change', function () {
if (($('#id_round_trip').is(':checked')) ) {
var id_form_1_destination_from =$('#id_form-1-destination_from');
var id_form_1_destination_to = $('#id_form-1-destination_to');
ride_two.show('fast');
//id_form_1_destination_from.off();
id_form_1_destination_from.val(destination_to_0.val()).change();
//id_form_1_destination_from.on();
//id_form_1_destination_from.change();
id_form_1_destination_to.val(destination_from_0.val()).change();
}else{
ride_two.hide('fast');
ride_two.find(':input').not(':button, :submit, :reset, :checkbox, :radio').val('').change();
ride_two.find(':checkbox, :radio').prop('checked', false).change();
}
});
$('.class-destination-to').on('change', destination_to_changed);
});
function destination_to_changed() {
var destination_id = $(this).val();
var arrival_container = $(this).siblings('.arrival-container');
var departure_container = $(this).siblings('.departure-container');
if (destination_id == '') {
return;
}
$.ajax({
url: '/ajax/is-airport/' + destination_id + '/',
success: function (data) {
if (data.status == true) {
arrival_container.hide("slow");
departure_container.show("slow");
}
if (data.status == false) {
departure_container.hide("slow");
arrival_container.show("slow");
}
arrival_container.change();
departure_container.change();
}
})
}
function destination_from_changed() {
var destination_id = $(this).val();
if (destination_id == '') {
return;
}
var ajax_loading_image = $('#ajax-loading-image');
var destination_to = $(this).siblings('.class-destination-to');
destination_to.empty();
ajax_loading_image.show();
$.ajax({
url: '/ajax/get-destination-to-options/' + destination_id + '/',
async:false, // ADDED NOW - THIS HELPED BUT IT'S NOT NECESSARY EVERYTIME
success: function (data) {
ajax_loading_image.hide();
destination_to.append('<option value="" selected="selected">' + "---------" + '</option>');
$.each(data, function (key, value) {
destination_to.append('<option value="' + key + '">' + value + '</option>');
});
destination_to.change();
}
})
}
If i'm understanding correctly, you have a concurrency issue. You basically want your first ajax call to be terminated before calling the second right?
I don't see any ajax request in your code but I think the paramter async: false, might be what you need.
Check the documentation: http://api.jquery.com/jquery.ajax/
Hope it helps
You definitely have a classic "race condition" going on here.
Since the AJAX calls seem fairly unrelated to one another, you might need to add some code on the JavaScript side so that potentially "racing" situations cannot occur. For example, to recognize that a combo is "being populated" if you've issued an AJAX request to populate it but haven't gotten the response back yet. You might disable certain buttons.
Incidentally, in situations like this, where two (or more ...) forms are involved, I like to try to centralize the logic. For example, there might be "a singleton object" whose job it is to know the present status of everything that's being done on or with the host. A finite state machine (FSM) (mumble, mumble ...) works very well here. This object might broadcast events to inform "listeners" when they need to change their buttons and such.
You need to cancel the first AJAX request before you start the second. From this SO question:
Abort Ajax requests using jQuery
var xhr;
function getData() {
if (xhr) { xhr.abort(); }
xhr = $.ajax(...);
}

ajaxComplete with getJSON causing loop

I am using ajaxComplete to run some functions after dynamic content is loaded to the DOM. I have two separate functions inside ajaxComplete which uses getJSON.
Running any of the functions once works fine
Running any of them a second time causes a loop cause they are using getJSON.
How do I get around this?
I'm attaching a small part of the code. If the user has voted, clicking the comments button will cause the comments box to open and close immediately.
$(document).ajaxComplete(function() {
// Lets user votes on a match
$('.btn-vote').click(function() {
......
$.getJSON(path + 'includes/ajax/update_votes.php', { id: gameID, vote: btnID }, function(data) {
......
});
});
// Connects a match with a disqus thread
$('.btn-comment').click(function() {
var parent = $(this).parents('.main-table-drop'), comments = parent.next(".main-table-comment");
if (comments.is(':hidden')) {
comments.fadeIn();
} else {
comments.fadeOut();
}
});
});
Solved the problem by checking the DOM loading ajax request URL
$(document).ajaxComplete(event,xhr,settings) {
var url = settings.url, checkAjax = 'list_matches';
if (url.indexOf(checkAjax) >= 0) { ... }
}

Jquery POST sending multiple variables

I've been trying to figure out this issue with my website for a while now--I have a bunch of "stars" a user can click on.
clicking on a star loads a file into a div with information regarding that star. It also loads a button for the players to click and "Take over" the planet. That all is working well and fine, however--I've recently discovered an issue that I'm not quite sure how to handle.
IF a player clicks on multiple stars before reloading the page for whatever reason--when the click to attack/whatever the star--it'll send multiple requests across the server. I at first thought this was something in my coding that was sending all information regarding all the stars, however I've come to realize that it's only the stars that the player has clicked on.
Now--Here is the code:
$.ajaxSetup ({
// Disable caching of AJAX responses
cache: false
});
function loadStatus()
{
$.ajax(
{
url:'world1.php', error: function () { }, dataType:'json',
success: function(data)
{
denial = false;
$('#credits').html(data.credits);
$('#fuelleft').html(data.fuel);
$('#energyleft').html(data.energy);
}
});
}
function currentStarMapURL(URL)
{
$('#starmap').load(URL, {},
function()
{
$('#loader').hide();
fullStarInformation(URL);
starInformation();
setInterval(function() { $('.unknown').effect("highlight",{color:"#800000"}, 1500)});
return false;
}
);
}
/*
purhcase upgrades
*/
/*
Retriever Better Star Info
*/
function fullStarInformation()
{
$(".star").click(
function()
{
$('#planet-bar').empty();
val = this.id;
url = "planet.php?sid="+val;
$('#planet-bar').load(url, {'sid':val},
function()
{
colony(url);
}
);
}
);
}
function colony(url)
{
$('#planet-bar').on("click", "button",
function() {
event.preventDefault();
name = 0;
$(this).hide();
name = $(this).attr('sid');
$.post('purchase.php?mode=planet', {sid: name},
function ()
{
$('#planet-bar').load(url, {}, function () { currentStarMapURL(URL2); })
}
);
$(this).prop('disabled', true);
});
}
I figured at first that the issue was a caching issue, so I added the $.ajaxSetup to the first line, but that didn't seem to change anything.
Then I figured, maybe it's the way the code was being called--I originally had two seperate functions; one for attack, one for colonizing. both of which were being called in the fullStarInformation function, So I moved it all down to one function, i'm still getting the issue.
AFAIK, right now, i may have to rewrite this entire block of code so that the colony function and the starInformation function are separate and not acting upon one another. But I wanted to get a second, third maybe even fourth set of eyes on the code before I go about doing that.
If you are getting multiple ajax calls, chances are you are setting up multiple event handlers.
Just quickly glancing through the code, I would think you should change
function colony(url)
{
$('#planet-bar').on("click", "button", function() { ... } );
To
function colony(url)
{
$('#planet-bar').off("click", "button"); //unbind old event handlers
$('#planet-bar').on("click", "button", function() { ... } );

Categories

Resources