Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Problem with ToString in Coldfusion

Posted on 2010-11-23
20
Medium Priority
?
759 Views
Last Modified: 2012-05-10
#Replace("<strong>" & ToString(qBusiness.businessName) & "</strong><br />"

This section of the code above is driving me crazy.  This code is a section of code being used for google maps.

Instead of listing business names and use emails the code works.  The only thing I can think of that is not allowing this to work would be blank spaces.

Any insight on this would be great.  If you want me to paste all the code I will.

Thanks
<cfoutput query="qBusiness">
    var address_0_#qBusiness_id# = {
      street: '#Replace("" & ToString(qBusiness.streetAddress) & "", "'", "\'")#',
      city: '#Replace("" & ToString(qBusiness.city) & "", "'", "\'")#',
      state: '#Replace("" & ToString(qBusiness.state) & "", "'", "\'")#',
      zip: '#Replace("" & ToString(qBusiness.postalCode) & "", "'", "\'")#',
      country: '',
      infowindow: 'custom',
      infowindowtext: '<span style="font: 12px Verdana, Arial, Helvetica, sans-serif; color: black;">#Replace("<strong>" & ToString(qBusiness.businessName) & "</strong><br />" & ToString(qBusiness.streetAddress) & "<br />" & ToString(qBusiness.city) & ", " & ToString(qBusiness.state) & " " & ToString(qBusiness.postalCode) & "", "'", "\'")#</span>',
      full: '#Replace("" & ToString(qBusiness.streetAddress) & "", "'", "\'")#, #Replace("" & ToString(qBusiness.city) & "", "'", "\'")#, #Replace("" & ToString(qBusiness.state) & "", "'", "\'")#, #Replace("" & ToString(qBusiness.postalCode) & "", "'", "\'")#',

Open in new window

0
Comment
Question by:sonicimpulse
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 12
  • 8
20 Comments
 
LVL 52

Expert Comment

by:_agx_
ID: 34202607
If the values are being used in javascript you typically want to use either: JSStringFormat or ToScript (not ToString)

http://livedocs.adobe.com/coldfusion/8/functions_in-k_46.html
http://livedocs.adobe.com/coldfusion/8/functions_t-z_05.html#188861

I think that'll fix the problem. But if not
1) Can you explain what you mean by "doesn't work"?
2) What's an example of a #qBusiness.businessName# value that doesn't work?

0
 
LVL 52

Expert Comment

by:_agx_
ID: 34202643
ToScript takes a string and escapes special characters so it's safe to use in javascript (or actionscript). ToString converts something that is *not* a string (integer, binary, etc..) into a string.
0
 

Author Comment

by:sonicimpulse
ID: 34202955
I get the following error with ToScript

Parameter validation error for the TOSCRIPT function.  
The function accepts 2 to 4 parameters.  

The values are as follow.

businessName will out put "myMobi Saver"
email will output "ken2@mymobisaver.com

Whats weird is the city, state, and zip out puts correctly.

I attached the entire code below.  Its line 153 in dreamweaver that creating the problem.
function WAMapRef(mapObj)  {
  this.obj = mapObj;
  this.directions = false;
  this.icons = [];
  this.markers = [];
  this.addresses = [];
  this.points = [];
  this.getPointByAddress = getPointByAddressFunc;
  this.addressFailed = true;
  return this;
}

function WAMapPoint(theMarker, theAddress, theIcon)  {
  this.icon = theIcon;
  this.marker = theMarker;
  this.address = theAddress;
  return this;
}

function getPointByAddressFunc(value,attname)  {
  if (!attname) attname = "street";
  for (var x=0; x < this.addresses.length; x++) {
    if (eval("this.addresses[x]."+attname) == value)  {
      return WAMapPoint(this.markers[x],this.addresses[x],this.icons[x]);
    }
  }
  return false;
}

function getHTTPObject(){   
  if (window.ActiveXObject)        
    return new ActiveXObject("Microsoft.XMLHTTP");   
  else if (window.XMLHttpRequest)        
    return new XMLHttpRequest();   
  else {
    return null;
  }
}

