Using JavaScript setInterval function - javascript

I found out a lot of questions related to using of JavaScript setInterval() function and found the answers and also implemented them, but my hard luck, none could gain success. I might be doing some silly mistake, but i am not able to find it out now. Following is my code snippet.
$.ajax({
url: "https://api.dropbox.com/1/oauth/request_token",
data:`{"oauth_version":"1.0","oauth_signature_method":"PLAINTEXT","oauth_consumer_key":"consumer_key","oauth_signature":"signature&"}`,
type: 'POST',
async: false,
cache: false,
dataType: 'text',
contentType: "application/x-www-form-urlencoded",
processData: true,
success: function(requestInfo)
{
console.log("requestInfo: "+requestInfo);
requestInfo = "http://localhost/?"+requestInfo;
var oauth_request_token = processQueryStringData(requestInfo, 'oauth_token'); //a regex function that parses oauth_token from requestInfo
var oauth_request_token_secret = processQueryStringData(requestInfo, 'oauth_token_secret');//a regex function that parses oauth_token_secret from requestInfo
console.log("oauth_token_secret: "+oauth_request_token_secret);
console.log("oauth_request_token: "+oauth_request_token);
var url = "<url-to-redirect to dropbox alongwith callback url>";
var win = window.open(url, 'DropBox Auth', 'width=800, height=600');
var pollTimer = window.setInterval(function() {
try {
console.log("URL ===== : " + win.document.URL);
if(**some condition is true**)
{
window.clearInterval(pollTimer);
// some code that i need to execute to get the authorize token and then the access tokens.
}
}
catch(e)
{
}
}, 1000);
});
The ajax returns a success and i get the oauth_request_token and oauth_request_token_secret. Also dropbox log-in page opens in a child window. But the setInterval is not executed since i dont see the console.log("URL ===== : " + win.document.URL); on the console.
Also, after reading a few answers, i created a function named event in which i placed the code from within the setInterval callback function and called that function like,
var pollTimer = window.setInterval(event,1000);
At this time,pollTimer is global.Also, i saw the log statement only once and then the html page was refreshed. I am not able to understand where i am going wrong. Might happen to be a silly mistake, but not able to figure it out. Help please.
Note: This code lies in a function present inside a .js file which is included in a html file.

Here is the thing. When you run function in setInterval, It is totally different context even if you call setInterval in ajax method. So I recommend to you to do check *some condition is true* statement first.

Related

Cant call jQuery POST request from Javascript's addEventListener method

I have a Javascript file that handles a button click on my html page. It works well and detects the button tap, however I can't make the POST request work inside the addEventListener method. I get no errors in the console of my browser, it just simply doesn't work. My question is that what is missing? Based on the POST requests I checked this implementation should work fine.
// my .js file:
(function(){
const btnSignUp = document.getElementById('btnSignUp');
const txtEmail= document.getElementById('txtEmail');
btnSignUp.addEventListener('click', e => {
const email = txtEmail.value;
console.log('test log');
if (email.length < 4) {
$.ajax({
type: "POST",
contentType: "application/json",
url: "/signup/",
data: JSON.stringify({title: email}),
success: function (data) {
console.log(data.title);
},
dataType: "json"
});
}
});
}());
Remove the alert call from your object, that’s a syntax error, thus your snippet will not run because of that.
Also, unsure if this will make a difference but you could either replace the self executing function (IIFE) with jquery onload function, both provide an encapsulated scope... example below
(function () {
//...
})();
Becomes
$(function () {
//...
});
Where
//...
Is your code.
I would also add an error field to your jquery Ajax call, that way you can log any error.
error: function (err) {
console.log(err);
}
That’s about all I can advise, given you have a syntax error in your question.
Become friends with the browser development tools, specifically the console and network tabs, console tab would pick up your syntax error, and network tab will yield the answers you’re looking for, when asking “is the endpoint being hit”, and “what response is the endpoint giving”.
Lastly, I’d add any else statement, after your if, which checks for the length of the email, a simple log will do, could be that you’re fetching the wrong email field, or it isn’t long enough.

Code after window.open doesn't get executed

I recently started learning javascript, and I'm currently trying to make a small script to automate a login procedure by filling the user name/password fields, and then clicking the 'Submit'-button.
My code is as follows:
window.open("");
document.getElementById('ctl00_Username').value = "XXXX";
document.getElementById('ctl00_Password').value="XXXX";
document.getElementById('ctl00_ButtonLogin').click();
If I run it once, the site is opened but no text fields are filled.
If I run the code twice (when the site is already opened) the login is successful.
I tried putting "console.log" after "window.open", but for some reason that never seems to get called.
What might I be doing wrong?
Edit: Removed unnecessary code. I am also no longer sure that the document-object actually points to the newly opened window. Calls to "console.log" and "alert" don't seem to do anything, either.
Is it possible to get the correct document-object from the window?
Is it even possible to use "window.open" and then access the new document-object?
Help would be greatly appreciated!
A reference to the window is returned from the window.open call, you can use it to modify the window.
win=window.open(...);
win.document.doYourThing
You also probably need to wait until the document is ready (aka loaded). Using jquery below
$(win.document).ready(function() {
//the document is loaded by here, this is probably where you should do your stuff.
});
1.Pass your values as query string. Example: www.test.com?username=bro&password=bro.
2.On the other page paste the below code.
$(function () {
$(document).ready(function () {
var amount = $('money').val();
var from = "INR";
var to = "SGD";
$.ajax({ type: "POST",
url: "WebService.asmx/CurrencyConversion",
data: "{amount:" + amount + ",fromCurrency:'" + from + "',toCurrency:'" + to + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var money = $(".money").val();
$(".money").replace(money, data.d);
}
});
});
});
3.Now paste this code too.
var uname = getUrlVars()["username"];
var psw = getUrlVars()["password"];
4.You will be having values in the above variables.Enjoy doing whatever you want.

