Code after window.open doesn't get executed - javascript

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.

Related

JavaScript function is not triggering

I have html/kendo ui mobile as follows:
<li><a data-action="initContactView" data-click="initContactView">Contacts</a></li>
then javascript:
function initContactView() {
alert('before');
var txtSearch = document.getElementById('searchTextField');
$.ajax({
type: "GET",
data: = "txtSearch='" + txtSearch +"'",
contentType: "application/json; charset=utf-8",
url: "http://xot-wsdl.compx.net/mobile.asmx/ContactGet",
dataType: "json",
success: successContact,
});
alert('after');
}
the function successContact is just putting it all in list view.
My problem is when I take out all the code in JavaScript function the alert works fine, as soon as I put all the other code back, nothing happens when I trigger the button.
What the JavaScript code should do is to connect to my web service and retrieve data.
Any help?
You have a syntax problem on "data: ="
I see you use jQuery, why don't use $("#searchTextField") for
find the field?
txtSearch with getElementById will return a DOM element, non the
value of the field, use this istead:
var txtSearch = $("#searchTextField").val();
EDIT: For debugging you can use FireBug with Mozilla or any other developers tools available in al major browsers.
EDIT 2: In the ajax URL i see a complete URL, please be sure that the url is in the same domain of your web server or you will get a permission denied error.
If you are using Google Chrome you can press Ctrl+Shift+I - Also firefox. Then you can debug your javascript errors by looking for the erros in debug.

Using JavaScript setInterval function

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.

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 can't call plugins after appending Ajax data?

EDIT2: Nevermind, got it working. jQuery was included again in one of the scripts called with ajax. Thanks anyway.
EDIT: This is a rephrased question. Took my a while to find where the problem was.
Calls to plugin functions (including UI effect) aren't working after I load some content with ajax.
The original question had .effect("pulsate",{},1000) call, which explains sarcastyxs answer. Now I'm trying the same thing with the countdown plugin. The same problem appears.
Here is my code. Ignore that it doesn't do much sense, it is stripped down from a larger file. By itself the code is fine. For instance, if I call fadeOut() it works, but if I use .countdown or .effect the mentioned problem appears.
var getOrderDetails= function(id){
var that = this;
$.ajax({
type: "GET",
url: "orderDetails.php",
data: {id: id},
success: function(data){
//$("#orderDetails").html(data);
$("#orderDetails").unbind().click(function(){
var status = $("#orderDetails .orderStatus").text()
acceptOrder(id, status);
});
}
});
}
var acceptOrder = function(id, status){
var that = this;
$.ajax({
type: "GET",
url: "orderStatus.php",
data: {action: 'set', id: id, status: status},
success: function(data){
var nowTime = new Date();
var countdownTime = nowTime.setMinutes(nowTime.getMinutes() + 2);
$("#waitingOrders").countdown({until: countdownTime, compact:true, format: 'MS'});
}
});
}
$(document).ready(function(){
$(".order").unbind().click(function() {
var id = $(this).find(".orderId").text();
getOrderDetails(id);
});
});
When I comment the $("#orderDetails").html(data) line (like in code), the countdown timer appears inside the orderDetails div.
When I uncomment the line, I get an countdown is not a function error. Looked at the dom in firebug, and really in first case I can see that the selector has the .countdown function, and in the second scenario it does not.
What am I missing here?
Someone please help, I have been stuck on this for a few days.
Tried to wrap the ajax success functions with another function and pass it this as context, but it doesn't help. Same thing
You seem to be missing some core functions from jquery-ui. You can download a custom jquery-ui library from the jQuery site.
You basically want to select Effects core and whatever other effect you want to use on the site. The effects core is not part of the default jQuery ui library for some reason.

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