2 XMLHTTPRequests in one Javascript (Dynamics CRM) - javascript

I am currently trying to run 2 separate XMLHTTPRequests in dynamics CRM Javascript to retrieve data from 2 different entities and run code depending on what is retrieved..
I've done my best to try and edit some names for security reasons, but the premise is the same.
My main problem is that the first run of the XMLHTTPRequest (the RA Banner) works fine, but then the second run (the Status Banner) the Readystate that is returned is 2 and stopping.
function FormBanners(formContext) {
//Clear the existing banners
formContext.ui.clearFormNotification("Notif1");
formContext.ui.clearFormNotification("Notif2");
//Get the customer/rep
var customer = formContext.getAttribute("customerid").getValue();
var rep = formContext.getAttribute("representative").getValue();
var contact;
//use the rep if there is one else use the customer
if (rep != null) {
contact = rep;
}
else if (customer!= null) {
contact = customer;
}
//Get the account
var account = formContext.getAttribute("accountfield").getValue();
//As there is a requirement for 2 XMLHTTPRequests we have to queue them
var requestURLs = new Array();
//There will always be a customers or rep on the form
requestURLs.push(Xrm.Page.context.getClientUrl() + "/api/data/v9.1/contacts?$select=new_RA,new_SC,new_VC,new_PR&$filter=contactid eq " + contact[0].id + "", true);
//there may not be an account
if (account) {
requestURLs.push(Xrm.Page.context.getClientUrl() + "/api/data/v9.1/accounts?$select=_new_statusLookup_value&$filter=accountid eq " + account[0].id + "", true);
}
var current = 0;
function getURL(url) {
var req = new XMLHttpRequest();
req.open("GET", requestURLs[current]);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var result = JSON.parse(req.response);
// Creation of the RA Banner
if (current == 0) {
var RA = result.value[0]["new_RA#OData.Community.Display.V1.FormattedValue"];
var SC = result.value[0]["new_SC#OData.Community.Display.V1.FormattedValue"];
var VC = result.value[0]["new_VC#OData.Community.Display.V1.FormattedValue"];
var PR = result.value[0]["new_PR#OData.Community.Display.V1.FormattedValue"];
var Notif = "";
//Only create a notification if any of the above contain "Yes"
if (RA == "Yes" || SC == "Yes" || VC == "Yes" || PR == "Yes") { Notif = "The Customer/Rep has:" }
if (RA == "Yes") { Notif = Notif + " RA,"; }
if (SC == "Yes") { Notif = Notif + " SC,"}
if (VC == "Yes") { Notif = Notif + " VC,"}
if (PR == "Yes") { Notif = Notif + " PR."}
if (Notif != "") {
formContext.ui.setFormNotification(Notif, "INFO", "Notif1");
}
}
//Creation of the Status Banner
else if (current == 1) {
status = results.value[i]["_new_statusLookup_value"];
if (status) {
if (status[0].name != "Open")
var Notif = "The status for the organisation on this case is " + status[0].name + ".";
formContext.ui.setFormNotification(Notif, "INFO", "Notif2");
}
}
++current;
if (current < requestURLs.length) {
getURL(requestURLs[current]);
}
} else {
Xrm.Utility.alertDialog(req.statusText);
}
}
}; req.send();
}
getURL(requestURLs[current]);
}
Can anyone help me out?

So in my example I had made many mistakes. Taking Arun's advice I separated the function out, which made debugging far easier.. it instead was not failing on the XMLHTTP Request because that worked fine, but firefox was crashing when debugging.
So my issues were that I was in the second part:
Used the value of i for results (i was no longer defined)
Getting the "_new_statusLookup_value" would only provide the guid of the lookup I would instead want "_new_statusLookup_value#OData.Community.Display.V1.FormattedValue"
Lets not ignore the fact that because I had copied and pasted many iterations of this code that I was also using "results" instead of "result".
Many little mistakes.. but it happens! Thanks for the help, just goes to show.. typos are our downfall!

Related

Entity Type not defined when Customer Field Code is run

