Turning xmlhttp.responseText into links

I need to turn xmlhttp.responseText into a column of links that will be displayed in a popup div.

I’ve defined xmlhttp.responseText as var named txt with:

var txt=xmlhttp.responseText;

That produces a var with comma delimited values.

I’d like to proceed by passing txt through a For Loop that will create the links, but I can’t find a method that will count commas.

How do I return the number of commas in javascript?

You have a few options including:

  1. get the server side script to create the html to create the links and return that html to your responseText via an echo. Then use javascript to assign the xmlhttp.responseText to an element in your web page.

  2. use javscript’s .split() method to breal up your string of comma delimited values into an array of those values . Then in a FOR loop use DOM methods (createElement() etc etc) to create links for each element in the array and then use appendChild() to place those links where you like in the DOM.

Here’s what I have. How do I get the new link name into the anchor tag?


          var txt=xmlhttp.responseText;
	  var end = txt.slice(0,txt.indexOf(",")); //define number of cycles of For Loop 
	  var txt2 = txt.substr(txt.indexOf(",")+1);  //cut 1st position from string and save remaining info
	  var i = 0;
	  for (i=0;i<=end;i++){
	    var link = document.createElement('a'); //create anchor
	    var new_link = txt.slice(0,txt.indexOf(",")); //name new link/page name 
	    var balance = txt2.substr(txt.indexOf(",")+1);  //cut new link from string and store remaning link names 
	  }

I would use split() rather than slice().

I’m not sure how your responseText is structured so I’m assuming a comma delimited string containing link label/href pairs.

I would include something like below in your onreadystatechange() event handler to create the links.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
        <title></title>
        <style type="text/css">
            a {
                display: block;
            }
        </style>
    </head>
    <body>
        <div id="linksCont"></div>
        <script type="text/javascript">
            var str = 'link1,url1,link2,url2,link3,url3';  // this would be your responsetext string
            var strA = str.split(',');

            for(i=0; i<strA.length; i+=2){
                var newLnk = document.createElement('a');
                newLnk.href = strA[i+1];
                newLnk.innerHTML = strA[i];
                document.getElementById('linksCont').appendChild(newLnk);
            }
        </script>
    </body>
</html>

For the record, xmlhttp.responseText= “2, Bob , Brittany , Brian”
Where 2 is the number of commas.

I should have said that I need to get the links into the div created by my javascript. Here’s all the code I have so far:


 html>
<head>
<script type="text/javascript">
function showHint(str) {
  if (str.length==0) {
    document.getElementById("txtHint").innerHTML="";
    return;
  }
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
    } else {
         // code for IE6, IE5
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
   xmlhttp.onreadystatechange=function() {
   if (xmlhttp.readyState==4 && xmlhttp.status==200) {
     var div = document.createElement('div');
     div.setAttribute('id', 'link_container');
     div.setAttribute("style","background-color:red;");
     div.style.width = '300px';
     div.style.height = '100px';
     div.style.margin = '-15px 0px 0px 75px';
          
     var txt=xmlhttp.responseText;
     var end = txt.slice(0,txt.indexOf(",")); //define number of cycles of For Loop
     var txt2 = txt.substr(txt.indexOf(",")+1);  //cut 1st position from string and save remaining info
     var i = 0;
     for (i=0;i<=end;i++){
         var link = document.createElement('a'); //create anchor
        var new_link = txt.slice(0,txt.indexOf(",")); //name new link
         var balance = txt2.substr(txt.indexOf(",")+1);  //cut new link from string and store remaning link names
     }
           
     document.getElementsByTagName('body')[0].appendChild(div);
     document.getElementById('link_container').innerHTML=txt2+end;
      }
  }
  xmlhttp.open("GET","gethint.php?q="+str,true);
  xmlhttp.send();
}
</script>
</head>
<body>
  <p><b>Start typing a name in the input field below:</b></p>
  <form>
    First name: <input type="text" onkeyup="showHint(this.value)" size="20" />
  </form>
 
</body>
</html>

It would’ve been nice if you posted the example string in your first post. But it’s only a few minor tweaks to the code I posted.

Agreed. Please excuse me. I usually try to post the least amount of code in the interest of making it as easy as possible for someone to respond. Obviously, I should have posted everything. It wasn’t that long.

Any way, the script was displaying the empty red div until I uncommented the second line of the For Loop. That surprised me.

Why do you think it’s choking (I’m trying to work up to the complete For Loop)?


