Speed Up Jquery heartbeats - javascript

I'm a pretty new programmer who made an application that sends out a heartbeat every 3 seconds to a php page and returns a value, the value of which decides which form elements to display. I've been fairly pleased with the results, but I'd like to have my jquery as fast and efficient as possible (its a little slow at the moment). I was pretty sure SO would already have some helpful answers on speeding up heartbeats, but I searched and couldn't find any.
So here's my code (just the jquery, but I can post the php and html if needed, as well as anything anyone needs to help):
<script type="text/javascript">
$(document).ready(function() {
setInterval(function(){
$('.jcontainer').each(function() {
var $e = $(this);
var dataid = $e.data("param").split('_')[1] ;
$.ajax({
url: 'heartbeat.php',
method: 'POST',
contentType: "application/json",
cache: true,
data: { "dataid": dataid },
success: function(data){
var msg = $.parseJSON(data);
if (msg == ""){ //after reset or after new patient that is untouched is added, show checkin
$e.find('.checkIn').show();
$e.find('.locationSelect').hide();
$e.find('.finished').hide();
$e.find('.reset').hide();
}
if ((msg < 999) && (msg > 0)){ // after hitting "Check In", Checkin button is hidden, and locationSelect is shown
$e.find('.checkIn').hide();
$e.find('.locationSelect').show();
$e.find('.finished').hide();
$e.find('.reset').hide();
$e.find('.locationSelect').val(msg);
}
if (msg == 1000){ //after hitting "Checkout", Option to reset is shown and "Finished!"
$e.find('.checkIn').hide();
$e.find('.locationSelect').hide();
$e.find('.finished').show();
$e.find('.reset').show();
}
}
});
});
},3000);
$('.checkIn').click(function() {
var $e = $(this);
var data = $e.data("param").split('_')[1] ;
// gets the id of button (1 for the first button)
// You can map this to the corresponding button in database...
$.ajax({
type: "POST",
url: "checkin.php",
// Data used to set the values in Database
data: { "checkIn" : $(this).val(), "buttonId" : data},
success: function() {
// Hide the current Button clicked
$e.hide();
var $container = $e.closest("div.jcontainer");
// Get the immediate form for the button
// find the select inside it and show...
$container.find('.locationSelect').show();
$container.find('.locationSelect').val(1);
}
});
});
$('.reset').click(function() {
var $e = $(this);
var data = $e.data("param").split('_')[1] ;
// gets the id of button (1 for the first button)
// You can map this to the corresponding button in database...
$.ajax({
type: "POST",
url: "reset.php",
// Data used to set the values in Database
data: { "reset" : $(this).val(), "buttonId" : data},
success: function() {
// Hide the current Button clicked
$e.hide();
var $container = $e.closest("div.jcontainer");
// Get the immediate form for the button
// find the select inside it and show...
$container.find('.checkIn').show();
}
});
});
$('.locationSelect').change(function(e) {
if($(this).children(":selected").val() === "CheckOut") {
$e = $(this);
var data = $e.data("param").split('_')[1] ;
$.ajax({
type: "POST",
url: "checkout.php",
// Data used to set the values in Database
data: { "checkOut" : $(this).val(), "buttonId" : data},
success: function() {
// Hide the current Button clicked
$e.hide();
var $container = $e.closest("div.jcontainer");
// Get the immediate form for the button
// find the select inside it and show...
$container.find('.finished').show();
$container.find('reset').show();
}
});
}
else{
$e = $(this);
var data = $e.data("param").split('_')[1] ;
// gets the id of select (1 for the first select)
// You can map this to the corresponding select in database...
$.ajax({
type: "POST",
url: "changeloc.php",
data: { "locationSelect" : $(this).val(), "selectid" : data},
success: function() {
// Do something here
}
});
}
});
});
</script>
Thanks for all and any help! Please just ask if you need any more details! Thanks!

Alot of factors could be causing slowness. Some things to consider:
The speed of the heartbeat is not dependent on your client-side javascript code alone. There may be issues with your server-side php code.
Also, a heartbeat every three seconds is very frequent, perhaps too frequent. Check in your browser's developer debug tools that each of the requests is in fact returning a response before the next 3 second interval. It could be that your server is slow to respond and your requests are "banking up".
You could speed your your jQuery a fraction by streamlining your DOM manipulation, eg:
if (msg == "")
{
$e.find('.checkIn').show();
$e.find('.locationSelect, .finished, .reset').hide();
}