I've been working on this code. When I run it and some fields don't exist, the error of Entity Type not defined pops up. I tried If statements but it still isn't working. I've read it may have something to do with the currency but I can't seem to figure out what. I'm a beginner and most of this isn't my code. Help! Thanks.
function customerSelected() {
var customerID = Xrm.Page.getAttribute("customerid").getValue();
var custID = customerID[0].id.substr(1, 36);
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/accounts?$select=_defaultpricelevelid_value,paymenttermscode,shippingmethodcode&$filter=accountid eq " + custID + "&$orderby=name asc", true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
for (var i = 0; i < results.value.length; i++) {
var _defaultpricelevelid_value = results.value[i]["_defaultpricelevelid_value"];
var _defaultpricelevelid_value_formatted = results.value[i]["_defaultpricelevelid_value#OData.Community.Display.V1.FormattedValue"];
var _defaultpricelevelid_value_lookuplogicalname = results.value[i]["_defaultpricelevelid_value#Microsoft.Dynamics.CRM.lookuplogicalname"];
var paymenttermscode = results.value[i]["paymenttermscode"];
var paymenttermscode_formatted = results.value[i]["paymenttermscode#OData.Community.Display.V1.FormattedValue"];
var shippingmethodcode = results.value[i]["shippingmethodcode"];
var shippingmethodcode_formatted = results.value[i]["shippingmethodcode#OData.Community.Display.V1.FormattedValue"];
var _defaultpricelevelid_lookupVal = new Array();
_defaultpricelevelid_lookupVal[0] = new Object();
_defaultpricelevelid_lookupVal[0].id = _defaultpricelevelid_value;
_defaultpricelevelid_lookupVal[0].name = _defaultpricelevelid_value_formatted;
_defaultpricelevelid_lookupVal[0].entityType = _defaultpricelevelid_value_lookuplogicalname;
if ("pricelevelid" != null)
{
Xrm.Page.getAttribute("pricelevelid").setValue(_defaultpricelevelid_lookupVal);
}
if ("paymenttermscode" != null)
{
Xrm.Page.getAttribute("paymenttermscode").setValue(_defaultpricelevelid_lookupVal);
}
if ("shippingmethodcode" != null)
{
Xrm.Page.getAttribute("shippingmethodcode").setValue(_defaultpricelevelid_lookupVal);
}
}
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send();
};
Your query will always return exactly one record, so it does not make sense to use a loop to iterate the results.
Condition ("pricelevelid" != null) will always be true. It probably should be (_defaultpricelevelid_value != null). The same goes for the lines below it.
Your code is assigning _defaultpricelevelid_lookupVal to three separate attributes, which cannot be correct. Apparently this object is supposed to represent a lookup ID value referencing entity pricelevel. Therefore it only makes sense to assign it to attribute pricelevelid. paymenttermscode and shippingmethodcode are option set attributes and apparently need to be filled with the values of the equally named variables.
Replace the for loop with this code:
if (results.value[0]._defaultpricelevelid_value != null) {
var priceLevelId = [{
id = results.value[0]._defaultpricelevelid_value,
name = results.value[0]["_defaultpricelevelid_value#OData.Community.Display.V1.FormattedValue"],
entityType = "pricelevel"
}];
Xrm.Page.getAttribute("pricelevelid").setValue(priceLevelId);
}
if (results.value[0].paymenttermscode != null) {
Xrm.Page.getAttribute("paymenttermscode").setValue(results.value[0].paymenttermscode);
}
if (results.value[0].shippingmethodcode != null) {
Xrm.Page.getAttribute("shippingmethodcode").setValue(results.value[0].shippingmethodcode);
}

Slow ajax for simple DB access

While testing out setInterval(), i had a slow load time for an ajax request. It was very simple and other pages with much more complex requests were terminating in less than a second while this very simple one is terminating after 10-12. Without using setInterval() it is still taking this long and it uses the same layout as the other pages.
Example of script:
document.getElementById("test").innerHTML = "Starting";
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("test").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "/TestLive.cshtml", true);
xmlhttp.send();
Slow server page (ASP.NET):
Response.Expires = -1;
var db = Database.Open("mydb");
string query = "select Name from Game where ID='97';";
Response.Write(db.QuerySingle(query).Name);
Example of fast:
Response.Expires = -1;
string query = "select * from Season where Season.Game = 'Football' and Season.End > '" + DateTime.Now.Add(new TimeSpan(-8,0,0)).ToString("yyyy-MM-dd") + "';";
var db = Database.Open("mydb");
var result = db.Query(query);
Response.Write("<select id=\"chosenSeason\" onchange=\"setDraftSeason()\">");
Response.Write("<option selected=\"selected\">Choose a Season</option>");
foreach (var season in result)
{
Response.Write("<option value=\"" + season.ID + "\">");
Response.Write(season.Name);
Response.Write(" (" + season.Start.ToString("dd-MM-yyyy") + " - " + season.End.ToString("dd-MM-yyyy") + ")");
Response.Write("</option\">");
}
Response.Write("</select>");
EDIT: It seems to be related to using the layout page to access the script. all of the fast pages use the same setup though.

