Logging into website with VBScript - javascript

Okay, so here's my problem, there's a webpage on our intranet that I must login to in order to gain access through one of our firewalls. I require this access the entire time I'm working but it automatically logs off every 60 minutes so I have to stop what I'm doing, go back to the page, enter my username & password & log in again. This repeats itself for about 9 hours or until I get off work.
I've been working on a VBScript that I could schedule to run every 60 minutes for me. Currently I'm able to do this via this basic script...
Const strID = "username"
Const strPswd = "password"
Set oShell = CreateObject("WScript.Shell")
oShell.Run("""https://00.0.00.00:0000/php/uid.phpvsys=1&url=http://www.yyy.net%2f""")
WScript.Sleep 3000
oShell.SendKeys strID
oShell.SendKeys "{TAB}"
wScript.Sleep 1000
oShell.SendKeys strPswd
WScript.Sleep 1000
OShell.SendKeys "{TAB}"
OShell.SendKeys "{ENTER}"
WScript.Sleep 1500
Set IE = CreateObject("Shell.Application")
Set windows = IE.Windows()
For Each window In IE.windows
If left(window.LocationUrl, 5) <> "file:" Then
If InStr(window.locationUrl, "http://www.yyy.net/") Then window.Quit()
If UCase(window.locationUrl) = UCase("about:tabs") Then window.Quit()
End If
Next
The above script works of course & I'm currently using it; however, the problem is, if/when the script runs before you're logged out then you receive an error from the script & obviously it won't run again for another hour. This inspired me to dive deeper into scripting. I began searching around for similar topics/methods, examining others codes, etc. just to get some ideas. My first attempt was to accomplish the same thing as the above script except completely hidden & without the use of 'SendKeys'. My goal was to put together a script like this...
Navigate to the page & then check the "heading" string...if it's = 'xxxx' then you're logged out so set the values for the username & password elements & submit them...otherwise, if it's = 'yyyy' then you're still logged in so Sleep for 10sec., reload & check again. I was almost certain this would work but with this script, no matter WHAT I looked for with document.getElementById("zzz"), I ALWAYS get the "null" error. It's as if no elements even exist & I've used every single Name= & ID= I can find in the source. (If interested, I can post this script as well but I ended up moving on to a completely different approach)
After the above issues I started reading about XMLHttp & sending the data this way instead. Using Fiddler I logged into the webpage like normal & was able to find the string with the username+password which get's sent to the server & tried writing a script to accomplish it. This is what I now have...
Call Main
Function Main ()
User = "myusername"
Pass = "mypassword"
'This is the string Fiddler revealed is being sent to server at login...
'"inputStr=&escapeUser=user&user=user&passwd=passwd&ok=Login"
'So I create this string with my information instead of elements values...
Credentials = ("inputStr=&escapeUser=" & User & "&user=" & User & "&passwd=" & Pass & "&ok=Login")
Set objXML = CreateObject("Msxml2.XMLHttp.6.0")
objXML.Open "POST", "https://00.0.00.00:0000/php/uid.php?vsys=1&url=http://www.yyy.net%2f", False
objXML.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
objXML.Send Credentials
End Function
Using the above method, it shouldn't matter if I was or wasn't logged in, the data would still be sent & no errors would be raised. But this script does nothing, it runs, I don't get any errors, I'm still not logged in & Fiddler doesn't even show any requests having been sent or received after I run it. However, if I enter the appropriate information into Fiddler & then execute it, boom, I'm logged in. This is the information I entered & executed & successfully logs me in via Fiddlers Composer under the Parsed tab...
With "POST" selected / The login pages URL / "HTTP/1.1" selected...
Referer: https://00.0.00.00:0000/php/uid.php?vsys=1&url=http://www.yyy.net%2f
Content-Type: application/x-www-form-urlencoded
Host: 00.0.00.00:0000
Content-Length: 68
Then in the "Requested Body" section I input...
inputStr=&escapeUser=myusername&user=myusername&passwd=mypassword&ok=Login
When I hit execute, you can see the request go through & the response come back & when I check on my end I'm logged in.
Hopefully I'm missing something simple that one of you guru's can easily point out or maybe someone has a better approach, I'm open to all ideas & suggestions because after 2 full days, I've gotten no where.
BTW, in case someone is just curious, or it's needed, or whatever, the relevant portion of the source from the login pages is below...
<body onload="loadPage();">
<table id="formtable">
<tr><td>
<div id="activearea">
<div id="logo"><img src="http://xxxxx.xxxx.net/xxx.png" data alt="Logo" width="100"/></div>
<div id="heading">Firewall Access</div>
<div id="desc">Please enter your credentials.</div>
<div id="formdiv">
<script>
function loadPage() {
if (document.login.user.value == '')
document.login.user.focus();
var errMsg = "";
var respStatus = "Success";
var respMsg = "";
if (respStatus == "Error") {
if (errMsg != "")
errMsg += "<br><br>";
errMsg += "<li>"+respMsg;
} else if (respStatus == "Challenge") {
var divUserName = document.getElementById("dUserName");
divUserName.style.display = "none";
var passwdTitle = document.getElementById("passwdTitle");
passwdTitle.innerHTML = "";
var divInputStr = document.getElementById("dInputStr");
divInputStr.style.display = "block";
divInputStr.innerHTML = respMsg;
}
if (errMsg != "") {
var divObj = document.getElementById("dError");
divObj.style.display = "block";
divObj.innerHTML = errMsg;
}
}
function submitClicked() {
var thisForm = document.getElementById("login_form");
// hide the error div, just incase it was showing.
var divObj = document.getElementById("dError");
divObj.style.display = "none";
divObj.innerHTML = "";
var divTaLogin = document.getElementById("taLogin");
divTaLogin.style.display = "none";
thisForm.inputStr.value = "";
thisForm.escapeUser.value = thisForm.user.value.replace(/\\/g, "\\\\");
}
function onClickHandler() {
submitClicked();
}
</script>
<form name="login" id="login_form" method="post">
<input type='hidden' name="inputStr" value="">
<input type='hidden' name="escapeUser" value="">
<div id="taLogin">
<table>
<tr id="dUserName">
<td><span id="userTitle">User</span></td>
<td><input type="text" id="user" name="user" size="19"></td>
</tr>
<tr>
<td><span id="passwdTitle">Password</span></td>
<td>
<div id="dInputStr" style="display:none"><br></div>
<input type="password" maxlength="40" size="19" name="passwd">
</td>
</tr>
<tr>
<td> </td>
<td><input class="buttonFixed" type="submit" id="submit"
name="ok" value="Login" onClick="submitClicked()"></td>
</tr>
</table>
</div>
</form>
<div id="dError" class="msg" style="display:none"></div>
</div>
</div>
</td></tr>
</table>
</body>
</html>