Related

JQUERY ajax post - multiple click, one reload - it is possible?

I have a problem and I don't know what is the solution. I would like to reload the specified divs only once after multiple click. Now when I add new item to the database from dropdown input, then after each click each time reload the specified div, and sometimes it is very disturbing. When you want to select a new item from the list, and then suddenly reset, and you need to select again). How can I do that if I click to add new item (sometimes I select 4-5 new items - not multiple select!) then not refresh the specified div after each click, just once with a specified delay.
Here is the current code of the javascript part (now it refresh after 100 milliseconds after a new item added). I hope that someone could help me, or give me an idea how can I resolve this. Many thanks!
<script type="text/javascript">
$('body').on('click',".addhplayer",function() {
var absidplayer = $('#abshidplayer').find(":selected").val();
var abstype = $('#abshtype').find(":selected").val();
var obj = $(this); // first store $(this) in obj
var absseasonid = $(this).attr('data-absseasonid');
var absidclub = $(this).attr('data-absidclub');
var absidmatch = $(this).attr('data-absidmatch');
//var dataString = 'abstype=' + abstype + '&addplayer=1&' + 'absidplayer=' + absidplayer + '&' + 'absidclub=' + absidclub + '&' + 'absidmatch=' + absidmatch + '&' + 'absseasonid=' + absseasonid;
$.ajax({
url: 'edit_absence.php',
type: 'POST',
timeout: 100,
data: {
addtype: abstype,
addhplayer: '1',
addidplayer: absidplayer,
addidclub: absidclub,
addidmatch: absidmatch,
addseasonid: absseasonid
},
success: function(response, textStatus, jqXHR){
$('.hpstatus').show();
$(".hpstatus").load(" .hpstatus");
$('#injur').show();
$("#injur").load(" #injur");
$("#homelineups").load(" #homelineups");
$("#awaylineups").load(" #awaylineups");
},
});
});
</script>
check out my old response to this question :
How do you send an ajax request every time that a form input field changes?
basically wrap your event code to a delayed function, on multiple call it will cancel the previous planned ajax call if the delay is not reach
edit > on your particular code :
var changeTimer = false;
function yourSpecificEventCode(){
var absidplayer = $('#abshidplayer').find(":selected").val();
var abstype = $('#abshtype').find(":selected").val();
var $o = $(this); // first store $(this) in obj
var absseasonid = $o.attr('data-absseasonid');
var absidclub = $o.attr('data-absidclub');
var absidmatch = $o.attr('data-absidmatch');
$.ajax({
url: 'edit_absence.php',
type: 'POST',
timeout: 100,
data: {
addtype: abstype,
addhplayer: '1',
addidplayer: absidplayer,
addidclub: absidclub,
addidmatch: absidmatch,
addseasonid: absseasonid
},
success: function(response, textStatus, jqXHR){
$('.hpstatus').show().load(" .hpstatus");
$('#injur').show().load(" #injur");
$("#homelineups").load(" #homelineups");
$("#awaylineups").load(" #awaylineups");
},
});
}
$('body').on('click',".addhplayer",function() {
if(changeTimer !== false) clearTimeout(changeTimer);
let t = this ;
changeTimer = setTimeout(function(){
yourSpecificEventCode.call( t ) ;
changeTimer = false;
},300);
});

Update image after it's been clicked, without reloading page

