Could anyone tell me why this code doesn't work? I can't even get the alert(); in init() to work right...
window.onload = init;
var downloadedstuff;
function init() {
alert();
$.get('example.php' + '?v=' + Math.random(), success: function (data) {
downloadedstuff = data;
});
doTimer();
}
var t;
var timer_is_on=0;
function timedCount()
{
$.get('example.php' + '?v=' + Math.random(), success: function (data) {
if(data != downloadedstuff)
{
alert('SOMETHING HAPPENED!!!!');
location.reload(true);
}
else
{
alert(data);
}
});
t=setTimeout("timedCount()",5000);
}
function doTimer()
{
if (!timer_is_on)
{
timer_is_on=1;
timedCount();
}
}
once again, really sorry for all the questions, i just don't know what's wrong.
This line (which occurs twice):
$.get('example.php' + '?v=' + Math.random(), success: function(data) {
should be:
$.get('example.php' + '?v=' + Math.random(), function(data) {
since the : is for javascript objects
Related
i have a script that reload the page when the value is >= 100 the problem is that location.reload(true); are not working in ie11, i also have tried with window.location = self.location.href; but i am having the same problem, in other browsers it works good.
$(function () {
if (value < 100) {
var timer = setInterval(function () {
$.ajax({
type: "GET",
url: $("#ancUrl").attr('href'),
data: {},
success: function (msg) {
console.log("This is msg:" + msg);
var msgInt = parseInt(msg);
if (msgInt > value)
value = msgInt;
},
error: function (err) {
console.log(err.responseText);
},
dataType: "json"
});
$("#progress-bar").width(value.toString() + "%");
if (value >= 100) {
clearInterval(timer);
window.location = self.location.href;
}
}, 2000);
}
});
You don't appear to have defined self anywhere, so you may have an error there. Beyond that, you're trying to assign the value of href as the whole value of location - which is meant to be an object. Instead, try:
window.location.href = window.location.href;
Try to move the if statement into the success callback.
Like that you can clear the interval into the same stack and reload the page on the good
.
$(function() {
if (value < 100) {
var timer = setInterval(function() {
$.ajax({
type: "GET",
url: $("#ancUrl").attr('href'),
data: {},
success: function(msg) {
console.log("This is msg:" + msg);
var msgInt = parseInt(msg);
if (msgInt > value)
value = msgInt;
$("#progress-bar").width(value.toString() + "%");
if (value >= 100) {
clearInterval(timer);
window.location = self.location.href;
}
},
error: function(err) {
clearInterval(timer);
console.log(err.responseText);
},
dataType: "json"
});
}, 2000);
}
});
place the if in the success function, ajax is asynchronous the if will execute immediately but value will change after the ajax has completed so the code may never reach the if statement
$(function () {
if (value < 100) {
var timer = setInterval(function () {
$.ajax({
type: "GET",
url: $("#ancUrl").attr('href'),
data: {},
success: function (msg) {
console.log("This is msg:" + msg);
var msgInt = parseInt(msg);
if (msgInt > value) {
value = msgInt;
$("#progress-bar").width(value.toString() + "%");
if (value >= 100) {
clearInterval(timer);
location.reload(true);
}
}
},
error: function (err) {
console.log(err.responseText);
},
dataType: "json"
});
}, 2000);
}
});
I am trying to call synchronous call for getting data count using ajax call.
Here is my Jquery Code:
var baseurl = _spPageContextInfo.webServerRelativeUrl;
console.log(baseurl);
var ItemCount = $.Deferred();
function tilesCount(tilename, count)
{
var url = baseurl + "/_api/web/lists/getByTitle('policies')/rootFolder/Folders?$expand=ListItemAllFields";
count = 0;
$.ajax({
url: url,
dataType: 'json',
success: function(data) {
$(data.value).each(function (i, folder) {
count = count + 1;
});
console.log("Call 1: " + count)
ItemCount.resolve(count);
return count;
},
error: function(error){
console.log("Error: " + JSON.stringify(error));
ItemCount.reject;
}
});
}
$(document).ready(function () {
var count = tilesCount("");
$.when(count).then(function(data){
console.log("Call 2: " + data);
});
});
Output:
Call 1: 1
Call 2: undefined
Synchronous call working perfectly, but I am getting data as undefined
Since ajax is asynchronous return count; will be empty
var count = tilesCount("");
So the best solution is to just passed a callback function inside your method which can be call whenever your ajax is completed
function tilesCount(tilename, count, callback)
Wrap this inside your callback function
function(count) {
$.when(count).then(function(data){
console.log("Call 2: " + data);
});
}
so your $(document).ready will be like this and just add parameter count inside the callback
$(document).ready(function () {
tilesCount("", "", function(count) {
$.when(count).then(function(data){
console.log("Call 2: " + data);
});
});
});
your javascript code would be like this now
var baseurl = _spPageContextInfo.webServerRelativeUrl;
console.log(baseurl);
var ItemCount = $.Deferred();
function tilesCount(tilename, count, callback)
{
var url = baseurl + "/_api/web/lists/getByTitle('policies')/rootFolder/Folders?$expand=ListItemAllFields";
count = 0;
$.ajax({
url: url,
dataType: 'json',
success: function(data) {
$(data.value).each(function (i, folder) {
count = count + 1;
});
console.log("Call 1: " + count)
ItemCount.resolve(count);
return callback(count);
},
error: function(error){
console.log("Error: " + JSON.stringify(error));
ItemCount.reject;
}
});
}
$(document).ready(function () {
tilesCount("", "", function(count) {
$.when(count).then(function(data){
console.log("Call 2: " + data);
});
});
});
I've been completing FreeCodeCamp and have given myself the task of fetching an image from the Wikipedia API. I am so close but I am just having trouble with this recursive function.
I'm having some trouble with an ajax request. I want the whole success function to return when obj===label. However, it is only returning one instance of findObjByLabel().
What can I do to make the success function completely return as soon as the label is found?
var wikiUrl = "https://en.wikipedia.org/w/api.php?action=query&format=json&titles=India&prop=pageimages&pithumbsize=300&callback=?";
// this retrieves info about the wikiUrlImg
$.ajax( {
url: wikiUrl,
data: {
format: 'json'
},
dataType: 'json',
type: 'GET',
headers: { 'Api-User-Agent': 'Example/1.0' },
success: function(data) {
console.log("wiki api success");
var findLabel = findObjByLabel(data,"India",1);
function findObjByLabel(obj, label, iterrations){
var itterationLimit = "9";
if (iterrations < itterationLimit){
for(var i in obj){
if(obj === label){
console.log(">>>>>>>>>>>>>>>>>>>>>>> !!!its the label!!! <<<<<<<<<<<<<<<<<<<<<<<<");
// ****************I want the success function to return here! ****************
return "something";
}else{
console.log(">>>>>>>>>>>>>>>>>>>>>>>its not the label<<<<<<<<<<<<<<<<<<<<<<<<");
console.log("i= " + i);
if(obj.hasOwnProperty(i)){
iterrations+=1;
console.log("obj[i] : " + obj[i]);
var foundLabel = findObjByLabel(obj[i], label, iterrations);
}
}
}
}
}//end of findObjByLabel function
}, //end of success
error: function(){
console.log("failure of getWiki api");
}
});
Substitute obj[i] for obj at if condition, use break within if statement, place return statement outside of for loop
var wikiUrl = "https://en.wikipedia.org/w/api.php?action=query&format=json&titles=India&prop=pageimages&pithumbsize=300&callback=?";
// this retrieves info about the wikiUrlImg
$.ajax({
url: wikiUrl,
data: {
format: 'json'
},
dataType: 'json',
type: 'GET',
headers: {
'Api-User-Agent': 'Example/1.0'
},
success: function(data) {
console.log("wiki api success");
var findLabel = findObjByLabel(data, "India", 1);
function findObjByLabel(obj, label, iterrations) {
var itterationLimit = "9";
if (iterrations < itterationLimit) {
for (var i in obj) {
if (obj[i] === label) {
console.log(">>>>>>>>>>>>>>>>>>>>>>> !!!its the label!!! <<<<<<<<<<<<<<<<<<<<<<<<");
// ****************I want the success function to return here! ****************
break; // break `for` loop
} else {
console.log(">>>>>>>>>>>>>>>>>>>>>>>its not the label<<<<<<<<<<<<<<<<<<<<<<<<");
console.log("i= " + i);
if (obj.hasOwnProperty(i)) {
iterrations += 1;
console.log("obj[i] : " + obj[i]);
var foundLabel = findObjByLabel(obj[i], label, iterrations);
}
}
}
}
return "something"; // return `"something"`
} //end of findObjByLabel function
console.log(findLabel); // "something"
}, //end of success
error: function() {
console.log("failure of getWiki api");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have a piece of code that seems to have a problem. I've tried JSLint and other tools to see where I might have a missing delimiter. Eclipse doesn't show me anything either. In Firebug, the complete block of code shows as disabled line numbers like comment lines do. Anyone know of a good tool? I used ctrl+K to indent the code I pasted below.
$(document).ready(function() {
$('.startover').live('click', function() {
var ReInitAnswer = confirm('Are you sure you want TO start over FROM SCRATCH?');
if (ReInitAnswer){
return true;
}
ELSE {
alert('canceled');
return false;
}
});
$('.notdupe').live('click', function(e) {
alert("indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"));
$.ajax({ type: "POST",
url: "cfc/basic.cfc?method=SetNotDupe",
data: "indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"),
error: function (xhr, textStatus, errorThrown){
// show error alert(errorThrown);
}
});
});
$('.alphabet').live('click', function(l) {
SelectedLetter = $(l.target).val();
$(".alphabet").each(function(i){
var CheckLetter = $(this).val();
if (CheckLetter == SelectedLetter){
$(this).css("background-color", "yellow");
$('.NameBeginsWith').val(SelectedLetter);
} ELSE {
$(this).css("background-color", "");
}
});
$('.Reinit').attr('value', SelectedLetter);
$('.Reinit').trigger ('click');
});
$(".alphabet").hover(function () {
var _$this = $(this);
var usercount = 0;
$.ajax({ type: "POST",
url: "scribble.cfc?method=CountUsersByLetter&returnformat=json",
data: "nbw=" + $(this.target).val(),
datatype: "html",
success: function(res){
usercount = eval("(" + res + ")").DATA[0][0];
_$this.append($("<span> (" + usercount +")</span>"));
},
error: function (xhr, textStatus, errorThrown){
console.log('errorThrown');
}
});
},
function () {
$(this).find("span:last").remove();
}
);
});
It's really difficult to tell what you're asking, but if you mean it's formatted wrong, try http://jsbeautifier.org/ for better formatting. Here's that code cleaned up (including the incorrect casing of else):
$(document).ready(function () {
$('.startover').live('click', function() {
var ReInitAnswer = confirm('Are you sure you want TO start over FROM SCRATCH?');
if(ReInitAnswer) {
return true;
} else {
alert('canceled');
return false;
}
});
$('.notdupe').live('click', function(e) {
alert("indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"));
$.ajax({
type: "POST",
url: "cfc/basic.cfc?method=SetNotDupe",
data: "indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"),
error: function (xhr, textStatus, errorThrown) {
// show error alert(errorThrown);
}
});
});
$('.alphabet').live('click', function(l) {
SelectedLetter = $(l.target).val();
$(".alphabet").each(function (i) {
var CheckLetter = $(this).val();
if(CheckLetter == SelectedLetter) {
$(this).css("background-color", "yellow");
$('.NameBeginsWith').val(SelectedLetter);
} else {
$(this).css("background-color", "");
}
});
$('.Reinit').attr('value', SelectedLetter);
$('.Reinit').trigger('click');
});
$(".alphabet").hover(function() {
var _$this = $(this);
var usercount = 0;
$.ajax({
type: "POST",
url: "scribble.cfc?method=CountUsersByLetter&returnformat=json",
data: "nbw=" + $(this.target).val(),
datatype: "html",
success: function(res) {
usercount = eval("(" + res + ")").DATA[0][0];
_$this.append($("<span> (" + usercount + ")</span>"));
},
error: function(xhr, textStatus, errorThrown) {
console.log('errorThrown');
}
});
}, function() {
$(this).find("span:last").remove();
});
});
Javascript is case sensitive.
ELSE must be lowercase.
ELSE must be lowercase
ELSE { // <-- this is bad
alert('canceled');
return false;
}
When I check this code in Firebug, the entire block is disabled.
<script type="text/javascript">
var usercount = 0;
var nbw = '';
$(document).ready(function () {
$('.alphabet').each(function () {
_$this = $(this);
nbw = $(this).val();
$.ajax({
type: "Get",
url: "cfc/basic.cfc?method=CountUsersByLetter&returnformat=json",
data: "nbw=" + nbw,
datatype: "html",
success: function (response) {
usercount = parseInt(response.substring(0, 10));
$(_$this.target).attr('title', usercount);
},
error: function (xhr, textStatus, errorThrown) {
alert('errorThrown');
}
});
});
$('.StartOver').live('click', function () {
var ReInitAnswer = confirm('Are you sure you want TO DELETE ALL temp dupe records AND start over FROM SCRATCH? \nIt may take a couple OF hours.');
if (ReInitAnswer) {
// submit the form TO BEGIN re-creating the temp table
document.forms["dupeIndivs"].submit();
//return true;
} ELSE {
alert('canceled');
return false;
}
});
$('.notdupe').live('click', function (e) {
alert("indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"));
$.ajax({
type: "POST",
url: "cfc/basic.cfc?method=SetNotDupe",
data: "indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"),
error: function (xhr, textStatus, errorThrown) {
// show error alert(errorThrown);
}
});
});
$('.alphabet').live('click', function (l) {
SelectedLetter = $(l.target).val();
$(".alphabet").each(function (i) {
var CheckLetter = $(this).val();
if (CheckLetter == SelectedLetter) {
$(this).css("background-color", "yellow");
$('.NameBeginsWith').val(SelectedLetter);
} ELSE {
$(this).css("background-color", "");
}
});
$('.Reinit').attr('value', SelectedLetter);
$('.Reinit').trigger('click');
});
</script>
You have to replace all uppercase ELSE with else (JavaScript is case-sensitive).
Add the closing brace and parenthesis at the end of the code, to finish the $(document).ready(function(){ block.
Working code:
<script type="text/javascript">
var usercount = 0;
var nbw = '';
$(document).ready(function () {
$('.alphabet').each(function () {
_$this = $(this);
nbw = $(this).val();
$.ajax({
type: "Get",
url: "cfc/basic.cfc?method=CountUsersByLetter&returnformat=json",
data: "nbw=" + nbw,
datatype: "html",
success: function (response) {
usercount = parseInt(response.substring(0, 10));
$(_$this.target).attr('title', usercount);
},
error: function (xhr, textStatus, errorThrown) {
alert('errorThrown');
}
});
});
$('.StartOver').live('click', function () {
var ReInitAnswer = confirm('Are you sure you want TO DELETE ALL temp dupe records AND start over FROM SCRATCH? \nIt may take a couple OF hours.');
if (ReInitAnswer) {
// submit the form TO BEGIN re-creating the temp table
document.forms["dupeIndivs"].submit();
//return true;
} else { // <------------------------------------ ELSE > else
alert('canceled');
return false;
}
});
$('.notdupe').live('click', function (e) {
alert("indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"));
$.ajax({
type: "POST",
url: "cfc/basic.cfc?method=SetNotDupe",
data: "indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"),
error: function (xhr, textStatus, errorThrown) {
// show error alert(errorThrown);
}
});
});
$('.alphabet').live('click', function (l) {
SelectedLetter = $(l.target).val();
$(".alphabet").each(function (i) {
var CheckLetter = $(this).val();
if (CheckLetter == SelectedLetter) {
$(this).css("background-color", "yellow");
$('.NameBeginsWith').val(SelectedLetter);
} else { // <------------------------------------ ELSE > else
$(this).css("background-color", "");
}
});
$('.Reinit').attr('value', SelectedLetter);
$('.Reinit').trigger('click');
});
}); // <---------------------------------------------------- Added });
</script>