Related

Sending data and saving in a text field

I have a main page with a popup window.
<textarea class="form-control item"></textarea>
<button type="button" class="btn btn-primary" name="name">Send</button>
There is also a second page. (/conclusion/main)
<textarea id="retro" style="height: 200px; width: 800px"></textarea>
I enter the text in the window and send. The window should close and the text should be sent to the second page and the text should be saved in the field "textarea". Even if they close the page or reload, the text should remain in the second page.
This code allows you to save, but after closing the page, does not save
(function(){
var textarea = document.getElementById('retro');
if (localStorage.retro)
{
textarea.value = localStorage.retro;
}
textarea.onchange = function()
{
localStorage.retro = this.value;
}
})();
Sends from the first page to the second
function getParams(){
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx != -1) {
var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
for (var i=0; i<pairs.length; i++){
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params2;
}
params = getParams();
name = unescape(params["name"]);
document.getElementById('retro').innerHTML = name;
There are some questions around what you are trying to do here. What I have done is broken this down into 2 parts
Passing the local storage between 2 pages and accessing it.
Decoding Parameters in the URL and assigning them
Some assumptions that I made:
I have noticed some of the classes from bootstrap so i assume that you have jQuery on the page and also you may know how to use it.
Using chrome for testing this
PART 1 - Passing localstorage between windows:
First thing to note is you may be better using a cookie library (js-cookie) or creating one yourself that you can access. As localstorage may well be insecure depending on what data you want to store in there.
With that out of the way, you were on the right track, just needed to add your event listener to 'input' as i think then every keystroke the data in local storage is being updated.
Page 1
HTML
<textarea id="retro" class="form-control item"></textarea>
<button type="button" class="btn btn-primary" name="name">Send</button>
JS (I would recommend place this at the bottom of you page for quick testing)
<script type="text/javascript">
var textarea = document.getElementById('retro');
textarea.addEventListener('input',function(){
localStorage.setItem('retro', this.value);
})
</script>
In Chrome developer tools if you watch the variable 'localstorage' then you will see this change as you key in the value.
What I have done here is bound the event listener to the text area so that any 'input' the value changes, furthermore is am setting the item in the localstorage
PAGE 2
HTML
<textarea id="retro" style="height: 200px; width: 800px"></textarea>
JS
<script type="text/javascript">
var textarea = document.getElementById('retro').value = localStorage.getItem('retro');
</script>
Here using the 'getItem' method for localstorage you can then retrieve it from the storage area and output it as the value of the textarea.
Obviously is the cache or localstorage is cleared then this value will disappear.
PART 2 - Decoding Parameters in the URL and assigning them
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
}
This function above will get you any parameter you want form the url I found this from here. This is using jQuery.
Here is how you would use it
// example.com?param1=name&param2=&id=6
$.urlParam('param1'); // name
$.urlParam('id'); // 6
$.urlParam('param2'); // null
Well I hope this answers your question on both parts, and helps you further, please add any comments if I have missed anything and I will be happy to update my answer