function searchCache(searchStr, zip) {
	var xmlDoc = null;
  if (window.ActiveXObject) {//IE
    xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  } else if(navigator.userAgent && navigator.userAgent.toLowerCase().indexOf('webkit') >= 0) { //webkit (Safari, Chrome)
  	var coordinates = '';
    xmlDoc = getHTTPObject();
    if(xmlDoc) {
      xmlDoc.onreadystatechange = function() {
        if(xmlDoc.readyState == 4) {
          var x = xmlDoc.responseXML.getElementsByTagName("geocode_entry");
          var geocode, id;
          searchStr = searchStr.replace(/,/g, ''); //remove commas
          for (i=0; i < x.length; i++) {
            id = x[i].getAttribute("ID");
            if (id == searchStr) {
              coordinates = x[i].getElementsByTagName("geocode")[0].childNodes[0].nodeValue;
              return coordinates;
            }
          }
        }
      };
      xmlDoc.open("GET", "_promaps_cache/_promaps_geocache.xml", false);
      xmlDoc.send(null);
    }
    
    return coordinates;
  } else if (document.implementation.createDocument) {//gecko (Mozilla, Firefox, Opera)
    xmlDoc=document.implementation.createDocument("","",null);
  } else {
    return '';
  }
  if (xmlDoc != null) {
    xmlDoc.async=false;
    try {
      if(xmlDoc.load("_promaps_cache/_promaps_geocache.xml")) {
        var x=xmlDoc.getElementsByTagName("geocode_entry");
        var geocode, id;
        searchStr = searchStr.replace(/,/g, ''); //remove commas
        for (i=0; i < x.length; i++) {
          id = x[i].getAttribute("ID");
          if (id == searchStr) {
            return x[i].getElementsByTagName("geocode")[0].childNodes[0].nodeValue;
          }
        } 
      } 
    }
    catch(err) {
      return '';
    }
  }
  return '';
}

function addToCache(fullAddress,zip, geocode){
  httpObject = getHTTPObject();
  if (httpObject != null) {
    httpObject.open("POST", "google_javascript/promaps_geocache_cfm.cfm", true);
    httpObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    var entryId = fullAddress.replace(/,/g, '');
    if (zip != '') {
      fullAddress = fullAddress.replace(zip+',', '');
    }
    entryId = escape(entryId);
    fullAddress = escape(fullAddress);
    geocode = escape(geocode);
    httpObject.send("sender=promapsforgoogle&action=add&entryId="+entryId+"&address="
+fullAddress+"&geocode="+geocode);
  }
}


