tags:

views:

248

answers:

3

hi,

I have a JavaScript function code where I want to alert.

function msg(x,y)
{
 tempstr = x.value
if(tempstr.length>y)
 {
  alert(c_AcknowledgementText);
  x.value = tempstr.substring(0,y);
  }
}

Now I have an xml with below format:

<?xml version="1.0" encoding="utf-8" ?>
<root>
    <key name="c_ContactUsHeading">Contact Us</key>
    <key name="c_AcknowledgementText">Comments can not be more than 250 characters.</key>
</root>

I want the JavaScript code so that the message shown in above alert can be read from above xml key name "c_AcknowledgementText".

I hope it is clear about my problem.

A: 

You have to parse the XML file for c_AcknowledgementText (either in JavaScript or using a server side language and storing it into JavaScript as the page loads).

Detect
Thanks, can I have code using javascript.
MKS
+1  A: 

First step is to get a DOM reference to the XML document. One way to do that is with Ajax. In this case, the server needs to respond with the Content-Type: text/xml header.

$.ajax({
   type: "GET",
   url: "/path/to/my.xml",
   dataType: "xml",
   success: function(doc){
     var keys = doc.getElementsByTagName('key');
     if (keys.length > 0) {
       for (var i=0; i<keys.length; i++) {
         if (keys[i].getAttribute('name') == 'c_AcknowledgementText') {
           alert(keys[i].innerHTML);
         }
       }
     }
   }
 });

You may need some additional error-handling, etc.

steamer25
The property is responseXML.
Matthew Flaschen
Corrected--thanks.
steamer25
can it be done using jquery? if yes then please give me the code
MKS
how can I do the dom reference to XML document? please help
MKS
I've updated my answer to include jQuery AJAX functionality. Replace /path/to/my.xml with your actual path.
steamer25
+1  A: 

Basically, you want to use XMLHttpRequest. Not sure what you're trying to do with tempstr, etc., though.

function msg(x,y)
{
    tempstr = x.value;
    if(tempstr.length>y)
    {
     var req = new XMLHttpRequest();
     req.open('GET', '/file.xml', true);
     req.onreadystatechange = function (aEvt) {
      if (req.readyState == 4) {
       if(req.status == 200)
       {
        var keys = req.responseXML.getElementsByTagName("key");
        for(var i = 0; i < keys.length; i++)
        {
         var key = keys[i];
         if(key.getAttribute("name") == "c_AcknowledgementText")
         {
          alert(key.textContent);
          break;
         }
        }
       }
       else  
        alert("Error loading page\n");

            }
      };
      req.send(null);
      x.value = tempstr.substring(0,y);
    }
}
Matthew Flaschen
Thanks Matthew, but my code is not getting inside the if (req.readyState == 4), please suggest? Can it be done using JQuery?
MKS
Yes, you could use JQuery. But you might want to figure out what's going on first. Are you getting any errors? Have you checked that the path is correct?
Matthew Flaschen