I'm making this Flag/Unflag system, and it works okay. The only thing I'm struggeling with is how to update the Flag_icon, after it's been clicked? It's should be so it just changes after it's been clicked, and if it's clicked again then it changes back. Right now I have to click the flag, and then reload the page manually, and then it's changed.
$FlagStatus[$count] has the value YES/NO, from my database, and $testjobids[$count] is a unique ID from db table. I've been looking at some Ajax and Javascript to do this, but i can't seem to wrap my head around how to implement it right. I just need to be pointed into the right direction, because I'm a bit stuck.
Index.php
if ($FlagStatus[$count] == ('YES')) {
echo'<img class="Unflagging" onclick="changeImage('.$testjobids[$count].')" id="'.$testjobids[$count].'" data-id = "'.$testjobids[$count].'" src = "../Test/Images/Flag/FlagMarked.png">';
} elseif($FlagStatus[$count] == ('NO')){
echo'<img class="Flagging" onclick="changeImage()" id="'.$testjobids[$count].'" data-id2 = "'.$testjobids[$count].'" src = "../Test/Images/Flag/FlagUnmarked.png">';
}
Flagging.php / Almost same as Unflagging.php
<?php
require("../resources/MysqliHandler.class.php");
require("../resources/layoutfunctions.php");
require("GetData.php");
$ICON_DIMENSION = "16px";
// Used to connect the right server Testreportingdebug or Testreporting
$db = ServerConn();
// -------------------------------------
$MysqliHandler = new mysqliHandler($db);
$MysqliHandler->query("SET NAMES UTF8");
$receiver = $_POST["FlagID"];
$MarkYes = "UPDATE `testreportingdebug`.`testjob` SET `FlagStatus` = 'YES' WHERE id = $receiver";
$query = $MysqliHandler->query($MarkYes);
?>
Ajax
echo'
<script type="text/javascript">
$(document).on("click", ".Unflagging", function(){
var FlagID = $(this).data("id");
$.ajax({
method: "post",
url: "unflagging.php",
data: { FlagID: FlagID},
success: function(data) {
changeImage();
}
});
});
$(document).on("click", ".Flagging", function(){
var FlagID = $(this).data("id2");
$.ajax({
method: "post",
url: "flagging.php",
data: { FlagID: FlagID},
success: function(data) {
changeImage();
}
});
});
</script>
';

Need to be able to run an ajax call with element loaded after document.ready()