function wagmp_map_1() {
  if(GBrowserIsCompatible()) {
    if(!document.getElementById('wagmp_map_1')) return false;
    var map = new GMap2(document.getElementById('wagmp_map_1'));
    wagmp_map_1_obj = new WAMapRef(map);
    map.enableContinuousZoom();
    map.enableDoubleClickZoom();
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
    var geocoder = new GClientGeocoder();
    
    var fromAddress = {
      enabled: false,
      street: '<cfoutput></cfoutput>',
      city: '<cfoutput></cfoutput>',
      state: '<cfoutput></cfoutput>',
      zip: '<cfoutput></cfoutput>',
      country: '<cfoutput></cfoutput>',
      full: ''
    };

    var icon_0 = new GIcon();
    icon_0.image = 'google_javascript/images/flag_deepjungle.png';
    icon_0.shadow = 'google_javascript/images/flag_shadow.png';
    icon_0.iconSize = new GSize(31,35);
    icon_0.shadowSize = new GSize(31,35);
    icon_0.iconAnchor = new GPoint(4,27);
    icon_0.infoWindowAnchor = new GPoint(8,3);
    icon_0.printImage = 'google_javascript/images/flag_deepjungle.gif';
    icon_0.mozPrintImage = 'google_javascript/images/flag_deepjungle_mozprint.png';
    icon_0.printShadow = 'google_javascript/images/flag_shadow.gif';
    icon_0.transparent = 'google_javascript/images/flag_deepjungle_transparent.png';
<cfset qBusiness_id=0>
<cfoutput query="qBusiness">
    var address_0_#qBusiness_id# = {
      street: '#Replace("" & ToString(qBusiness.streetAddress) & "", "'", "\'")#',
      city: '#Replace("" & ToString(qBusiness.city) & "", "'", "\'")#',
      state: '#Replace("" & ToString(qBusiness.state) & "", "'", "\'")#',
      zip: '#Replace("" & ToString(qBusiness.postalCode) & "", "'", "\'")#',
      country: '',
      infowindow: 'custom',
      infowindowtext: '<span style="font: 12px Verdana, Arial, Helvetica, sans-serif; color: black;">#Replace("<strong>" & ToScript(qBusiness.businessName) & "</strong><br />" & ToString(qBusiness.streetAddress) & "<br />" & ToString(qBusiness.city) & ", " & ToString(qBusiness.state) & " " & ToString(qBusiness.postalCode) & "", "'", "\'")#</span>',
      full: '#Replace("" & ToString(qBusiness.streetAddress) & "", "'", "\'")#, #Replace("" & ToString(qBusiness.city) & "", "'", "\'")#, #Replace("" & ToString(qBusiness.state) & "", "'", "\'")#, #Replace("" & ToString(qBusiness.postalCode) & "", "'", "\'")#', 
      isdefault: true,
      addressType: 'address',
      loop: 'qBusiness',
      latitude: '',
      longitude: '',
      markerStyle: 'Flag',
      markerColor: 'Deep Jungle'
    };
    
    if (address_0_#qBusiness_id#.addressType == "coordinates") {
      var cacheReturn = '';
    } else {
      var cacheReturn = searchCache(address_0_#qBusiness_id#.full, address_0_#qBusiness_id#.zip);
    }
    if (cacheReturn != "" || (address_0_#qBusiness_id#.addressType == "coordinates")) {
      if(address_0_#qBusiness_id#.addressType == "coordinates") {
        var latitude = address_0_#qBusiness_id#.latitude;
        var longitude = address_0_#qBusiness_id#.longitude;
      } else {
        var latitude = cacheReturn.substring(1,cacheReturn.indexOf(",")-1);
        var longitude = cacheReturn.substring(cacheReturn.indexOf(",")+1,(cacheReturn.length)-1);
      }
      var point = new GLatLng(latitude, longitude);
      if (point && !isNaN(latitude)) {
        wagmp_map_1_obj.addressFailed = false;
        var marker_0_#qBusiness_id# = new GMarker(point, icon_0);
        GEvent.addListener(marker_0_#qBusiness_id#, 'click', function() {
          marker_0_#qBusiness_id#.openInfoWindowHtml(address_0_#qBusiness_id#.infowindowtext);
        });
        if(!fromAddress.enabled || 'address_0_#qBusiness_id#' != 'address_0_0') {
          if('address_0_#qBusiness_id#' == 'address_0_0')
          map.setCenter(point, 13);
          map.addOverlay(marker_0_#qBusiness_id#);
if('address_0_#qBusiness_id#' == 'address_0_0')
            marker_0_#qBusiness_id#.openInfoWindowHtml(address_0_#qBusiness_id#.infowindowtext);
        }
          wagmp_map_1_obj.markers.push(marker_0_#qBusiness_id#);
          wagmp_map_1_obj.addresses.push(address_0_#qBusiness_id#);
          wagmp_map_1_obj.icons.push(icon_0);
          wagmp_map_1_obj.points.push(point);
        } else {
        if (wagmp_map_1_obj.addressFailed) {
          map.setCenter(new GLatLng(30, -98), 3);
        }
        wagmp_map_1_obj.addressFailed = true;
      }
    } else if (address_0_#qBusiness_id#.addressType == "address") {
      geocoder.getLatLng (
      address_0_#qBusiness_id#.full,
      function(point) {
        if(point) {
          this.addressFailed = false;
          addToCache(address_0_#qBusiness_id#.full, '', point);
          var marker_0_#qBusiness_id# = new GMarker(point, icon_0);
          GEvent.addListener(marker_0_#qBusiness_id#, 'click', function() {
            marker_0_#qBusiness_id#.openInfoWindowHtml(address_0_#qBusiness_id#.infowindowtext);
          });
          if(!fromAddress.enabled || 'address_0_#qBusiness_id#' != 'address_0_0') {
            if('address_0_#qBusiness_id#' == 'address_0_0')
            map.setCenter(point, 13);
            map.addOverlay(marker_0_#qBusiness_id#);
if('address_0_#qBusiness_id#' == 'address_0_0')
            marker_0_#qBusiness_id#.openInfoWindowHtml(address_0_#qBusiness_id#.infowindowtext);
          }
              wagmp_map_1_obj.markers.push(marker_0_#qBusiness_id#);
          wagmp_map_1_obj.addresses.push(address_0_#qBusiness_id#);
          wagmp_map_1_obj.icons.push(icon_0);
          wagmp_map_1_obj.points.push(point);
        
        } else {
          var noZipAddress = address_0_#qBusiness_id#.full.replace((address_0_#qBusiness_id#.zip+','), '');
          geocoder.getLatLng (noZipAddress,
            function(point) {
              if(point) {
                wagmp_map_1_obj.addressFailed = false;
                addToCache(address_0_#qBusiness_id#.full, address_0_#qBusiness_id#.zip, point);
                var marker_0_#qBusiness_id# = new GMarker(point, icon_0);
                GEvent.addListener(marker_0_#qBusiness_id#, 'click', function() {
                  marker_0_#qBusiness_id#.openInfoWindowHtml(address_0_#qBusiness_id#.infowindowtext);
                });
                if (!fromAddress.enabled || 'address_0_#qBusiness_id#' != 'address_0_0') {
                  if('address_0_#qBusiness_id#' == 'address_0_0')
                  map.setCenter(point, 13);
                  map.addOverlay(marker_0_#qBusiness_id#);
if('address_0_#qBusiness_id#' == 'address_0_0')
            marker_0_#qBusiness_id#.openInfoWindowHtml(address_0_#qBusiness_id#.infowindowtext);
                }
                    wagmp_map_1_obj.markers.push(marker_0_#qBusiness_id#);
          wagmp_map_1_obj.addresses.push(address_0_#qBusiness_id#);
          wagmp_map_1_obj.icons.push(icon_0);
          wagmp_map_1_obj.points.push(point);
        
              } else {
                if (wagmp_map_1_obj.addressFailed) {
                  map.setCenter(new GLatLng(30, -98), 3);
                }
                  wagmp_map_1_obj.addressFailed = true;
              }
            }
          );
        }
      }
    );
  }
<cfset qBusiness_id=qBusiness_id+1>
</cfoutput>


  }
}

Open in new window

0
The Eight Noble Truths of Backup and Recovery

How can IT departments tackle the challenges of a Big Data world? This white paper provides a roadmap to success and helps companies ensure that all their data is safe and secure, no matter if it resides on-premise with physical or virtual machines or in the cloud.

 
LVL 52

Expert Comment

by:_agx_
ID: 34202990
>> Whats weird is the city, state, and zip out puts correctly.
Ok.. but you still didn't explain what "not correct" means ;-)  Are you getting an error in FF/Firebug?


>> I get the following error with ToScript
Yeah, ToScript requires at 2 parameters minimum (ToScript(cfvar, javascriptvar, ....).  Try JSStringFormat() instead. It's simpler.

0
 
LVL 52

Expert Comment

by:_agx_
ID: 34203001
Could you post the javascript code generated, or a link to a live page? It'd be easier to spot the problem.

Btw: I'm going to be heading to sleep soon.  It's been a loong day ;-)
0
 

Author Comment

by:sonicimpulse
ID: 34203029
JSStringFormat does not work either. I'm not getting an error but no map.
Here is whats happening.

When I use an email the actual google map show up.  If I use a business name it does not show up at all.

Link below.
http://mymobisaver.com/indexbak.cfm

0
 
LVL 52

Expert Comment

by:_agx_
ID: 34203100
Can you post a separate link showing the non-working business name?
0
 
LVL 52

Expert Comment

by:_agx_
ID: 34203215
I tried to look a the page, but for some reason a view source of the page is killing FF/Firebug ... :(  Maybe all the javascript?  

Sorry - I hate to run out, but I have to go to sleep now :) I'll check back tomorrow, if you haven't figured it out by then.
0
 

Author Comment

by:sonicimpulse
ID: 34203319
I narrowed done the problem.

the apostrophe " ' " in business names is causing the problem.  All I need to know is how do I fix the problem without taking that out of every business name?

If someones business names is KICK's it will not work only KICKs will.

0
 
LVL 52

Expert Comment

by:_agx_
ID: 34207453
>> the apostrophe " ' " in business names is causing the problem

Something doesn't sound right. Single quotes are one of the special characters JSStringFormat escapes.  Notice how

      #JSFormat("Bob's Business")#

... becomes

       Bob\'s Business

Which works fine in javascript.  Without the JSStringFormat() it _doesn't_ work.

<cfoutput>
<script>
      var value1 = '<b>#JSStringFormat("Bob's Business")#</b>';
      alert(value1);
</script>
</cfoutput>

So are you *positive* you've applied the function correctly?

0
 
LVL 52

Expert Comment

by:_agx_
ID: 34207799
So are you *positive* you've applied the function correct

... meaning you use JSStringFormat() instead of Replace(). Because JSStringFormat handles more than just single quotes.

0
 

Author Comment

by:sonicimpulse
ID: 34209042
Still does not work.  here is my code below with the JSStringFormat.

<span style="font: 12px Verdana, Arial, Helvetica, sans-serif; color: black;">#Replace("<strong>" & JSStringFormat(qBusiness.businessName) & "</strong><br />" & ToString(qBusiness.streetAddress) & "<br />" & ToString(qBusiness.city) & ", " & ToString(qBusiness.state) & " " & ToString(qBusiness.postalCode) & "", "'", "\'")#</span>',
0
 
LVL 52

Expert Comment

by:_agx_
ID: 34209263
>> Still does not work.

No, you're not doing what I described ;-)

1) Get rid of the ToString()'s.  
The function doesn't do anything when the values are already strings!

2) Get rid of the Replace()'s.  
That's what JSStringFormat() is for. It handles more than replace(). Including both functions will cause errors.

3) Try a simple example with JSStringFormat() only.  Get a small example working 1st.

<cfset qBusiness.businessName = "Bob's buisiness">
<cfset qBusiness.streetAddress = "address blah">
<cfset qBusiness.city = "Seattle">
<cfset qBusiness.state = "WA">
<cfset qBusiness.postalCode = "00000">
<cfoutput>
<script>
	var test = '<span style="font: 12px Verdana, Arial, Helvetica, sans-serif; color: black;"><strong>#JSStringFormat(qBusiness.businessName)#</strong><br />#JSStringFormat(qBusiness.streetAddress)#<br />#JSStringFormat(qBusiness.city)#, #JSStringFormat(qBusiness.state)# #JSStringFormat(qBusiness.postalCode)#</span>';
	alert(test);
</script>
</cfoutput>

Open in new window


4) Watch out for line breaking in the middle of the string. It can sometimes cause problems.

0
 

Author Comment

by:sonicimpulse
ID: 34209376
I get a message from from webpage with your example.

I'm not really good with this yet so thanks for the help so far.
0
 
LVL 52

Accepted Solution

by:
_agx_ earned 2000 total points
ID: 34209446
Generating big strings is always a pain when quotes are involved.  Sometime it's easier to create a CF variable with the html first. Then convert the 1 variable to javascript




<!--- 
    create a CF variable w/html first 
--->	
<cfsavecontent variable="MyOutput">
<cfoutput>
<span style="font: 12px Verdana, Arial, Helvetica, sans-serif; color: black;">
	<strong>#qBusiness.businessName#</strong><br />
	#qBusiness.streetAddress#<br />
	#qBusiness.city#, #qBusiness.state# #qBusiness.postalCode#
</span>
</cfoutput>
</cfsavecontent>

<!--- then pass it to javascript --->
<cfoutput>
<script>
	var test = '#JSStringFormat(MyOutput)#';
	alert(test);
</script>
</cfoutput>

Open in new window

0
 

Author Comment

by:sonicimpulse
ID: 34209815
Even if I use your example:

<span style="font: 12px Verdana, Arial, Helvetica, sans-serif; color: black;"><strong>#JSStringFormat(qBusiness.businessName)#</strong><br />#JSStringFormat(qBusiness.streetAddress)#<br />#JSStringFormat(qBusiness.city)#, #JSStringFormat(qBusiness.state)# #JSStringFormat(qBusiness.postalCode)#</span>'

Still the map will not show. I'm not getting any errors just no map.
0
 

Author Comment

by:sonicimpulse
ID: 34209924
There has to be away to pass single quotes into a variable with in Java.
0
 

Author Closing Comment

by:sonicimpulse
ID: 34210063
Thanks so much I found out what I was doing wrong.  Its works now.
0
 
LVL 52

Expert Comment

by:_agx_
ID: 34210081
Can you post a *small* standalone example we can test? Because the string works in a simple test, so obviously there's more going on in the map.
0
 
LVL 52

Expert Comment

by:_agx_
ID: 34210089
Didn't see your last post before responding.  So what was the problem? :)
0

Featured Post

Will your db performance match your db growth?

In Percona’s white paper “Performance at Scale: Keeping Your Database on Its Toes,” we take a high-level approach to what you need to think about when planning for database scalability.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Since I wrote the original article about Handling Date and Time in PHP and MySQL several years ago, it seemed like now was a good time to update it for object-oriented PHP.  This article does that, replacing as much as possible the pr…
In this blog post, we’ll look at how using thread_statistics can cause high memory usage.
In this video, Percona Solution Engineer Dimitri Vanoverbeke discusses why you want to use at least three nodes in a database cluster. To discuss how Percona Consulting can help with your design and architecture needs for your database and infras…
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…

722 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question