Get AJAX data from server before document ready (jQuery)

I want take some data from server and write it to global array in JavaScript. Then in document ready I want to use this array to create some new elements (options). I should have global array with this data, because after first load client can modify user interface using this data.
$(document).ready(function () {
UseAjaxQueryForFillGlobalArray();
MakingInterfaceUsingGlobalArray();
});
But I have strange behavior, when I debug page, I can see that method MakingInterfaceUsingGlobalArray working first, and just after I get data via AJAX with method UseAjaxQueryForFillGlobalArray and I don't have new interface(html options) with loaded data.
If I do like this:
UseAjaxQueryForFillGlobalArray();
$(document).ready(function () {
MakingInterfaceUsingGlobalArray();
});
Then in Firefox working fine, but in another web-browsers incorrect in first load (for example go to this page by link). But if I refreshing by F5, I have correct user interface which loaded via AJAX to global JS array.
How to fix it? Maybe I using totally incorrect way?
Added after comments:
This is my ajax function:
function UseAjaxQueryForFillGlobalArray(){
var curUserId = '<%= Master.CurrentUserDetails.Id %>';
var curLocale = '<%= Master.CurrentLocale %>';
$.ajax({
type: "POST",
url: "/segment.aspx/GetArrayForCF",
data: '{"userId":"' + curUserId + '","curLocale":"' + curLocale + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
//here is I doing parse my string from server and fill arrays.
}
});
}
I think that the problem is that you don't know exactly when the first function returns, since it'a asynchronous. So you should use the array in the callback only
function UseAjaxQueryForFillGlobalArray() {
// make the call
$.post(url, data, function() {
// let's be sure that the dom is ready
$(document).ready(function () {
// use the array
MakingInterfaceUsingGlobalArray();
}
}
}();// invoke the function
It's like reviving this post from the dead, but I had the same problem today, jQuery version greater than 1.6 has this ability:
https://api.jquery.com/jquery.holdready/
And I've used it like this:
$.holdReady(true);
var remoteJSONContent = null;
$.getJSON("http://www.example.com/remote.json", function(data) {
remoteJSONContent = data;
$.holdReady(false);
});
$(document).ready(function(){
console.log(remoteJSONContent);
});
Without using holdReady, I was getting null, after, I got the content.
For anyone still searching the answer for this.

jQuery Ajax HTTP Request INTO a click function - not working

My question is:
Is it possible to do an Ajax request WITHIN a click function, with jQuery? (see example below), If so, what am I doing wrong? Because I'm not being able to do any request (I'm alerting the data through my success function and nothing is being retrieved).
Thank you very much in advance for any help! :)
function tracker(){
this.saveEntry = function(elementTracked, elementTrackedType){
var mode = "save";
var dataPost = "mode="+mode+"&elementTracked="+elementTracked+"&elementTrackedType="+elementTrackedType;
$.ajax({
type: "POST",
url: 'myURL',
data:dataPost,
success:function(msg){
alert(msg);
},
beforeSend:function(msg){
$("#trackingStatistics").html("Loading...");
}
});
return;
},
this.stopLinksSaveAndContinue = function(){
var fileName;
$("a[rel^='presentation']").click(function(e){
fileName = $(this).attr("rel").substring(13);
this.saveEntry(fileName,"Presentation");
})
}
}
If your anchor is linked with the href attribute, then this may be interrupting your AJAX request. A similar problem was recently discussed in the following Stack Overflow post:
window.location change fails AJAX call
If you really want to stick to using AJAX for link tracking, you may want to do the following:
Link
With the following JavaScript logic:
function tracker(url) {
$.ajax({
type: 'POST',
url: 'tracker_service.php',
data: 'some_argument=value',
success: function(msg) {
window.location = url;
}
});
}
Have you considered the possiblity that the request might be failing. If so, you're never going to hit the alert.
Can you confirm that the beforeSend callback is being fired?
Also, I'm assuming 'myURL' isn't that in your real-world source code?
There may also be something awry in the }, that closes your function.
Im guessing some sort of error is being generated. Try adding
error:function(a,b){
alert(a);
},
After 'success'