I've got checkbox inputs on a page and am filtering the results using ajax.
One search option is type and the vendors option updates depending on the type selected. But this means that the change function used to update the actual results no longer works within the document.ready(). To rectify this, I also call the function within .ajaxComplete().
But as an ajax call is being called within the ajaxComplete(), it is causing an infinite loop and crashing the site.
$(document).ready(function(){
$('input[type=radio]').change(function(){
var type = $(this).attr('data-id');
$.ajax({
method: 'POST',
url: 'assets/ajax/update-filters.php',
data: {type : type},
success: function(data)
{
$('#vendor-filter input[type=checkbox]').prop('checked', false);
vendors = [];
$('#vendor-filter').empty();
$('#vendor-filter').html(data);
}
});
$('#vendor-filter input[type=checkbox]').change(function(){
filterResults(this);
});
});
$(document).ajaxComplete(function(){
$('#vendor-filter input[type=checkbox]').click(function(){
filterResults(this);
});
});
function filterResults($this)
{
var type = $('input[type=radio]:checked').attr("data-id");
var vendor = $($this).attr('data-id');
if($($this).prop('checked'))
{
var action = 'add';
vendors.push(vendor);
}
else
{
var action = 'remove';
var index = vendors.indexOf(vendor);
if(index >= 0)
{
vendors.splice(index, 1);
}
}
$.ajax({
method: 'POST',
url: 'assets/ajax/filter-results.php',
data: {'vendor' : vendor, 'action' : action, 'vendors' : vendors, 'filter_type' : type},
success: function(data)
{
$('#results').empty();
if(action == 'add')
{
window.history.pushState("", "Title", window.location.href+"&v[]="+vendor);
}
else if(action == 'remove')
{
var newUrl = window.location.href.replace("&v[]="+vendor, "");
window.history.replaceState("", "Title", newUrl);
}
$('#results').html(data);
}
});
}
How do I get the .change function to still work after the input checkbox has been called via ajax previously and without causing a loop with .ajaxComplete() ?
Any help would be greatly appreciated.
Thanks
Please try by change function as follow :
$(document.body).on("change",'input[type=radio]',function(){
var type = $(this).attr('data-id');
$.ajax({
method: 'POST',
url: 'assets/ajax/update-filters.php',
data: {type : type},
success: function(data)
{
$('#vendor-filter input[type=checkbox]').prop('checked', false);
vendors = [];
$('#vendor-filter').empty();
$('#vendor-filter').html(data);
}
});

select not getting updated on ajax call

I have an ajax call to dynamically create select elements. the amount of selects is dependent on another select. This works fine. for my test 3 select menus should be created dynamically which works fine. the dynamically created selects will make ajax calls on their own to create some options dynamically, this is where I have the issue. Everything seems to be working except the options for a second select is not getting populated. Please see code below.
Thank you
$('#union').on('change',function(){
var union_id = $(this).val();
if(union_id){
$.ajax({
type:'POST',
url:'fetch_referee.php',
data:'union_id='+union_id,
dataType: 'json',
success:function(data){
$('#dynamic_selects').html(data.html);
var total = data.total;
for(i=1; i<=total; i++){
$('#allreferee'+i).on('change', function(){
var all_games = $(this).val();
//alert(all_games);// this is good output is valid
if(all_games){
$.ajax({
type:'POST',
url:'fetch_places.php',
data:'all_games='+all_games,
dataType: 'json',
success:function(html){
alert(html);/// this is good.. returns option values
$('#refposition'.i).html(html);//the select menu does not get updataded
}
});
}else{
$('#refposition'+i).html('<option value=""></option>');
}
});
}
}
});
}else{
}
});
You have to add the selector parameter, otherwise the event is directly bound instead of delegated, which only works if the element already exists (so it doesn't work for dynamically loaded content). Check this for more details
Your code should now look like this
$(document.body).on('change','#union',function(){
var union_id = $(this).val();
if(union_id){
$.ajax({
type:'POST',
url:'fetch_referee.php',
data:'union_id='+union_id,
dataType: 'json',
success:function(data){
$('#dynamic_selects').html(data.html);
var total = data.total;
for(i=1; i<=total; i++){
$(document.body).on('change','#allreferee'+i, function(){
var all_games = $(this).val();
//alert(all_games);// this is good output is valid
if(all_games){
$.ajax({
type:'POST',
url:'fetch_places.php',
data:'all_games='+all_games,
dataType: 'json',
success:function(data){
alert(html);/// this is good.. returns option values
$('#refposition'+i).html(data.html);//the select menu does not get updataded
}
});
}else{
$('#refposition'+i).html('<option value=""></option>');
}
});
}
}
});
}else{
}
});
I'm sure that your methodology is flawed, but if you must:
$('#union').change(function(){
var union_id = $(this).val();
if(union_id !== ''){
$.post('fetch_referee.php', 'union_id='+union_id, function(data){
$('#dynamic_selects').html(data.html);
$('[id^=allreferee').change(function(){ // I would give the Elements an HTML class instead - but
var t = $(this), all_games = t.val();
// console.log(all_games); // this is good output is valid ??
if(all_games === ''){
t.html("<option value=''></option>");
}
else{
$.post('fetch_places.php', 'all_games='+all_games, function(html){
// console.log(html); // this is good.. returns option values ??
t.html(html); // the select menu does get updataded ??
}, 'json');
}
});
}, 'json');
}
});

Comparing user input value with JSON object via ajax to ultimately update page content

On page load for my current project, I have a modal overlay appear that prompts the user to enter a 5 digit long value. From that value, I want to have an AJAX call hit an API to see if that value exists/matches and from there, update the nav bar to say, "Hello, [user]" ([user] being another key value pair from the JSON object that the 5 digit long value is referencing. I'm still new to AJAX, so I'm wondering what the best way to go about doing this. I know the following is completely wrong, but I imagine this is the basic framework for starting out something like this.
$("#inputForm").submit(function(){
$.ajax({
url: "/my/api/url/",
type: "POST",
data: postData
success: function(postData){
//if 5-digit value matches value in the API, update the navbar with name key value pair in the JSON object
}
});
});
Try utilizing change event prompt
$(function() {
var check = function(vals, data) {
if (vals.length === 5 && vals.split("").every(Number)) {
if (vals in data) {
// do `$.ajax()` stuff here
/*
$.ajax({
url: "/my/api/url/",
type: "POST",
data: vals
success: function(returnData) {
var data = JSON.parse(returnData);
// check data and update nav bar
$("#navbar").html("Hi, " + data)
}
error: function() {
evt.preventDefault();
// show error
}
});
*/
$("#navbar").html("Hi, " + data[vals])
}
}
};
var data = {
12345: "abc"
};
var vals = prompt("enter 5 digits");
if (vals !== null) check(vals, data);
$("input").change(function(e) {
check(this.value, data)
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="navbar"></div>
<input type="text" placeholder="enter 12345" />
$("#inputForm").submit(function(evt){
$.ajax({
url: "/my/api/url/",
type: "POST",
data: postData
success: function(returnData){
var data = JSON.parse(returnData);
// check data and update nav bar
}
error: function() {
evt.preventDefault();
// show error
}
});
});

Categories

Resources