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.
Related
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!
I have a conceptual issue about scopes on the following code.
The code is a simple client-side validation script for two forms.
I used a self-invoking function to try a something different approach by avoiding to set all global variables but its behavior seems a bit weird to me.
I am still learning to code with JavaScript and I'm not an expert, but these advanced features are a bit complicated.
I don't want to use jQuery but only pure JavaScript in order to learn the basis.
<!-- Forms handling -->
<script src="validate_functions.js"></script>
<script>
(function main() {
var frmPrev = document.getElementById('frmPrev');
var frmCont = document.getElementById('frmCont');
var btnPrev = frmPrev['btnPrev'];
var btnCont = frmCont['btnCont'];
var caller = '';
var forename = '';
var surname = '';
var phone = '';
var email = '';
var privacy = '';
var message = '';
var infoBox = document.getElementById('info-box');
var infoBoxClose = infoBox.getElementsByTagName('div')['btnClose'];
btnPrev.onclick = function(e) {
submit(e);
};
btnCont.onclick = function(e) {
submit(e);
};
function submit(which) {
caller = which.target.name;
var errors = '';
if(caller == 'btnPrev') {
forename = frmPrev['name'].value.trim();
surname = frmPrev['surname'].value.trim();
phone = frmPrev['phone'].value.trim();
email = frmPrev['email'].value.trim();
message = frmPrev['message'].value.trim();
privacy = frmPrev['privacy'].checked;
}
if(caller == 'btnCont') {
phone = frmCont['phone'].value.trim();
email = frmCont['email'].value.trim();
message = frmCont['message'].value.trim();
}
errors = validateFields(caller, forename, surname, phone, email, privacy, message);
if(errors == '') {
var params = 'which=' + caller;
params += '&fname=' + forename;
params += '&sname=' + surname;
params += '&tel=' + phone;
params += '&email=' + email;
params += '&priv=' + privacy;
params += '&mess=' + message;
var request = asyncRequest();
request.open('POST', "send-mail.php", true);
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
request.setRequestHeader('Content-length', params.length);
request.setRequestHeader('Connection', 'close');
request.onreadystatechange = function() {
if(this.readyState == 4) {
if(this.status == 200) {
if(this.responseText != null) {
infoBox.innerHTML = this.responseText;
} else {
infoBox.innerHTML = '<p>No data from server!</p>';
}
} else {
infoBox.innerHTML = '<p>Could not connect to server! (error: ' + this.statusText + ' )</p>';
}
}
}
request.send(params);
} else {
infoBox.innerHTML = errors;
}
infoBox.style.display = 'block';
}
infoBoxClose.onclick = function() {
infoBox.style.display = 'none';
infoBox.innerHTML = '';
};
function validateFields(_caller, _forename, _surname, _phone, _email, _privacy, _message) {
var errs = '';
if(_caller == 'btnPrev') {
errs += validateForename(_forename);
errs += validateSurname(_surname);
errs += validatePhone(_phone);
errs += validateEmail(_email);
errs += validateMessage(_message);
errs += validatePrivacy(_privacy);
}
if(_caller == "btnCont") {
errs += validatePhone(_phone);
errs += validateEmail(_email);
errs += validateMessage(_message);
}
return errs;
}
function asyncRequest() {
var request;
try {
request = new XMLHttpRequest();
}
catch(e1) {
try {
request = new ActiveXObject('Msxml2.XMLHTTP');
}
catch(e2) {
try {
request = new ActiveXObject('Microsoft.XMLHTTP');
}
catch(e3) {
request = null;
}
}
}
return request;
}
})();
Web console keeps telling me that single validate functions are not defined.
Why?
They should be loaded from the external script.. furthermore they should have a global scope.
Thank you in advance :)
Problem solved!
The path to the external script was incorrect.
Sorry for this rubbish! ^^"
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
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()
I have a script i have been battling with now for like a week.
I have a page which has a div with id ("content"). Now I loaded some content, a form contained in a div tag to be specific, into this div VIA Ajax, and it is displaying fine
Now, the challenge is - When the form is submitted, Im am calling a function that will disable all the field on the element in that div tag. I always get the error "undefined".
It seems that the div, that i brought in to the page isn't recognized by javascript..
I have searched google, bing, yahoo..i just havent found the solution yet...
Please, what do I do??
I have included the code below --
+++++++++
The code below for my external javascript file
++++++++++++++++++++
// JavaScript Document
var doc = document;
var tDiv;
var xmlHttp;
var pgTitle;
function getXMLObj(){
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
Obj = new XMLHttpRequest();
}
else if (window.ActiveXObject){
// code for IE6, IE5
Obj = new ActiveXObject("Microsoft.XMLHTTP");
}
else{
alert("Your browser does not support Ajax!");
}
return Obj;
}
function loadCont(toLoad, view){
doc.getElementById('loadBlank').innerHTML = '<div id="loading">Processing Request...</div>';
var url;
switch(toLoad){
case 'CI':
pgTitle = "Administration - Company Information";
url = "comp_info.php?v=" + view + "&sid=" + Math.random();
break;
case 'JB':
pgTitle = "Administration - Jobs";
url = "jobs.php?v=" + view + "&sid=" + Math.random();
break;
case 'US':
pgTitle = "Administration - Users";
url = "users.php?v=" + view + "&sid=" + Math.random();
break;
case 'EP':
pgTitle = "Administration - Employees";
url = "emp.php?v=" + view + "&sid=" + Math.random();
break;
case 'AP':
pgTitle = "Administration - Recruitments";
url = "applicants.php?v=" + view + "&sid=" + Math.random();
break;
case 'JV':
pgTitle = "Administration - Recruitments";
url = "jobvacancy.php?v=" + view + "&sid=" + Math.random();
break;
}
xmlHttp = getXMLObj();
if (xmlHttp !== null && xmlHttp !== undefined){
xmlHttp.onreadystatechange = loadingContent;
xmlHttp.open('GET', url, true);
xmlHttp.send(null);
}
}
function loadingContent(){
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete'){
//Show the loading and the title, but hide the content...
if (xmlHttp.status == 200){
doc.getElementById('dMainContent').innerHTML = parseScript(xmlHttp.responseText);
doc.getElementById('loadBlank').innerHTML = '';
}
else{
doc.getElementById('dMainContent').innerHTML = 'Sorry..Page not available at this time. <br />Please try again later';
doc.getElementById('loadBlank').innerHTML = '';
}
}
if (xmlHttp.readyState < 4){
//Show the loading and the title, but hide the content...
doc.getElementById('ActTitle').innerHTML = pgTitle;
doc.getElementById('dMainContent').innerHTML = '';
}
}
function valCompInfo(){
//First Disable All the elements..
alert('I was hree');
DisEnaAll('CompForm');
//Now..lets validate the entries..
}
function DisEnaAll(contId){
//alert(doc.getElementById(contId).elements);
var theId = doc.getElementById(contId).elements;
try{
var numElems = theId.length;
for (var i=0; i < (numElems - 1); i++){
(theId[i].disabled == false) ? (theId[i].disabled = true) : (theId[i].disabled = false);
}
}
catch(e){
var msg = "The following error occurred: \n\n";
msg += e.description
alert(msg);
}
}
// http://www.webdeveloper.com/forum/showthread.php?t=138830
function parseScript(_source) {
var source = _source;
var scripts = new Array();
// Strip out tags
while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
var s = source.indexOf("<script");
var s_e = source.indexOf(">", s);
var e = source.indexOf("</script", s);
var e_e = source.indexOf(">", e);
// Add to scripts array
scripts.push(source.substring(s_e+1, e));
// Strip from source
source = source.substring(0, s) + source.substring(e_e+1);
}
// Loop through every script collected and eval it
for(var i=0; i<scripts.length; i++) {
try {
eval(scripts[i]);
}
catch(ex) {
// do what you want here when a script fails
}
}
// Return the cleaned source
return source;
}
This code is on the main page where the javascript is
<div id="dMainContent">
</div>
</body>
</html>
And finally, the content of the page i am loading via ajax..
<div style="width:738px" id="CompForm">
<div class="tdright">
<?php echo $btnNm; ?>
</div>
</div>
That's the code..
Thanks
The issue is with div tag (id "CompForm") which is not a HTML form.
"elements" is a collection of the form element not div element. So when trying to access div.elements the property is undefined.
See MSDN, form.elements is part of DOM level 1 (according to MSDN)
http://msdn.microsoft.com/en-us/library/ms537449%28v=VS.85%29.aspx
Add your Javascript functions or external JS file to the original page.
this is not JavaScript....
doc.getElementById(contId).elements
but is used in your JavaScript... you will definitely not get anything. (null)
I don't think this is valid either:
theId[i].disabled == false
EDIT: Note per comments: this is NOT the answer :) See comments for details of why.
Left as an answer simply as a learning aid aid as suggested.
Shouldn't
xmlHttp.onreadystatechange = loadingContent;
be
xmlHttp.onreadystatechange = loadingContent();
or
loadingContent();
and that function should return a value if you want to assign it like that...