What I have is a collection. By default the whole collection is shown on the page in a table. The user can then narrow down the results by entering in filter data in 1 or multiple textboxes.
So I have spent the last several hours trying to make this work reactively but failing miserably. The helper is below:
Template.localBoardTemplate.helpers({
localDelivery: function (){
return localBoardColl.find(query);
}
});
Now I have keyup events on the individual textboxes that all trigger the same function to dynamically build the query:
function loadBoardRecords(){
var query = {};
if($('input:text[name=localBoardTripNumSetting]').val() != ""){
query['tripNumber'] = {$regex: new RegExp('^' + $('input:text[name=localBoardTripNumSetting]').val(), 'i')};
}
if($('input:text[name=localBoardLoadNumSetting]').val() != ""){
query['orderLoadNum'] = {$regex: new RegExp('^' + $('input:text[name=localBoardLoadNumSetting]').val(), 'i')};
}
if($('input:text[name=localBoardEquipmentSetting]').val() != ""){
query['equipmentTypeName'] = {$regex: new RegExp('^' + $('input:text[name=localBoardEquipmentSetting]').val(), 'i')};
}
if($('input:text[name=localBoardCustomerSetting]').val() != ""){
query['Customer'] = {$regex: new RegExp('^' + $('input:text[name=localBoardCustomerSetting]').val(), 'i')};
}
if($('input:text[name=localBoardTrailerNumSetting]').val() != ""){
query['trailerNum'] = {$regex: new RegExp('^' + $('input:text[name=localBoardTrailerNumSetting]').val(), 'i')};
}
if($('input:text[name=localBoardPUCitySetting]').val() != ""){
query['puCity'] = {$regex: new RegExp('^' + $('input:text[name=localBoardPUCitySetting]').val(), 'i')};
}
if($('input:text[name=localBoardPUStateSetting]').val() != ""){
query['puState'] = {$regex: new RegExp('^' + $('input:text[name=localBoardPUStateSetting]').val(), 'i')};
}
if($('#localBoardPUDateSetting').val() != ""){
puDate = moment($('#localBoardPUDateSetting').val(), "MM-DD-YYYY").toDate();
query['puDate'] = puDate;
}
if($('input:text[name=localBoardDELCitySetting]').val() != ""){
query['delCity'] = {$regex: new RegExp('^' + $('input:text[name=localBoardDELCitySetting]').val(), 'i')};
}
if($('input:text[name=localBoardDELStateSetting]').val() != ""){
query['delState'] = {$regex: new RegExp('^' + $('input:text[name=localBoardDELStateSetting]').val(), 'i')};
}
if($('#localBoardDELDateSetting').val() != ""){
delDate = moment($('#localBoardDELDateSetting').val(), "MM-DD-YYYY").toDate();
query['delDate'] = delDate;
}
}
Now I have tried using a session variable to hold the query this failed because you can't have nested objects in the session variables. I then tried a package called ReactiveObj and that I couldn't get working either. Heck I even tried a ReactiveArr but that isn't reactive unless you .list it and that doesn't work for the query in the find.
This can't be this hard of a problem and I have probably overlooked something minor. I am hoping someone can point me to the write package or solution for this problem.
A quick-n-dirty code with ReactiveVar
var buildQuery = function(formId) {
// put the code in the loadBoardRecords with the form id
// and return the query
return query;
}
Template.layout.helpers({
localDelivery: function (){
return Template.instance()['resultSet'].get();
}
});
Template.layout.events({
'click .searchButton': function() {
var formId = $(...); // get the id for the form
var cursor = localBoardColl.find(search(formId));
Template.instance()['resultSet'].set(cursor);
}
});
Template.layout.created = function () {
this['resultSet'] = new ReactiecVar(null);
}
Actually you CAN store nested objects in Session variable.
On helpers:
Template.localBoardTemplate.helpers({
localDelivery: function (){
var query = Session.get('QUERY') || {};
return localBoardColl.find(query);
}
});
On events:
function loadBoardRecords(){
var query = Session.get('QUERY') || {};
if($('input:text[name=localBoardTripNumSetting]').val() != ""){
query['tripNumber'] = {$regex: new RegExp('^' + $('input:text[name=localBoardTripNumSetting]').val(), 'i')};
}
.
.
.
.
.
if($('#localBoardDELDateSetting').val() != ""){
delDate = moment($('#localBoardDELDateSetting').val(), "MM-DD-YYYY").toDate();
query['delDate'] = delDate;
}
Session.set('QUERY',query);
}
That is totally possible.
I have solved this through a few bit more trial and error and the help of Thai Trans answer. I used a reativevar variable to store an object. The correct code is as follows:
Helper:
Template.localBoardTemplate.helpers({
localDelivery: function (){
return localBoardColl.find(Template.instance().searchQuery.get());
}
});
The function that creates the query and stores it in the reacvtive-var:
function loadBoardRecords(template){
var query = {};
if($('input:text[name=localBoardTripNumSetting]').val() != ""){
query['tripNumber'] = {$regex: new RegExp('^' + $('input:text[name=localBoardTripNumSetting]').val(), 'i')};
}
if($('input:text[name=localBoardPUStateSetting]').val() != ""){
query['puState'] = {$regex: new RegExp('^' + $('input:text[name=localBoardPUStateSetting]').val(), 'i')};
}
if($('#localBoardPUDateSetting').val() != ""){
puDate = moment($('#localBoardPUDateSetting').val(), "MM-DD-YYYY").toDate();
query['puDate'] = puDate;
}
if($('input:text[name=localBoardDELCitySetting]').val() != ""){
query['delCity'] = {$regex: new RegExp('^' + $('input:text[name=localBoardDELCitySetting]').val(), 'i')};
}
if($('input:text[name=localBoardDELStateSetting]').val() != ""){
query['delState'] = {$regex: new RegExp('^' + $('input:text[name=localBoardDELStateSetting]').val(), 'i')};
}
if($('#localBoardDELDateSetting').val() != ""){
delDate = moment($('#localBoardDELDateSetting').val(), "MM-DD-YYYY").toDate();
query['delDate'] = delDate;
}
template.searchQuery.set( query );
}
This works perfectly. It also still allows for the reactive collection updates even during a users search.
Related
What i want to do is when we click on Reply button , the From address field will be populate with the email-id (default team's default queue's email-id). Current scenario is populated with logged in user.
I used the following js code onLoad, but I am getting an error that says "Object doesn't support property or method getAttributeValue
function CheckEnquiryReplyAddress() {
// Only complete this validate on Create Form
var formType = Xrm.Page.ui.getFormType();
var emailStatus = Xrm.Page.getAttributeValue("statecode").getValue();
var emailDirection = Xrm.Page.getAttributeValue("directioncode").getValue();
if (formType == 1 || (formType == 2 && emailStatus == "Open")) {
if (emailDirection == "1"){
var previousEmailId=getExtraqsParam("_InReplyToId", window.parent.location.search);
//getting context from the parent window
var context = Xrm.Page.context;
try {
var serverUrl = context.getServerUrl();
//The XRM OData end-point
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var query="/EmailSet?$select=ActivityId,ActivityTypeCode,DirectionCode,";
query=query+"ToRecipients,Email_QueueItem/QueueId&$expand=Email_QueueItem&$filter=ActivityId eq guid'" + previousEmailId +"'";
query =serverUrl+ODATA_ENDPOINT+ query;
var request= new XMLHttpRequest();
request.open("GET", query, false);
request.setRequestHeader("Accept", "application/json");
request.setRequestHeader("Content-Type", "application/json; charset=utf-8");
request.onreadystatechange=function(){ CompleteEnquiryReplyCheck(request,serverUrl);}
request.send(null);
}
catch(e) {
alert(e.Description);
}
}
}
}
function CompleteEnquiryReplyCheck(request,url)
{
if (request.readyState==4) {
if(request.status==200) {
var queue=JSON.parse(request.responseText).d.results[0];
if (queue != null) {
var queueId = queue.Email_QueueItem.results[0].QueueId.Id;
var lookup = new Array();
var lookupItem = new Object();
lookupItem.id = queueId;
lookupItem.name = queue.Email_QueueItem.results[0].QueueId.Name;
lookupItem.typename = "queue";
lookup[0] = lookupItem;
Xrm.Page.getAttribute("from").setValue(lookup);
}
}
}
}
The get attribute value method is incorrect, to get value of an attribute use the following:
var attributeValue = Xrm.Page.getAttribute("attributeName").getValue();
So, in your case it would be:
var emailStatus = Xrm.Page.getAttribute("statecode").getValue();
var emailDirection = Xrm.Page.getAttribute("directioncode").getValue();
I want to check if fileExtis in avoidExt and use it in a if...else statement.
var thisFile=$(this).val(); //returns "file.jpg"
var fileExt = thisFile.replace(/^.*\./, ''); //return "jpg"
var avoidExt= new RegExp(/(\.|\/)(bat|exe|cmd|sh|php|pl|cgi|386|dll|com|torrent|js|app|jar|pif|vb|vbscript|wsf|asp|cer|csr|jsp|drv|sys|ade|adp|bas|chm|cpl|crt|csh|fxp|hlp|hta|inf|ins|isp|jse|htaccess|htpasswd|ksh|lnk|mdb|mde|mdt|mdw|msc|msi|msp|mst|ops|pcd|prg|reg|scr|sct|shb|shs|url|vbe|vbs|wsc|wsf|wsh)$/i);
Maybe this will help
var thisFile = $(this).val();
// var fileExt = thisFile.replace(/^.*\./, ''); doesn't need this line
var avoidExt= new RegExp(/(\.|\/)(bat|exe|cmd|sh|php|pl|cgi|386|dll|com|torrent|js|app|jar|pif|vb|vbscript|wsf|asp|cer|csr|jsp|drv|sys|ade|adp|bas|chm|cpl|crt|csh|fxp|hlp|hta|inf|ins|isp|jse|htaccess|htpasswd|ksh|lnk|mdb|mde|mdt|mdw|msc|msi|msp|mst|ops|pcd|prg|reg|scr|sct|shb|shs|url|vbe|vbs|wsc|wsf|wsh)$/i);
if(avoidExt.test(thisFile)){
// exist
}else{
// doesn't exist
}
Check this
var thisFile=$(this).val();
var fileExt = thisFile.replace(/^.*\./, '');
var avoidExt= new RegExp(/(\.|\/)(bat|exe|cmd|sh|php|pl|cgi|386|dll|com|torrent|js|app|jar|pif|vb|vbscript|wsf|asp|cer|csr|jsp|drv|sys|ade|adp|bas|chm|cpl|crt|csh|fxp|hlp|hta|inf|ins|isp|jse|htaccess|htpasswd|ksh|lnk|mdb|mde|mdt|mdw|msc|msi|msp|mst|ops|pcd|prg|reg|scr|sct|shb|shs|url|vbe|vbs|wsc|wsf|wsh)$/i);
if(fileExt.test(avoidExt)){
console.log("EXIST");
}else{
console.log("NOT EXIST");
}
Is not necessary to create a RegExp object, you can use a regexp literal:
var fileExt = $(this).val().replace(/^.*\./, '');
var avoidExt = /(bat|exe|cmd|sh|php|pl|cgi|386|dll|com|torrent|js|app|jar|pif|vb|vbscript|wsf|asp|cer|csr|jsp|drv|sys|ade|adp|bas|chm|cpl|crt|csh|fxp|hlp|hta|inf|ins|isp|jse|htaccess|htpasswd|ksh|lnk|mdb|mde|mdt|mdw|msc|msi|msp|mst|ops|pcd|prg|reg|scr|sct|shb|shs|url|vbe|vbs|wsc|wsf|wsh)/i;
if(fileExt.text(avoidExt)){
// exist
} else {
// doesn't exist
}
You can use RegExp.prototype.test()
var thisFile = "file.jpg";
var fileExt = thisFile.replace(/^.*\./, ''); //return "jpg"
var avoidExt = new RegExp(/(\.|\/)(bat|exe|cmd|sh|php|pl|cgi|386|dll|com|torrent|js|app|jar|pif|vb|vbscript|wsf|asp|cer|csr|jsp|drv|sys|ade|adp|bas|chm|cpl|crt|csh|fxp|hlp|hta|inf|ins|isp|jse|htaccess|htpasswd|ksh|lnk|mdb|mde|mdt|mdw|msc|msi|msp|mst|ops|pcd|prg|reg|scr|sct|shb|shs|url|vbe|vbs|wsc|wsf|wsh)$/i);
console.log(avoidExt.test('.' + fileExt) ? 'fileExt is in' : 'fileExt is not in');
UPDATE : IF...ELSE format
var thisFile = "file.jpg";
var fileExt = thisFile.replace(/^.*\./, ''); //return "jpg"
var avoidExt = new RegExp(/(\.|\/)(bat|exe|cmd|sh|php|pl|cgi|386|dll|com|torrent|js|app|jar|pif|vb|vbscript|wsf|asp|cer|csr|jsp|drv|sys|ade|adp|bas|chm|cpl|crt|csh|fxp|hlp|hta|inf|ins|isp|jse|htaccess|htpasswd|ksh|lnk|mdb|mde|mdt|mdw|msc|msi|msp|mst|ops|pcd|prg|reg|scr|sct|shb|shs|url|vbe|vbs|wsc|wsf|wsh)$/i);
if (avoidExt.test('.' + fileExt))
console.log('fileExt is in')
else
console.log('fileExt is not in');
Or there is no need to extract the extension using regex you can do the following
var thisFile = "file.jpg";
var avoidExt = new RegExp(/(\.|\/)(bat|exe|cmd|sh|php|pl|cgi|386|dll|com|torrent|js|app|jar|pif|vb|vbscript|wsf|asp|cer|csr|jsp|drv|sys|ade|adp|bas|chm|cpl|crt|csh|fxp|hlp|hta|inf|ins|isp|jse|htaccess|htpasswd|ksh|lnk|mdb|mde|mdt|mdw|msc|msi|msp|mst|ops|pcd|prg|reg|scr|sct|shb|shs|url|vbe|vbs|wsc|wsf|wsh)$/i);
console.log(avoidExt.test(thisFile) ? 'fileExt is in' : 'fileExt is not in');
Until very recently we'd been using RU 11 within our Dynamics CRM 2011 application but have recently begun a project to eventually move to CRM 2015. We've upgraded to RU 12 and this is where things get fun!
I've managed to sort out a lot of the coding issues that were previously present but cannot for the life of me solve our issue of accessing an external web service, passing parameters along the way and retrieving data back.
At first I had trouble with the "CreateXmlHttp()" function but found a great answer online indicating that the following function would help:
function CreateXmlHttp()
{
var ref = null;
if (window.XMLHttpRequest) {
ref = new XMLHttpRequest();
} else if (window.ActiveXObject) { // Older IE
ref = new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
return ref;
}
This worked fine and as expected, it would have appeared that I could now connect to the service.
However, I am not retrieving any data and this is the issue that is tying me up in knots.
As background, the following is my code to declare a few integer variables before POSTING the xml through to the webservice.
parseInt(lngLicensNr);
parseInt(lngNrOfUsers);
parseInt(lngAnnualWorkingTime);
parseInt(lngIncludedHours);
parseInt(productType);
if (licenceType == 100000000) {
var licenseType = "ltUnlimitedMode";
lngIncludedHours = 1000000;
}
if (licenceType == 100000001) {
var licenseType = "ltHourlyMode";
}
if (lngLicensNr != null && lngNrOfUsers != null && lngAnnualWorkingTime != null && lngIncludedHours != null && productType != null && licenseType != null) {
var errMsg = "";
var errCount = 0;
var xml = "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
xml += "<soap:Body>";
xml += "<GetBaseInstallationKey xmlns=\"http://www.keyservice.com/\">";
xml += "<licensNr>" + lngLicensNr + "</licensNr>";
xml += "<nrOfUsers>" + lngNrOfUsers + "</nrOfUsers>";
xml += "<annualWorkingTime>" + lngAnnualWorkingTime + "</annualWorkingTime>";
xml += "<includedHours>" + lngIncludedHours + "</includedHours>";
xml += "<productType>" + baseProduct + "</productType>";
xml += "<licenseType>" + licenseType + "</licenseType>";
xml += "</GetBaseInstallationKey>";
xml += "</soap:Body>";
xml += "</soap:Envelope>";
try {
Request = CreateXmlHttp();
} catch (ex) {
alert("An error occured while accessing the webservice.\n\n1. " + ex.name + " \n " + ex.message + "\n\n");
errCount = 1;
}
if (errCount == 0) {
try {
Request.open("POST", "http://web01:8080/KeyWebService/KeyWebService.asmx", false);
} catch (ex) {
alert("An error occured while accessing the webservice.\n\n2. " + ex.name + " \n " + ex.message + "\n\n");
errCount = 1;
}
}
if (errCount == 0) {
try {
Request.setRequestHeader("SOAPAction", "http://www.keyservice.com/GetKey");
Request.setRequestHeader("Host", "web01:8080");
Request.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
Request.setRequestHeader("Content-Length", xml.length);
Request.send(xml);
var xmlDoc = Request.responseXML;
} catch (ex) {
alert("An error occured while accessing the webservice.\n\n3. " + ex.name + " \n " + ex.message + "\n\n");
errCount = 1;
}
}
if (errCount == 0 || Request.responseXML != null) {
baseKey = Request.responseXML.text;
} else {
baseKey = "No key generated";
}
}
if (lngLicensNr == null || lngNrOfUsers == null || lngAnnualWorkingTime == null || lngIncludedHours == null || productType == null || licenseType == null) {
alert('Not all parameters have been entered - it is not possible to generate a key without all parameters');
}
Prior to RU 12, the code worked absolutely fine and the last variable "baseKey" was retrieved from the web service.
However, the whole process works perfectly fine now in that it seems to connect ok but just does not retrieve a "baseKey" from the service.
I believe that the issue may be related to deprecated end points or schemas or even just deprecated code that returns and displays the value (i.e. var xmlDoc = Request.responseXML;) but I'm not sure where to resolve.
If anyone has any ideas or can point me in the right direction it would be a big help.
we had similar requirement to call an external Web-service to retrieve the latest contract of a contact and show it on Contact Form.
We had our own definition of latest contract that was implement in a webserivce. So i have to call that webservice on Contact Form Load and pull the data. I could not find an answer. So i am posting my workaround for this.
I had written a plugin that executes on the retrieve of Contact. From the plugin i had call the Webservice and updates the contact fields.
var javaScriptSerializer = new JavaScriptSerializer();
javaScriptSerializer.MaxJsonLength = 104857600; //200 MB unicode
StringBuilder URI = new StringBuilder();
URI.Append(crmRestWebServiceUrl).Append(webServiceMethod);
var request = (HttpWebRequest)WebRequest.Create(URI.ToString());
request.Method = "POST";
request.Accept = "application/json";
request.ContentType = "application/json; charset=utf-8";
//Serialize request object as JSON and write to request body
if (latestMembershipRequest != null)
{
var stringBuilder = new StringBuilder();
javaScriptSerializer.Serialize(latestMembershipRequest, stringBuilder);
var requestBody = stringBuilder.ToString();
request.ContentLength = requestBody.Length;
var streamWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
streamWriter.Write(requestBody);
streamWriter.Close();
}
var response = request.GetResponse();
//Read JSON response stream and deserialize
var streamReader = new System.IO.StreamReader(response.GetResponseStream());
var responseContent = streamReader.ReadToEnd().Trim();
LatestMembershipResponse latestMembershipResponse = javaScriptSerializer.Deserialize<LatestMembershipResponse>(responseContent);
ContactToUpdate["gr_membershiptitle"] = latestMembership.MembershipTitle;
ContactToUpdate["gr_membershipstartdate"] = Convert.ToDateTime(latestMembership.MembershipStartDate);
ContactToUpdate["gr_membershipenddate"] = Convert.ToDateTime(latestMembership.MembershipEndDate);
ContactToUpdate["gr_membershipstatus"] = latestMembership.MembershipStatus;
service.Update(ContactToUpdate);
Im having a problem with my mobile app i do not know how to solve it.
when i push a button that gets data from a database, i parse it in json and when i want to use it in my app i get the undefined. Hoe can i make it so i do not get the undifined.
Note
I only get the undefind when the database is empty.
This is the code that i use
subjectButton.addEventListener('click', function(e) {
Subjects.getSubjects(url, function(response) {
if(response == '') {
alert('There where no subjects found');
} else {
subjectView.remove(subjectsLabel);
var data = JSON.parse(response);
if(data != 'undefined') {
var subjectNameButton = [];
var subjectEditButton = [];
var subjectDeleteButton = [];
for(i in data) {
id = data[i].id;
var subject = data[i].subject;
var year = data[i].year;
var status = data[i].status;
var color;
Ti.API.info('id: ' + id);
Ti.API.info('type id: '+ typeof id);
Can someone explain to me how i can make it so i don't get the undefined
Like #0101 said json can't return undefined so your problem is somewhere else.
I know this is not the best solution but it seems to work for me:
subjectButton.addEventListener('click', function(e) {
Subjects.getSubjects(url, function(response) {
if(response == '') {
alert('There where no subjects found');
} else {
subjectView.remove(subjectsLabel);
var data = JSON.parse(response);
var subjectNameButton = [];
var subjectEditButton = [];
var subjectDeleteButton = [];
for(i in data) {
id = data[i].id;
var subject = data[i].subject;
var year = data[i].year;
var status = data[i].status;
var color;
Ti.API.info('id: ' + id);
if(id != undefined) {
//Your code here
} else {
alert('There where no subjects found');
}
}
}
});
});
So here you have a check if one of the variables returns undefined or not. If it isn't undefined it will run your code else it will give you / the user an alert message
You will never get "undefined" from JSON.parse. The error must occurred somewhere else. Try this:
Subjects.getSubjects(url, function(response) {
if(!response) {
alert('There where no subjects found');
}
else {
subjectView.remove(subjectsLabel); // You probably should move this after JSON.parse
try {
var data = JSON.parse(response),
subjectNameButton = [],
subjectEditButton = [],
subjectDeleteButton = [];
for (i in data) { // Global i?
id = data[i].id; // Global too?
var subject = data[i].subject;
var year = data[i].year;
var status = data[i].status;
var color;
Ti.API.info('id: ' + id);
Ti.API.info('type id: '+ typeof id);
// ...
}
}
catch(e) {
console.log("Invalid JSON")
};
// ...
}
}
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.