JavaScript: "Syntax error missing } after function body"

Ok, so you know the error, but why on earth am I getting it?
I get no errors at all when this is run locally, but when I uploaded my project I got this annoying syntax error. I've checked the Firebug error console, which doesn't help, because it put all my source on the same line, and I've parsed it through Lint which didn't seem to find the problem either - I just ended up formatting my braces differently in a way that I hate; on the same line as the statement, bleugh.
function ToServer(cmd, data) {
var xmlObj = new XMLHttpRequest();
xmlObj.open('POST', 'handler.php', true);
xmlObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlObj.send(cmd + data);
xmlObj.onreadystatechange = function() {
if(xmlObj.readyState === 4 && xmlObj.status === 200) {
if(cmd == 'cmd=push') {
document.getElementById('pushResponse').innerHTML = xmlObj.responseText;
}
if(cmd == 'cmd=pop') {
document.getElementById('messages').innerHTML += xmlObj.responseText;
}
if(cmd == 'cmd=login') {
if(xmlObj.responseText == 'OK') {
self.location = 'index.php';
}
else {
document.getElementById('response').innerHTML = xmlObj.responseText;
}
}
}
}
}
function Login() {
// Grab username and password for login
var uName = document.getElementById('uNameBox').value;
var pWord = document.getElementById('pWordBox').value;
ToServer('cmd=login', '&uName=' + uName + '&pWord=' + pWord);
}
// Start checking of messages every second
window.onload = function() {
if(getUrlVars()['to'] != null) {
setInterval(GetMessages(), 1000);
}
}
function Chat() {
// Get username from recipient box
var user = document.getElementById('recipient').value;
self.location = 'index.php?to=' + user;
}
function SendMessage() {
// Grab message from text box
var from = readCookie('privateChat');
var to = getUrlVars()['to'];
var msg = document.getElementById('msgBox').value;
ToServer('cmd=push','&from=' + from + '&to=' + to + '&msg=' + msg);
// Reset the input box
document.getElementById('msgBox').value = "";
}
function GetMessages() {
// Grab account hash from auth cookie
var aHash = readCookie('privateChat');
var to = getUrlVars()['to'];
ToServer('cmd=pop','&account=' + aHash + '&to=' + to);
var textArea = document.getElementById('messages');
textArea.scrollTop = textArea.scrollHeight;
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
The problem is your script on your server is in one line, and you have comments in it. The code after // will be considered as comment. That's the reason.
function ToServer(cmd, data) { var xmlObj = new XMLHttpRequest(); xmlObj.open('POST', 'handler.php', true); xmlObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xmlObj.send(cmd + data); xmlObj.onreadystatechange = function() { if(xmlObj.readyState === 4 && xmlObj.status === 200) { if(cmd == 'cmd=push') { document.getElementById('pushResponse').innerHTML = xmlObj.responseText; } if(cmd == 'cmd=pop') { document.getElementById('messages').innerHTML += xmlObj.responseText; } if(cmd == 'cmd=login') { if(xmlObj.responseText == 'OK') { self.location = 'index.php'; } else { document.getElementById('response').innerHTML = xmlObj.responseText; } } } };}function Login() { // Grab username and password for login var uName = document.getElementById('uNameBox').value; var pWord = document.getElementById('pWordBox').value; ToServer('cmd=login', '&uName=' + uName + '&pWord=' + pWord);}// Start checking of messages every secondwindow.onload = function() { if(getUrlVars()['to'] != null) { setInterval(GetMessages(), 1000); }}function Chat() { // Get username from recipient box var user = document.getElementById('recipient').value; self.location = 'index.php?to=' + user;}function SendMessage() { // Grab message from text box var from = readCookie('privateChat'); var to = getUrlVars()['to']; var msg = document.getElementById('msgBox').value; ToServer('cmd=push','&from=' + from + '&to=' + to + '&msg=' + msg); // Reset the input box document.getElementById('msgBox').value = "";}function GetMessages() { // Grab account hash from auth cookie var aHash = readCookie('privateChat'); var to = getUrlVars()['to']; ToServer('cmd=pop','&account=' + aHash + '&to=' + to); var textArea = document.getElementById('messages'); textArea.scrollTop = textArea.scrollHeight;}function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null;}function getUrlVars() { var vars = {}; var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { vars[key] = value; }); return vars;}
You're missing a semi-colon:
function ToServer(cmd, data) {
var xmlObj = new XMLHttpRequest();
xmlObj.open('POST', 'handler.php', true);
xmlObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlObj.send(cmd + data);
xmlObj.onreadystatechange = function() {
if(xmlObj.readyState === 4 && xmlObj.status === 200) {
if(cmd == 'cmd=push') {
document.getElementById('pushResponse').innerHTML = xmlObj.responseText;
}
if(cmd == 'cmd=pop') {
document.getElementById('messages').innerHTML += xmlObj.responseText;
}
if(cmd == 'cmd=login') {
if(xmlObj.responseText == 'OK') {
self.location = 'index.php';
}
else {
document.getElementById('response').innerHTML = xmlObj.responseText;
}
}
}
}; //<-- Love the semi
}
Additional missing semi-colon:
// Start checking of messages every second
window.onload = function() {
if (getUrlVars()['to'] != null) {
setInterval(GetMessages(), 1000);
}
}; //<-- Love this semi too!
I think you can adapt divide and conquer methodology here. Remove last half of your script and see whether the error is coming. If not, remove the first portion and see. This is a technique which I follow when I get an issue like this. Once you find the half with the error then subdivide that half further till you pin point the location of the error.
This will help us to identify the actual point of error.
I do not see any problem with this script.
This may not be the exact solution you want, but it is a way to locate and fix your problem.
It looks like it's being interpreted as being all on one line. See the same results in Fiddler 2.
This problem could do due to your JavaScript code having comments being minified. If so and you want to keep your comments, then try changing your comments - for example, from this:
// Reset the input box
...to...
/* Reset the input box */
Adding a note: very strangely this error was there very randomly, with everything working fine.
Syntax error missing } after function body | At line 0 of index.html
It appears that I use /**/ and //🜛 with some fancy Unicode character in different parts of my scripts for different comments.
This is useful to me, for clarity and for parsing.
But if this Unicode character and probably some others are used on a JavaScript file in comments before any JavaScript execution, the error was spawning randomly.
This might be linked to the fact that JavaScript files aren't UTF-8 before being called and read by the parent page. It is UTF-8 when the DOM is ready. I can't tell.
It seems there should be added another semicolon in the following code too:
// Start checking of messages every second
window.onload = function() {
if(getUrlVars()['to'] != null) {
setInterval(GetMessages(), 1000);
}
}; <---- Semicolon added
Also here in this code, define the var top of the function
function readCookie(name) {
var i;
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
"Hm I think I found a clue... I'm using Notepad++ and have until recently used my cPanel file manager to upload my files. Everything was fine until I used FireZilla FTP client. I'm assuming the FTP client is changing the format or encoding of my JS and PHP files. – "
I believe this was your problem (you probably solved it already). I just tried a different FTP client after running into this stupid bug, and it worked flawlessly. I'm assuming the code I used (which was written by a different developer) also is not closing the comments correctly as well.

Can I focus a dynamically loaded AJAX element?

My scenario is that I have a form on my page. My client would like to be able to fill out the form completely without ever touching the mouse. The problem is that I have a sort of "auto-complete" function that searches our DB (via AJAX) for similar entries, and dynamically loads them into a select element. Then you are able to click the entry that you'd like to have "auto-complete" the form.
To please my client, I am trying to find a way to have that dynamic select element acquire focus once it is loaded, so that the user can press the arrow keys and enter to select what they want, without using the mouse.
After googling for solutions, I have tried adding
document.getElementById('ajaxbox').focus();
into the function called when onreadystatechange is triggered. I have also tried adding that line as a script, and write the script in when the select box is written to the page. Neither of these have worked (either for reasons I can't determine or because I get the error that ajaxbox is null, telling me that it's trying to call the focus() before the box is loaded on the page).
Any ideas? I can provide further information, but not a functioning sample page. Javascript or JQuery solutions are preferred.
EDIT:
Added some code. The URL referenced in the first function is to a java servlet that writes the dynamic html onto the page (via a print writer). I can't really change that currently (due to time constraints). This is all inherited code, so please let me know if there are things that could/should change. I won't be offended.
Here is a portion of the javascript where I was trying to set the focus.
function xmlreqGET(url) {
//alert('ajax');
var xmlhttp=false;
var xmlreq;
try {
if (window.XMLHttpRequest) { // Mozilla, etc.
xmlhttp=new XMLHttpRequest();
xmlreq = new CXMLReq('', xmlhttp);
xmlreqs.push(xmlreq);
urlAr.push(url);
xmlhttp.onreadystatechange = xmlhttpChange;
//alert(url);
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
} else if (window.ActiveXObject) { // IE
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
if (xmlhttp) {
xmlreq = new CXMLReq('', xmlhttp);
xmlreqs.push(xmlreq);
xmlhttp.onreadystatechange = xmlhttpChange;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
}
} catch (e) { }
}
function xmlhttpChange() {
if (typeof(window['xmlreqs']) == "undefined") {
return;
}
try {
if (window.ActiveXObject) { // IE
for (var i=0; i < xmlreqs.length; i++) {
if (xmlreqs[i].xmlhttp.readyState == 4) {
if (xmlreqs[i].xmlhttp.status == 200 || xmlreqs[i].xmlhttp.status == 304) {
// 200 OK
// get response info here before splicing - see below on creating an xml object
var response = xmlreqs[i].xmlhttp.responseText;
//alert(name + ' ' + response);
if (name != "assignCase")
document.getElementById(div_id).style.top = 15;
document.getElementById(div_id).style.left = 50;
if (name == "streetName" || name == "equipName")
document.getElementById(div_id).style.top = 400;
document.getElementById(div_id).style.left = 50;
if (name == "equipment" ) {
document.getElementById(div_id).style.top = 150;
document.getElementById(div_id).style.left = 475;
}
document.getElementById(div_id).innerHTML = response;
xmlreqs.splice(i,1); i--;
urlAr.splice(i,1); i--;
} else {
xmlreqs.splice(i,1); i--;
urlAr.splice(i,1); i--;
}
}
}
} else {
//alert('at else');
for (var i=0; i < xmlreqs.length; i++) {
//alert(i + ':' + name + ':' + xmlreqs.length);
if (xmlreqs[i].xmlhttp.readyState == 4) {
if (xmlreqs[i].xmlhttp.status == 200 || xmlreqs[i].xmlhttp.status == 304) {
// 200 OK
// get response info here before splicing - see below on creating an xml object
// alert('200 was here' + name);
var response = xmlreqs[i].xmlhttp.responseText;
var len = response.length;
if (name == "streetName" || name == "equipName" || name == "city" || name == "zip" || name == "grid") {
document.getElementById(div_id).style.top = 270;
document.getElementById(div_id).style.left = 50;
} else if (name == "upstream"){
document.getElementById(div_id).style.left = 600;
document.getElementById(div_id).style.top = 150;
} else if (name == "equipment" ) {
document.getElementById(div_id).style.top = 125;
document.getElementById(div_id).style.left = 500;
} else if (name == "pingMeter"){
document.getElementById(div_id).style.left = 1025;
document.getElementById(div_id).style.top = 210;
} else if (name == "assignCase") {
//document.getElementById(div_id).style.top = 60;
//document.getElementById(div_id).style.left = 120;
} else {
document.getElementById(div_id).style.top = 400;
document.getElementById(div_id).style.left = 50;
}
document.getElementById(div_id).innerHTML = response;
if (response == "") {
// xmlreqGET(urlAr[i]);
xmlreqs.splice(i,1); i--;
urlAr.splice(i,1); i--;
} else {
//document.getElementById(div_id).innerHTML = response;
xmlreqs.splice(i,1); i--;
urlAr.splice(i,1); i--;
}
}
}
if (xmlreqs[i].xmlhttp.readyState < 4) {
// confirm('at nloading');
document.getElementById(div_id).style.top = 270;
document.getElementById(div_id).style.left = 50;
document.getElementById(div_id).innerHTML = "<div align=center class='fixedwidth' style='background-color:#ffff8f'> <br> <img src='omscontrol/common/images/loading.gif' width='20'><Font size=1> Loading Content....Please Wait! </Font><br> </div>";
}
}
}
alert(document.getElementById('firstOption'));
document.getElementById('firstOption').focus();
} catch (e) { }
}
Example from the servlet as to how the HTML is being written. This isn't really something I want to get into changing at this time.
comboOption = new StringBuffer();
/* Version 1.0.2 */
comboOption.append("<select id=\"" + id + "\" class='fixedwidth' style=\'background-color:#ffff8f\' size='4' "
+ "onchange=\"popVal(this.options[this.selectedIndex].value); populateValues('" + id + "');\">");
comboOption.append("<option value=''>" + "No Matches Found!" + "</option>");
/* Version 1.0.2 */
comboOption.append("</select>");
out.print(comboOption.toString());
I had tried adding the focus() to a script, and putting it into that last append. I'm not sure if that is even something that could work, but it didn't for me.
EDIT 2:
I added document.getElementById('firstOption').focus(); to the very end of the two readyState == 4 if conditions. I can tell that the element does exist at that time, but my focus actually ends on nothing. (I found that out by adding
$(document.activeElement).change(function(){
alert("NEWFOCUS: " + document.activeElement.id);
});
to my JSP. If that isn't reliable, please tell me.)
you have to append the input element first to the DOM before you call the focus function
var div = document.getElementById("dynamic");
$.ajax({
...
success:function (data) {
// append the new created input to the DOM
....
div.appendChild(newInput);
newInput.focus();
}
});
You are probably trying to access ajaxbox before it is present in the DOM that's why you are getting a null

Content Insensitive Autosave via XMLHttpRequest

I am trying to make an autosave that can be dropped into any of my forms and be "self aware" of the content in order to simulate an actual save. In addition, I want it to be able to notify the user in the event of multiple failures of the autosave. The following is the come I have come up with, but I keep getting readyState = 4 and status = 500 as a result of my XMLHttpRequest.send(). When I "normally" click save with the form, the save works perfectly fine, but this code just doesn't seem to pass the data over correctly. Every page that has this code has a setTimeout(autosave,5000) to initialize the code. Can someone point me in the right direction of what I'm doing wrong? I'm new to XMLHttpRequest objects.
For what I can tell, last_params gets "sent" with the correct data, but when I get it via the request() (using classic ASP on the other end), the value is "" (blank). I'm thinking I have an order of execution problem, I just don't know what or where.
Quick footnote: I know that there are 'similar' functions with jQuery and other frameworks, but I do not feel comfortable enough with them yet. I want to start with something "simple".
var last_params = "";
var autosave_time = 61000;
var autosave_fail_check = 5;
var max_autosave_fail_check = 5;
var response_text = "";
function autosave() {
var autosave_button_name = "save_button";
var form_action = document.getElementById("formS").action;
var form_data = document.getElementById("formS");
var all_inputs = form_data.getElementsByTagName("input");
var all_textareas = form_data.getElementsByTagName("textarea");
var params = "";
// Check all inputs for data
for (var i = 0; i < all_inputs.length; i++) {
var current_item = all_inputs[i];
if (current_item.type != "button" && current_item.type != "submit") {
if (current_item.type != "checkbox") {
params += current_item.name + "=" + current_item.value + "&";
} else {
params += current_item.name + "=" + current_item.checked + "&";
}
}
}
// check all textareas for data
for (var i = 0; i < all_textareas.length; i++) {
var current_item = all_textareas[i];
params += current_item.name + "=" + current_item.value + "&";
}
params += "autosave=1";
if (params == last_params) {
setTimeout(autosave, autosave_time);
return;
} else {
last_params = params;
}
// Setup time
var time = "";
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
if (minutes < 10) {
minutes = "0" + minutes;
}
time = hours + ":" + minutes + ":" + seconds;
if(hours > 11){
time = time + "PM";
} else {
time = time + "AM";
}
var status = "[]";
// **************************************************
var http;
try {
// Gecko-based browsers, Safari, and Opera.
http = new XMLHttpRequest();
} catch(e) {
try {
// For Internet Explorer.
http = new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
// Browser supports Javascript but not XMLHttpRequest.
document.getElementById(autosave_button_name).value = "Autosave NOT Available";
http = false;
}
}
http.onreadystatechange = function()
{
if (http.readyState == 4 && http.status == 200) {
autosave_fail_check = max_autosave_fail_check; // reset the fail check
}
status = " [" + http.readyState + " / " + http.status + "] ";
}
if (autosave_fail_check <= 0) {
if (autosave_fail_check == 0) {
document.getElementById(autosave_button_name).value = "Autosave FAILURE; Check Connection!";
//alert("Autosave has FAILED! Please check your connection!");
}
autosave_fail_check = -1;
} else {
autosave_fail_check--;
}
var url = form_action;
http.open("POST", url, true); // async set to false to prevent moving on without saving
http.setRequestHeader("Content-type", "multipart/form-data");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.send(last_params);
response_text = http.responseText;
if (autosave_fail_check >= 0) {
document.getElementById(autosave_button_name).value = "Last Saved: " + time + " [" + autosave_fail_check + "] " + status;
} else {
autosave_fail_check = -1;
}
setTimeout(autosave, autosave_time);
} // end function autosave()

Categories