Can Not Set Value of DOM Element Unless New Value Is Strictly Numeric

DISCLAIMER: total beginner with regards to browser extensions and javascript.
BACKGROUND:
I'm trying to develop a proof-of-concept Chrome extension that picks up the text from the input fields in the HTML form of the web page loaded into one tab, and enters the same text on analogous fields of the page in another tab.
In my particular example, the source page is a minimal, local HTML file with two input fields ("user name" and "password"), and the destination is the login page for Apple's Developer Website (https://developer.apple.com/account/).
Reading the official guides and questions here, I've put together some code that seems to work.
THE PROBLEM:
Only text consisting of digits (e.g.: "111111") gets copied from one tab to the other. As soon as my input field contains letters (e.g.: "111111a"), nothing happens.
This is the source page (local file:///):
<html>
<head>
<title>Source Page</title>
<meta charset="utf-8" />
<script src="popup.js"></script>
</head>
<body>
<form>
<input id="accountname_src" name="appleId" placeholder="Apple ID" /><br />
<input id="accountpassword_src" name="password" placeholder="Password" />
</form>
</body>
</html>
The destination HTML (Apple's page) has similar input fields with element ids of accountname and accountpassword, respectively.
My extension's script is as follows:
document.addEventListener('DOMContentLoaded', function(){
// The button in the browser action popup:
var button = document.getElementById('autofill');
var sourceTabID = null;
var destTabID = null;
// Get the SOURCE tab id:
chrome.tabs.query({'title': 'Source Page'}, function(tabArray){
sourceTabID = tabArray[0].id;
});
// Get the DESTINATION tab id:
chrome.tabs.query({'title': 'Sign in with your Apple ID - Apple Developer'}, function(tabArray){
destTabID = tabArray[0].id;
});
if (button !== null){
button.addEventListener('click', function(){
// Get entered text from Source page:
chrome.tabs.executeScript(sourceTabID, {file: "read_input.js"}, function(results){
var credentials = results[0];
var userName = String(credentials[0]);
var password = String(credentials[1]);
// Pass values to Apple login page:
var insertUserNameCode = "document.getElementById('accountname').value = " + userName + ";"
var insertPasswordCode = "document.getElementById('accountpassword').value = " + password + ";"
var autofillCode = insertUserNameCode + insertPasswordCode;
chrome.tabs.executeScript(destTabID, {code:autofillCode});
});
//window.close();
});
}
});
of course, the contents of read_input.js are:
var userName = document.getElementById("accountname_src").value;
var password = document.getElementById("accountpassword_src").value;
var attributes = [userName, password];
attributes // (Final expression, passed to callback of executeScript() as 'results')
It feels like there could be a type inference problem somewhere, but can't tell where.
Bonus Question:
I can read the input fields in the source page using an external script (read_input.js above) and the method chrome.tabs.executeScript(..., file:...; but when I try to write the values to the destination tab using a similar approach, the script does not run (that is why I'm using chrome.tabs.executeScript(..., code:... in my code). Any idea what can be happening?
Silly me (again)... Some console.logging led me in the right direction...
I was not escaping the value in the script; these lines:
var insertUserNameCode = "document.getElementById('accountname').value = " + userName + ";"
var insertPasswordCode = "document.getElementById('accountpassword').value = " + password + ";"
...should be:
var insertUserNameCode = "document.getElementById('accountname').value = '" + userName + "';"
var insertPasswordCode = "document.getElementById('accountpassword').value = '" + password + "';"
(added single ticks around the values)
...so that the code ends up as:
document.getElementById('accountname').value = '111111a';
...instead of:
document.getElementById('accountname').value = 111111a;
Still not sure why a numbers-only value works, though.

Trying to add promo code functionality to paypal transaction

I've looked everywhere and sifted through the paypal api but my downfall as a developer is when I look at code that isn't my own, I'm looking at a bunch of hieroglyphics that have absolutely no resonance with me. I've been given the task of adding promo code functionality to a site I had no hand in building
I made some progress on my own from looking at an online example so it shouldn't require a bunch of assistance, the live site is http://alphafreakapparel.com/viewcart.php1 . I have an item in the cart and I enter the promo code which is ALPHAPENCE15 and i get just one console error. The code I added is this script in the head of the html doc
<script language = "javascript">
<!--
function validate(text1,text2) {
var text1;
if (text1 == text2)
{
window.alert("15% discount applied!");
data.cart_total.toFixed(2) = data.cart_total.toFixed(2) * 0.15;
}
if (text1 !== text2)
{
window.alert("Incorrect code");
}
}
function CalculateOrder(form) {
if (form.text1.value == "ALPHAPENCE15")
{
form.discount_rate.value = "15";
form.discount_rate2.value = "15";
form.on3.value = "Coupon Entered";
form.os3.value = "ALPHAPENCE15";
}
}
//-->
</script>
and this code to prompt the code
<!-- Start Coupon Validate -->
Enter Promo Code:
<input type="text" name="text1">
<input type="button" value="Check" name="Submit" onclick=javascript&colon;validate(text1.value,"ALPHAPENCE15") >
<!-- End Coupon Validate -->
the error i got was
Uncaught ReferenceError: text1 is not defined viewcart.php:78onclick
What do you think is causing it? I added the var text1; just for that reason.
Also note, I'm not sure if this was the correct way to do this, but to apply the 15% off, I just put *0.15 in the if statement in the head script so that when the if statement completes, it adjusts the total.

Multiple JavaScripts - Both work separately, but if used together second doesn't do anything

I am trying to load 2 scripts (or more) on one page and Only the 1st one is working. I do not have access to edit the javascript so I cannot make changes to it.
Here is the code:
<div style="z-index:0; min-height:600px;">
<script language="javascript" src="http://tickettransaction.com/?bid=1202&sitenumber=0&tid=ticket_results2&evtid=2175269"></script>
<noscript></noscript>
</div>
<div style="z-index:0; min-height:600px;">
<script language="javascript" src="http://tickettransaction.com/?bid=1202&sitenumber=0&tid=ticket_results2&evtid=2175270"></script>
<noscript></noscript>
</div>
When I run the page, the 1st one loads fine but the second one does not. Any help is greatly appreciated.
Jsfiddle links:
Not working: http://jsfiddle.net/6E6ZC/
Working seperately 1: http://jsfiddle.net/5LZ8d/
Working seperately 2: http://jsfiddle.net/SQ778/
DO NOT REMOVE CACHE.
What is happening is that the browser thinks it is being asked to retrieve the same file on each request.
I had the same issue and here is how to resolve it.
Add one more querystring paramater like I have. I added the '&t='+ new Date().getTime()
'/api/drawings?a=e&f=img&id=' + eID + '&t=' + new Date().getTime()
Will work like a champ!
Here is a way to dynamically add the scripts to the page, and this is a FOR SURE WILL WORK WAY.
<script type="text/javascript">
setTimeout(function () {
var script1 = document.createElement('script'),
script2 = document.createElement('script');
script1.setAttribute('type', 'text/javascript');
script1.setAttribute('id', 'script1');
script1.setAttribute('src', 'http://tickettransaction.com/?bid=1202&sitenumber=0&tid=ticket_results2&evtid=2175269&t=' + new Date().getTime());
script1.setAttribute('type', 'text/javascript');
script1.setAttribute('id', 'script2');
script1.setAttribute('src', 'http://tickettransaction.com/?bid=1202&sitenumber=0&tid=ticket_results2&evtid=2175269&t=' + new Date().getTime());
document.getElementsByTagName("head")[0].appendChild(script1);
document.getElementsByTagName("head")[0].appendChild(script2);
},500);
</script>
**With the script above you do not have to add the scripts statically. Just let the script that I've provided run.
This is all assuming that you're not attempting to load two JS files with the same exact script in each file. If your trying to continually check for changes you only need one file and an interval. "setInterval(function(){//this would be something totally different and a lot more work})"
You may have a caching problem. Try setting headers on the JavaScript so that it doesn't allow browser caching.
There is no caching problem and both scripts load correctly with a http 200 status message. When used separately, they produce results but when used together the 2nd one doesn't produce any result.
This could be happening as 2nd script expects something in the page where it can put its contents, but it doesn't find there s it was removed by 1st script. This looks to me as the most probable cause.
Example:
http://jsfiddle.net/6E6ZC/
<div style="z-index:0; min-height:600px;">
<script language="javascript" src="http://tickettransaction.com/?bid=1202&sitenumber=0&tid=ticket_results2&evtid=2175269"></script>
<noscript></noscript>
</div>
<div style="z-index:0; min-height:600px;">
<script language="javascript" src="http://tickettransaction.com/?bid=1202&sitenumber=0&tid=ticket_results2&evtid=2175270"></script>
<noscript></noscript>
</div>
Okay, I feel bound to answer this one after seeing so many wrong turns.
Cache or not is a non-issue. Even if the browser does cache the request (and it most likely will, since the URLs are exactly the same), it all depends on what the loaded code is supposed to do.
Unless the code changes the name of its functions and/or variables on the fly or does other very smart things, including basically the same code a second time will very likely overwrite the first copy, thus doing nothing more than if the file had been included only once.
I would be very surprised if the guys at http://tickettransaction.com did design an interface relying on the user adding some random junk at the tail of the URL to allow a second execution of the very same request result on the same page.
Would they have wanted to support such an usage, they would simply have added a cache-control: no-cache or equivalent directive in their response headers.
But after all, I've seen weirdest things in my programmer's life.
Maybe the guy at tickettransaction.com was badly hungover the day he coded that or something?
To get rid of this cache false problem, simply open your dev tools and watch the network traffic. You will most likely see the request being fetched twice from the cache (or once from the server and once from the cache if you hit Ctrl+F5).
If you really want to have your request fetched twice from the server, simply disable the cache, and make sure you get a full server transfer twice.
Having jumped through all these hoops, you will very likely witness the same result, namely the second response code overwriting the first.
Last update.
Just to get rid of this caching non-issue, I added a variable parameter in the URL.
I used the dev tools to make sure the browser was NOT caching the second request.
Cache being dealt with once and for all, I did have a look at the code of this mysterious script:
document.write('<!--MA-WS-C23-->');
document.write('');
document.write('<script type="text/javascript" src="http://seatics.tickettransaction.com/jquery_tn.js"></' + 'script>');
document.write('');
var TN_ticketResults = null;
function TN_populateTicketData(data) {
TN_ticketResults = data;
if(typeof TN_tryCreateTicketTable == "function")
TN_tryCreateTicketTable();
}
(function() {
var cysct = document.createElement("script");
cysct.type = "text/javascript";
cysct.src= '//tickets.tickettransaction.com/Tickets/ByEvent/?' +
'eventId=2175270&websiteConfigId=669&sort=retail&callback=TN_populateTicketData';
cysct.async = true;
var pnode = document.getElementsByTagName('script')[0];
pnode.parentNode.insertBefore(cysct, pnode);
})();
document.write('');
document.write('<script type="text/javascript" src="http://seatics.tickettransaction.com/swfobject_tn.js"></' + 'script>');
document.write('');
document.write('<script type="text/javascript" src="http://seatics.tickettransaction.com/maincontrol_tnservice_tn.js" ></' + 'script>');
document.write('');
// ppcsrc
var cookie_tn_ppc_src ='';
var tn_cookies = '; '+document.cookie + ';';
var cookie_ppc_src_start =tn_cookies.indexOf('; tn_ppc_src=') + 13;
if(cookie_ppc_src_start != 12)
cookie_tn_ppc_src = '&ppcsrc=' + tn_cookies.substring(cookie_ppc_src_start, tn_cookies.indexOf(';', cookie_ppc_src_start));
var acct_start =tn_cookies.indexOf('; rcaid=') + 8;
if(acct_start != 7)
cookie_tn_ppc_src +='&rcaid=' + tn_cookies.substring(acct_start, tn_cookies.indexOf(';', acct_start));
//map css suppliment
var fileref=document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute('href', 'http://seatics.tickettransaction.com/tnservice_map_suppliment_tn.css');
document.getElementsByTagName('head')[0].appendChild(fileref);
//maps
var webParms = {
swfMapURL : "http://seatics.tickettransaction.com/FenwayPark_Baseball_2013-04-24_2013-04-24_1120_tn.swf",
staticMapURL : "http://seatics.tickettransaction.com/FenwayPark_Baseball_2013-04-24_2013-04-24_1120_tn.gif",
mapShellURL : 'http://seatics.tickettransaction.com/mapshell_tn.swf'
};
webParms.vfsFilterAnimate = 'vertical-list';
webParms.vfsImageAnimate = 'vertical-list';
webParms.vfsEnable = 'selected-hover';
var TN_docFinishedLoading = false;
window.onload = function() {
ssc.EH.buyTickets = function(buyObj) {
var purchaseUrl = 'https://tickettransaction2.com/Checkout.aspx?wcid=669&e=' + escape(buyObj.tgSds) + cookie_tn_ppc_src + '&treq=' + buyObj.buyQty + '&SessionId=' + makeGuid();
if (typeof AppendToPurchaseUrl == "function") {
try {
purchaseUrl = AppendToPurchaseUrl(purchaseUrl);
} catch(e) {
}
}
if (typeof PopupCheckOut == "function" && PopupCheckOut())
window.open(purchaseUrl, '_blank', 'location=no,scrollbars=yes,resizable=yes,menubar=yes,toolbar=yes');
else
location.href = purchaseUrl;
};
TN_docFinishedLoading = true;
TN_tryCreateTicketTable();
};
var TN_onEmptyEvent = TN_onEmptyEvent || function(title) {
$("#tn_loading").css("display", "none");
$("#ssc_listAndMapDiv").css("display", "none");
$("#tn_tblNoResults").css("display", "");
};
function TN_tryCreateTicketTable() {
if (TN_docFinishedLoading && TN_ticketResults) {
if (TN_ticketResults.TicketsAvailable) {
$("#tn_loading").css("display", "none");
ssc.loadTgList(TN_ticketResults.TicketData, webParms);
} else {
TN_onEmptyEvent('Boston+Red+Sox+vs.+Tampa+Bay+Rays+on+Tue%2c+Apr+29+2014');
}
}
}
function makeGuid() {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz';
var guidLength = 5;
var guid = '';
for (var i = 0; i < guidLength; i++) {
var rnum = Math.floor(Math.random() * chars.length);
guid += chars.substring(rnum, rnum + 1);
}
return guid;
}
function GoToOtherGame(eventid) {
if (eventid != '')
document.location = 'ResultsTicket.aspx?evtid=' + eventid;
}
document.write('<table class="tn_results_header"> <tr class="tn_results_header_title"> <td class="tn_results_header_title"> Boston Red Sox vs. Tampa Bay Rays </td> <td class="tn_results_header_venue"> Fenway Park <br /> Boston, MA </td> <td class="tn_results_header_datetime"> Tue, Apr 29 2014 <br /> 7:10 PM </td> </tr> <tr class="tn_results_header_divider"> <td colspan="3" class="tn_results_header_divider"> </td> </tr></table> <div id="tn_loading" style="text-align:center;"><img src="//s3.amazonaws.com/TNService/Images/spinner.gif"/></div><div id="ssc_listAndMapDiv"></div><table style="display: none;" id="tn_tblNoResults" class="tn_results_notfound" cellspacing="0" cellpadding="4"> <tr class="tn_results_notfound"> <td class="tn_results_notfound"> There is currently no online inventory available for this event. <br /> <br /> Please contact <span class=\'tn_results_notfound_name\'> TicketSociety.com</span> at <span class="tn_results_notfound_phone"> (866) 459-9233</span> or <a class="tn_results_notfound_email" href="mailto:CustomerSupport#TicketSociety.com"> CustomerSupport#TicketSociety.com</a> to check availability for this event. </td> </tr> <tr valign="middle" class="tn_results_divider"> <td class="tn_results_divider"> </td>');
document.write(' </tr></table>');
As expected, it does some inline Javascript that actually WORKS twice. You can see it when looking at the 2 lines header before the big table. They indeed appear twice.
You can also inspect the DOM and you will see that your second div is populated with a skeleton table, but the table is never filled.
Unfortunately, the code also defines some variables and functions that are overwritten by the second include. The result is an Ajax request that cannot succeed (basically because the code was not designed to handle the same Ajax request twice on the same page).

User is Typing Notification

I am developing my project on mvc4 , i have an issue with user is typing status notification on my chat module of the project.The problem with this j script is that it is showing the status to same user who is typing but i want that other user to see that i am typing in my text box
var textarea = $('#textarea');
var typingStatus = $('#typing_on');
var lastTypedTime = new Date(0); // it's 01/01/1970
var typingDelayMillis = 5000; // how long user can "think about his spelling" before we show "No one is typing -blank space." message
function refreshTypingStatus() {
if (!textarea.is(':focus') || textarea.val() == '' || new Date().getTime() - lastTypedTime.getTime() > typingDelayMillis) {
typingStatus.html('No one is typing -blank space.');
} else {
typingStatus.html('User is typing...');
}
}
function updateLastTypedTime() {
lastTypedTime = new Date();
}
setInterval(refreshTypingStatus, 100);
textarea.keypress(updateLastTypedTime);
textarea.blur(refreshTypingStatus);
<label>
<textarea name="textarea" id="textarea" cols="45" rows="5"></textarea>
</label>
<div id="typing_on"></div>
If you want users to see a different users typing status, you have to send the current users status to the server via AJAX and retrieve it from the server to display.
So basically, assuming two people are chatting, each client (browser) must:
Get the current users typing status and send to the server
Retrieve the other users typing status from the server and display it.
If you are unsure of how to use AJAX, you should look up jQuery's ajax documentation
Your client side code would have to change like so:
function refreshTypingStatus() {
if (!textarea.is(':focus') || textarea.val() == '' || new Date().getTime() - lastTypedTime.getTime() > typingDelayMillis) {
typingStatus.html('No one is typing -blank space.');
} else {
typingStatus.html('User is typing...');
}
//AJAX call to send typingStatus.html to server
//AJAX call to retrieve other users typingStatus (could be combined into one call)
}
Writing the code necessary is beyond an SO answer as it involves both server side and client side code, but start with this tutorial, and if you have more questions, just ask a new question specific to what you need.

Categories