<html>
<head>
<script type="text/javascript">
function showHint(str) {
  if (str.length==0) {
    document.getElementById("txtHint").innerHTML="";
    return;
  }
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
    } else {
   	  // code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
	  var div = document.createElement('div');
      div.setAttribute('id', 'link_container');
      div.setAttribute("style","background-color:red;");
      div.style.width = '300px';
      div.style.height = '100px';
	  div.style.margin = '-15px 0px 0px 75px';
	  //var txt=document.innerHTML=xmlhttp.responseText;
	  
	  var txt=xmlhttp.responseText;
	  var strA = txt.slice(0,txt.indexOf(",")); //define number of cycles of For Loop 
	  var str = txt.substr(txt.indexOf(",")+1);  //cut 1st position from string and save remaining info
	  for (i=0;i<=strA;i++){
	    var newLink = document.createElement('a'); //create anchor
            //newLnk.href = strA[i+1];
            //newLnk.innerHTML = strA[i];
            //document.getElementById('linksCont').appendChild(newLnk);
	  }
	    
	  document.getElementsByTagName('body')[0].appendChild(div);
      document.getElementById('link_container').innerHTM;
	}
  }
  xmlhttp.open("GET","gethint.php?q="+str,true);
  xmlhttp.send();
}
</script>
</head>
<body>
  <p><b>Start typing a name in the input field below:</b></p>
  <form>
    First name: <input type="text" onkeyup="showHint(this.value)" size="20" />
  </form>
 
</body>
</html>

ok, you need to do some basic debugging here.

I’m not sure where you started your debugging process but the first thing that needs to be done, if you haven’t already done so, is check the value of responseText


var txt=xmlhttp.responseText;
[COLOR=#ff0000]alert(txt);[/COLOR]

If txt is not ok, then there is no point in worrying about any downstream code for now.

If txt is ok then check the contents of strA

Your strA is the ouput from a slice() and I’m not sure what you are hoping to do with strA.

Post a correct value of txt and the expected contents of strA. Then post the actual contents of strA.

I displayed the results in my red drop-down div.

txt = “2,Bob , Brittany , Brian”

strA = “2”

That’s what I expected. 2 is the number of commas in the string.

EDIT:
changed text = “2,Bob , Brittany , Brian” to txt = “2,Bob , Brittany , Brian”

ok, but 1 thing I just noticed in your code.


[COLOR=#000000]var [/COLOR][B][COLOR=#ff0000]newLink[/COLOR][/B][COLOR=#000000] = document.createElement('a'); //create anchor            
 //[/COLOR][B][COLOR=#ff0000]newLnk[/COLOR][/B][COLOR=#000000].href = strA[i+1];             
//newLnk.innerHTML = strA[i];             
//document.getElementById('linksCont').appendChild(newLnk);[/COLOR]

That doesn’t look right.

Anyway, I can’t actually run your code, so just follow the basic debugging process and keep using alert()'s to check values of variables as you step through your code and fix any incorrect variable values as they come up.

I misspelled newLink as newLnk.

How do I get the links into the red div starting with this code?


<html>
<head>
<script type="text/javascript">
function showHint(str) {
  if (str.length==0) {
    document.getElementById("txtHint").innerHTML="";
    return;
  }
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
    } else {
   	  // code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
	  var div = document.createElement('div');
      div.setAttribute('id', 'link_container');
      div.setAttribute("style","background-color:red;");
      div.style.width = '300px';
      div.style.height = '100px';
	  div.style.margin = '-15px 0px 0px 75px';
	  //var txt=document.innerHTML=xmlhttp.responseText;
	  
	  var txt=xmlhttp.responseText;
	  var strA = txt.slice(0,txt.indexOf(",")); //define number of cycles of For Loop 
	  var str = txt.substr(txt.indexOf(",")+1);  //cut 1st position from string and save remaining info
	  for (i=0;i<=strA;i++){
	    var newLink = document.createElement('a'); //create anchor
		newLink.href = strA;
        newLink.innerHTML = strA[i];
        //document.getElementById('linksCont').appendChild(newLink);
	  }
	    
	  document.getElementsByTagName('body')[0].appendChild(div);
      document.getElementById('link_container').innerHTML=txt;
	}
  }
  xmlhttp.open("GET","gethint.php?q="+str,true);
  xmlhttp.send();
}
</script>
</head>
<body>
  <p><b>Start typing a name in the input field below:</b></p>
  <form>
    First name: <input type="text" onkeyup="showHint(this.value)" size="20" />
  </form>
 