Unexpected JavaScript Actions reported by my Users

My users keep complaining that a link does not show up for them. For me, I have tested this on several browsers and it works for me.
What should happen is that a process is started via AJAX using JQuery and once that is done I keep checking with the server via AJAX how much of the process has been done and once the process is complete I show them a link. But a lot of users tell me that it shows them the link and it quickly disappears back to showing 100.0%!
I can't see how I can fix this and I was hoping you guys could help me write something fool proof so that the link is always shown!
Here is the code concerned (its been shortened).
var startTime;
var continueTime;
var done = false;
function convertNow(validURL){
startTime = setTimeout('getStatus();', 6000);
$.ajax({
type: "GET",
url: "main.php",
data: 'url=' + validURL + '&filename=' + fileNameTxt,
success: function(msg){
done = true;
$("#loading").hide("slow");
$("#done").html("LINK SHOWN HERE");
}//function
});//ajax
}//function convertNow
function getStatus()
{
if(done==false){
$.ajax({
type: "POST",
url: "fileReader.php",
data: 'textFile=' + fileNameTxt,
success: function(respomse){
textFileResponse = respomse.split(" ");
$("#done").html("PROGRESS SHOWN HERE IN PERCENTAGES");
}
});//ajax
continueTime = setTimeout('getStatus();', 3000);
}
}
Thanks all
P.S. I have this question before and was given an idea of using a conditional in the function but that didn't work when it should have!!
UPDATE
I have some of my users what OS and browsers they are using and they usually say a Mac Os and firefox or safari. Not sure if that help with the solution.
The behaviour described by the users suggests that the success callback of your getStatus function is called after the one in convertNow. You should test done variable in this callback
function getStatus(){
if(done==false){
$.ajax({
type: "POST",
url: "fileReader.php",
data: 'textFile=' + fileNameTxt,
success: function(respomse){
// FIX : Already done, just ignore this callback
if (done) return;
textFileResponse = respomse.split(" ");
$("#done").html("PROGRESS SHOWN HERE IN PERCENTAGES");
// BONUS : call getStatus only when previous ajax call is finished
continueTime = setTimeout('getStatus();', 3000);
}
});//ajax
}
}
EDIT : This solution should prevent the bug from appearing most of the time, but there is still a chance. The only way to be sure is to remove the callback from convertNow and let the one in getStatus set the link when the processing is done (don't forget to allow only one call to getStatus at a time, see "BONUS" modification above).
If done is never set back to false then the reported behavior would be expected upon the second call to convertNow.
Since the ajax call in convertNow uses GET instead of POST, it is possible that a browser is returning a cached result whenever parameters are identical to a previous call.

Categories

Resources