MySQL AJAX PHP Notification Module - javascript

Can anyone help me with this code? I would like to convert this async ajax to sync ajax. How do I do it? Here is the code that is written below. The system just lags when I leave it for 20 mins without even doing anything. So, maybe the problem is within the code.
function addmsg20(type, msg, data) {
$('#display20').html(data);
}
function waitForMsg20() {
$.ajax({
type: "GET",
url: "liprintednotif.php",
async: true,
cache: false,
timeout: 50000,
success: function(data) {
var data = JSON.parse(data);
if(data.data.length > 0){
var res = data.data;
var printed = "<ul class='menu'>";
$.each(res, function(k, v){
var empext = v.employee_ext;
if(empext == null){
empext = "";
}else{
empext = v.employee_ext;
}
printed += "<li>" +
"<a href='#'>" +
"<h4>" +
" "+v.employee_fname + " " +
v.employee_mname+" "+v.employee_lname+" " +empext+ "<small>" +
v.status_desc+ "</small>" +"</h4>" +
"<p>" + v.subj_name + "</p>" +
"</a></li>";
})
printed += "</ul>";
}else{
printed = "";
}
addmsg20("new", data.count, printed);
setTimeout(
waitForMsg20,
1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
addmsg20("error", textStatus + " (" + errorThrown + ")");
setTimeout(
waitForMsg20,
15000);
}
});
};
$(document).ready(function() {
waitForMsg20();
});
I am completely new to Javascript and/or AJAX so I really need help about this.

To make the AJAX call synchronous, just set async to false:
$.ajax({
type: "GET",
url: "liprintednotif.php",
async: false,
cache: false,
timeout: 50000,
.
.
.

Related

.json not showing in Safari, jQuery plugin

I created a jQuery plugin that shows up in Chrome as expected, but in Safari, it is not loading the following URL so the badges are showing up: https://www.codeschool.com/users/audreyklammer.json
I think this is the issue. Any ideas on either what I should console.log or does anything stand out? I will do the work just would love your input.
Here is the full code on my GitHub but also pasted below:
https://github.com/Klammertime/Badge-Widget/blob/master/dist/js/jquery.insignia.js
;(function($) {
$(document).ready(function() {
var insigniaList = $('.insignia');
for(var i = 0; i < insigniaList.length; i++){
var insigniaEntry = insigniaList[i];
console.log(insigniaEntry);
$(insigniaEntry).insignia(insigniaEntry.dataset.treehouse, insigniaEntry.dataset.codeschool);
}
});
$.fn.insignia = function(usernameTreehouse, usernameCodeschool) {
this.empty();
if (usernameTreehouse) {
getBadges(usernameTreehouse, this);
}
if (usernameCodeschool) {
getBadges2(usernameCodeschool, this);
}
}
function getBadges(usernameTreehouse, element) {
$.ajax({
url: "http://teamtreehouse.com/" + usernameTreehouse + ".json",
type: "GET",
crossDomain: true,
dataType: "json",
async: true,
success: function(dataBack) {
var badges = dataBack.badges;
$(element).append("<h3>I have taken " + badges.length + " lessons and scored " + dataBack.points.total +
" points at Treehouse!</h3><div class=\"badges\"></div>");
badges.forEach(function(badge, i) {
if (i < 7) {
element.find(".badges").append("<li class=\"badgeImages\"> <img src=' " + badge.icon_url + " '/></li>");
}
});
},
error: function(dataBack) {
console.log("something went wrong.");
//this happen when call fails
}
});
}
function getBadges2(usernameCodeschool, element) {
$.ajax({
url: "https://www.codeschool.com/users/" + usernameCodeschool + ".json",
type: "GET",
crossDomain: true,
dataType: "jsonp",
async: true,
success: function(dataBack) {
console.log(dataBack);
$(element).append("<h3>I have taken " + dataBack.badges.length + " lessons and scored " + dataBack.user.total_score +
" points at Codeschool!</h3><div class=\"badges2\"></div>");
var badge = dataBack.badges;
console.log(badge);
badge.forEach(function(badge, i) {
if (i < 7) {
element.find(".badges2").append("<li class=\"badgeImages\"> <img src=' " + badge.badge + " '/></li>");
}
});
},
error: function(dataBack) {
console.log("something went wrong.");
//this happen when call fails
}
});
}
}(jQuery));

JS Alert or append is not working on DOM

Please look at this code on https://jsfiddle.net/safron6/9g98j68g/embedded/result/
I am trying to get the calculated result from the list of APIS and JSON code that is generated to show the precipIntensity. At the end of the code there is an alert and the code works in firebug but nothing is showing up. What may be the reason why the alert does not pop up?
var listAPIs = "";
$.each(threeDayAPITimes, function(i, time) {
var darkForecastAPI= "https://api.forecast.io/forecast/" + currentAPIKey + "/" + locations + "," + time +"?callback=?";
$.getJSON(darkForecastAPI, {
tags: "WxAPI[" + i + "]", //Is this tag the name of each JSON page? I tried to index it incase this is how to refer to the JSON formatted code from the APIs.
tagmode: "any",
format: "json"
}, function(result) {
// Process the result object
var eachPrecipSum = 0;
if(result.currently.precipIntensity >=0 && result.currently.precipType == "rain")
{
$.each(result, function() {
eachPrecipSum += (result.currently.precipIntensity);
totalPrecipSinceDate += eachPrecipSum ; ///Write mean precip
alert(eachPrecipSum );
$("body").append("p").text(eachPrecipSum)
});
}
});
totalPrecipSinceDate did not declared.
I can't access your hosted data source.
Replacing your current $.getJSON call with an $.ajax call should work:
$.each(threeDayAPITimes, function(i, time) {
var darkForecastAPI= "https://api.forecast.io/forecast/" + currentAPIKey + "/" + locations + "," + time +"?callback=?";
$.ajax({
type: 'GET',
url: darkForecastAPI,
async: false,
jsonpCallback: 'jsonCallback',
contentType: 'application/json',
dataType: 'jsonp',
success: function(result) {
var eachPrecipSum = 0;
if(result.currently.precipIntensity >=0 && result.currently.precipType == "rain") {
$.each(result, function() {
eachPrecipSum += (result.currently.precipIntensity);
totalPrecipSinceDate += eachPrecipSum ; ///Write mean precip
alert(eachPrecipSum );
$("body").append("p").text(eachPrecipSum)
});
}
},
error: function(){
alert('failure');
}
});
});

Incrementally load a webpage: Where can I put: $("#LoadingImage").Hide();

I am not very experienced with JavaScript. Please see the code below:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
<script type = "text/javascript">
function GetSQLTable() {
//alert($("#<%=fieldGroupReferences.ClientID%>")[0].value)
var str = $("#<%=fieldGroupReferences.ClientID%>")[0].value
var res = str.split(",");
for (var i = 0; i < res.length; i++) {
$("#LoadingImage").show();
var div = document.createElement('div');
div.id = "div" + i
document.body.appendChild(div);
//alert(res[i]);
$.ajax({
type: "POST",
url: "Default3.aspx/GetSQLTable",
data: '{username: "' + $("#<%=fieldUserName.ClientID%>")[0].value + '", terminalname: "' + $("#<%=fieldTerminalName.ClientID%>")[0].value + '", terminalip: "' + $("#<%=fieldTerminalIP.ClientID%>")[0].value + '", mappingid: "' + res[i] + '", usergroup: "' + $("#<%=fieldUserGroup.ClientID%>")[0].value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess(i,res.length),
failure: function (response) {
//alert(response.d);
alert('there was an error loading the webpage')
}
});
}
function OnSuccess(i,totalrows) {
return function (response) {
if (response.d != "") {
document.getElementById('div' + i).innerHTML = document.getElementById('div' + i).innerHTML + '<br>' + '<br>' + response.d;
}
}
}
}
window.onload = GetSQLTable
</script>
The code incrementally builds a webpage i.e. x number of HTML tables are obtained and displayed to the webpage as and when they become ready. This works.
The problem is I don't know how to remove the LoadingImage once the webpage is complete i.e. $("#LoadingImage").hide();. OnSuccess is called x number of times depending on how many tables are returned so I cannot put it in there.
One way would be to count the number of successful onSuccess() calls, and hide your loading image when they are all complete:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
<script type = "text/javascript">
function GetSQLTable() {
//alert($("#<%=fieldGroupReferences.ClientID%>")[0].value)
var str = $("#<%=fieldGroupReferences.ClientID%>")[0].value
var res = str.split(",");
var numSucceeded = 0;
for (var i = 0; i < res.length; i++) {
$("#LoadingImage").show();
var div = document.createElement('div');
div.id = "div" + i
document.body.appendChild(div);
//alert(res[i]);
$.ajax({
type: "POST",
url: "Default3.aspx/GetSQLTable",
data: '{username: "' + $("#<%=fieldUserName.ClientID%>")[0].value + '", terminalname: "' + $("#<%=fieldTerminalName.ClientID%>")[0].value + '", terminalip: "' + $("#<%=fieldTerminalIP.ClientID%>")[0].value + '", mappingid: "' + res[i] + '", usergroup: "' + $("#<%=fieldUserGroup.ClientID%>")[0].value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess(i,res.length),
failure: function (response) {
//alert(response.d);
alert('there was an error loading the webpage')
}
});
}
function OnSuccess(i,totalrows) {
return function (response) {
if (response.d != "") {
document.getElementById('div' + i).innerHTML = document.getElementById('div' + i).innerHTML + '<br>' + '<br>' + response.d;
numSucceeded++;
if (numSucceeded === totalrows) {
$("#LoadingImage").hide();
}
}
}
}
}
window.onload = GetSQLTable
</script>
Try using .when with an array of your ajax calls. Something like this (simplified to remove the irrelevant bits):
function GetSQLTable() {
//...
var calls = [];
for (var i = 0; i < res.length; i++) {
//..
calls.push($.ajax({
type: "POST",
//..
}));
}
$.when(calls).then(function(d) {
// all done!!!
});

JSON callfunction doesn't fire

here is my example
var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + area.getCenter().lat + "," + area.getCenter().lng + "&sensor=false";
$.getJSON(url, function (data) {
alert("inside json");
//console.log(data);
$.each(data.results[0], function (i, inside) {
console.log(i);
});
//var addr = data.results[0].geometry.location.lat;
});
now i realized that the call function doesn't fire at all....i read other post here and they say that it happens when JSON is not in valid format but here i am getting JSON from Google API so i hope its in valid format.... JSON is here
http://maps.googleapis.com/maps/api/geocode/json?latlng=27.88,78.08&sensor=false
can you please give your comments on this? or may be i am making some mistakes
Maybe try a full ajax call:
$.ajax({
url: "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + area.getCenter().lat + "," + area.getCenter().lng + "&sensor=false",
data: {},
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "JSON",
timeout: 10000,
success: function (Result) {
for (var i = 0; i < Result.d.length; i++) {
element = Result.d[i];
console.log(element);
};
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
can you add it to
$(document).ready(function(){
});
for example:
$(document).ready(function () {
var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + area.getCenter().lat + "," + area.getCenter().lng + "&sensor=false";
$.getJSON(url, function (data) {
alert("inside json");
//console.log(data);
$.each(data.results[0], function (i, inside) {
console.log(i);
});
//var addr = data.results[0].geometry.location.lat;
});
});

Synchronous AJAX...I know that sounds crazy

I have web methods that are called via AJAX in a .Net 4.0 web app. In many cases, the AJAX calls are made repeatedly in a for loop. My problem is, the information the web method is syncing to my server is time stamped and therefore must be synced in the order in which I am sending it to AJAX. Unfortunately, it seems whatever finishes first, simply finishes first and the time stamps are all out of order. I need to basically queue up my AJAX requests so that they execute in order rather than Asynchronously, which I know is the A in AJAX so this might be a totally dumb question.
How do I force the order of execution for AJAX calls done in a for loop?
Edit: Some code
for (var i = 0; i < itemCnt - 1; i++) {
try {
key = items[i];
item = localStorage.getItem(key);
vals = item.split(",");
type = getType(key);
if (type == "Status") {
var Call = key.substring(7, 17);
var OldStat = vals[0];
var NewStat = vals[1];
var Date1 = vals[2];
var Time1 = vals[3];
var miles = vals[4];
try {
stat(Call, OldStat, NewStat, Date1, Time1, miles, key);
}
catch (e) {
alert("Status " + e);
return;
}
}
else if (type == "Notes") {
var Call = key.substring(6, 16);
var Notes = item;
try {
addNotes(Call, Notes);
}
catch (e) {
alert("Notes " + e);
return;
}
}
else if (key == "StartNCTime" || key == "EndNCTime") {
var TechID = vals[0];
var Date = vals[1];
var Time = vals[2];
var Activity = vals[3];
var Location = vals[4];
var Type = vals[5];
try {
logTime(TechID, Date, Time, Activity, Location, Type,
}
catch (e) {
alert(key + ' ' + e);
return;
}
}
}
catch (e) {
alert(key + ' ' + e);
return;
}
}
function stat(Call, OldStat, NewStat, Date1, Time1, miles, key) {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "Service.asmx/update_Stat",
data: '{ CallNumber:"' + Call + '", OldStat:"' + OldStat + '", NewStat:"' + NewStat + '", Date1:"' + Date1 + '", Time1:"' + Time1 + '", Miles: "' + miles + '"}',
success: function (data) { },
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert("Sync Update Stat: " + err.Message);
location = location;
}
});
}
function logTime(TechID, Date, Time, Activity, Location, Type, key) {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "Service.asmx/nonCallTime",
data: '{ TechID:"' + TechID + '", Date1:"' + Date + '", Time1:"' + Time + '", Activity:"' + Activity + '", Location:"' + Location + '", Type: "' + Type + '"}',
success: function (data) { },
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert("Sync Non Call Time: " + err.Message);
location = location;
}
});
}
function addNotes(Call, Notes) {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "Service.asmx/addNote",
data: '{ Call:"' + Call + '", Notes:"' + Notes + '"}',
success: function (data) { },
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert("Sync Notes: " + err.Message);
location = location;
}
});
}
You have to use callbacks.
function ajax1(){
//..some code
//on ajax success:
ajax2();
}
//etcetera...
Or might I suggest using a javascript library like jQuery to synchronize your ajax requests for you.
set the third parameter in xmlhttp object's open method to false to make it synchronous.
http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
A general pattern for making actions serial would be such:
function doAjax(data, cb) {
...
// when ready call cb
}
(function (next) {
var xhr = doAjax(data, next);
})(function (next) {
var xhr = doAjax(data, next);
})(function (next) {
doAjax(data);
});
Doing so in a for loop would require recursion.
(function next() {
if ( i < n ) {
doAjax(data[i++], next);
}
})();

Categories

Resources