</body>
</html>

shouldn’t

newLink.innerHTML = strA[i];

be

newLink.innerHTML = str[i];

??

How do I get the links into the red div starting with this code?

This is starting to sound like you are just sticking together with band aids bits and pieces of code from cyberspace because if you wrote and understood all that code you would know the answer to how to get the links into the div because you are adding elements to other elements elsewhere in your code already.

I claim authorship for most of this, but I started with a template.

I’ve never created an element that to be placed in another element (my red div) with javascript before or a group of elements for placement into another element (my red div).

That’s where I need your help. I think were almost done.

The script is working again. The empty red div is displaying with this code:

How do i get the Result from the For Loop into the red div?

EDIT: I should’ve asked whether it appears that I’m thinking ab out this right?

 
<html>
<head>
<script type="text/javascript">
function showHint(str) {
  if (str.length==0) {
    document.getElementById("txtHint").innerHTML="";
    return;
  }
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
    } else {
   	  // code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
	  var div = document.createElement('div');
      div.setAttribute('id', 'link_container');
      div.setAttribute("style","background-color:red;");
      div.style.width = '300px';
      div.style.height = '100px';
	  div.style.margin = '-15px 0px 0px 75px';
	  //var txt=document.innerHTML=xmlhttp.responseText;
	  
	  var txt=xmlhttp.responseText;
	  var strA = txt.slice(0,txt.indexOf(",")); //define number of cycles of For Loop 
	  var str = txt.substr(txt.indexOf(",")+1);  //cut 1st position from string and save remaining info
	  for (i=0;i<=strA;i++){
	    var newLink = document.createElement('a'); //create anchor
		newLink.href = strA;
        newLink.innerHTML = str[i];
        //document.getElementById('linksCont').appendChild(newLink);
	  }
	    
	  document.getElementsByTagName('body')[0].appendChild(div);
      document.getElementById('link_container').innerHTML=txt;
	}
  }
  xmlhttp.open("GET","gethint.php?q="+str,true);
  xmlhttp.send();
}
</script>
</head>
<body>
  <p><b>Start typing a name in the input field below:</b></p>
  <form>
    First name: <input type="text" onkeyup="showHint(this.value)" size="20" />
  </form>
 
</body>
</html>

I’ve moved this a little further with webdev1958’s help. I’m displaying the last value in the string as a link in the red div, but not the preceding values. I haven’t found a way to group/concat the links produced in the For Loop. How can that be done?

Here’s my code so far:


&lt;html&gt;
&lt;head&gt;
&lt;script type="text/javascript"&gt;
function showHint(str) {
  if (str.length==0) {
    document.getElementById("txtHint").innerHTML="";
    return;
  }
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
    } else {
   	  // code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
	  var div = document.createElement('div');
      div.setAttribute('id', 'link_container');
      div.setAttribute("style","background-color:red;");
      div.style.width = '300px';
      div.style.height = '100px';
	  div.style.margin = '-15px 0px 0px 75px';
	  //var txt=document.innerHTML=xmlhttp.responseText;
	  var txt=xmlhttp.responseText;
	  var strA = txt.slice(0,txt.indexOf(",")); //define number of cycles of For Loop 
	  var str = txt.substr(txt.indexOf(",")+1);  //cut 1st position from string and save remaining info
	  for (i=0; i&lt;=strA; i++){
	    var newLink = document.createElement('a'); //create anchor
		var linkName = str.slice(0,str.indexOf(","));
		newLink.href = linkName+".php";
                newLink.innerHTML = linkName;
		var str = str.substr(str.indexOf(",")+1);
	  }
	    
	  document.getElementsByTagName('body')[0].appendChild(div);
      //document.getElementById('link_container').innerHTML=str;
      document.getElementById('link_container').appendChild(newLink);

	}
  }
  xmlhttp.open("GET","gethint.php?q="+str,true);
  xmlhttp.send();
}
&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;p&gt;&lt;b&gt;Start typing a name in the input field below:&lt;/b&gt;&lt;/p&gt;
  &lt;form&gt;
    First name: &lt;input type="text" onkeyup="showHint(this.value)" size="20" /&gt;
  &lt;/form&gt;
 
&lt;/body&gt;
&lt;/html&gt;

Adding appendChild() to the loop did the trick. I’m learning.

Thanks webdev1958! You made me work it out.

glad you eventually sorted it out :slight_smile: