Ajax Talk - Asynchronous javascript and xml discussion board
 FAQ   Search    Usergroups      Register   Profile   Check your messages   Log in 
Signup now to enjoy a range of free membership advantages !!
Ajax Talk - Moderators Wanted
Can I return HTML within an XMLHTTP request's responseXML?

 
Post new topic   Reply to topic    Ajaxtalk.com Forum Index -> AJAX Help
View previous topic :: View next topic  
Author Message
museumoftechno
New one
New one


Joined: 05 Jun 2007
Posts: 2
Location: London, UK

PostPosted: Tue Jun 05, 2007 11:10 am    Post subject: Can I return HTML within an XMLHTTP request's responseXML? Reply with quote

Hello there

I'm working on a form (code at the end of post) which submits to a PHP script using AJAX.

The PHP script then either UPDATEs or INSERTs a record in mySQL.

I'd like the PHP script to return some XML: the ID# of the affected record (particularly useful when INSERTing a new record); and some feedback for the user (a "success" message, or details of where the process failed).

This works well as long as my feedback is in the form of simple text, but I'd like to return HTML so that I can include formatted lists of invalid fields etc. And when I include HTML in my feedback, the code no longer works.

Does anyone know how I can return some HTML within my script's XML, and then display that via AJAX.. or alternatively, can anyone tell me why it won't work?

Many thanks

Dave

The Code

1: The page containing the form
Code:
<html>
   <head>
      <title>AJAX Test</title>
      <script type="text/javascript" language="javascript">
         //   Create XMLHTTPRequest
         var oXMLHTTP = createRequestObject();

         //   Function to create XMLHTTPRequest
         function createRequestObject() { 
            // find the correct xmlHTTP, works with IE, FF and Opera
            var xmlhttp;
            try{
               xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
            } catch(e){
               try{
                  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
               } catch(e){
                  xmlhttp = null;
               }
            }
            if(!xmlhttp && typeof XMLHttpRequest!="undefined") {
               xmlhttp = new XMLHttpRequest();
            }
            return xmlhttp;
         }
         
         //   Function to send XMLHTTPRequest to server - with random number in URL to avoid caching
         function sendRequest(){
            var rnd = Math.random();
            try{
               oXMLHTTP.open("GET", "ajax_process.php?rnd=" + rnd);
               //   Event handler for readystate change
               oXMLHTTP.onreadystatechange = handleResponse;
               oXMLHTTP.send(null);
            } catch(e){
               alert("Error sending AJAX request.");
            }
         }
         
         //   Function to return the contents of a specific tag in XMLTHHPRequest's ResponseXML
         function getTagValue(sTagName, oXMLResponse){
            try{
               return oXMLResponse.getElementsByTagName(sTagName)[0].firstChild.nodeValue;
            } catch(e){
               return false;
            }
         }
         
         //   Function to handle XMLHTTPRequest's response
         function handleResponse(){
            try{
               if(oXMLHTTP.readyState == 4 && oXMLHTTP.status == 200){
                  var oResponse = oXMLHTTP.responseXML.documentElement;
                  document.getElementById('member_id').value = getTagValue("recordid", oResponse);
                  document.getElementById('feedback_html').innerHTML = getTagValue("feedback", oResponse);
                  alert("member_id = " + document.getElementById('member_id').value);
               }
            } catch(e){
               alert("Error handling response.");
            }
         }
      </script>
   </head>
   <body>
      <div id="feedback_html"></div>
      <form name="myform" id="myform" onSubmit="javascript:return false;">
         <input type="hidden" id="member_id" value="0">
         <input type="button" id="mybutton" onClick="javascript:sendRequest();" value="AJAX">
      </form>
   </body>
</html>


2: The PHP which generates the XML response (TEXT version, this one works)
Code:
<?php
//  Send header to set content-type of response to XML
header("content-type: text/xml");

//  Catch rnd parameter from URL and generate a random number if none received
if(is_numeric($_GET['rnd'])){
    $rnd = $_GET['rnd'];
} else {
    srand((double) microtime( )*1000000);
    $rnd = rand();
}

//  Generate XML
echo "<response><recordid>12</recordid><feedback>It's a hard-knock life, so it is!</feedback><rnd>$rnd</rnd></response>";
die();
?>


2b: The PHP which generates the XML response (HTML version, this one causes the AJAX Javascript to fail)
Code:
<?php
//  Send header to set content-type of response to XML
header("content-type: text/xml");

//  Catch rnd parameter from URL and generate a random number if none received
if(is_numeric($_GET['rnd'])){
    $rnd = $_GET['rnd'];
} else {
    srand((double) microtime( )*1000000);
    $rnd = rand();
}

//  Generate XML
echo "<response><recordid>12</recordid><feedback><h2>Failed</h2><p>It's a hard-knock life, so it is!</p></feedback><rnd>$rnd</rnd></response>";
die();
?>
Back to top
View user's profile Send private message Visit poster's website MSN Messenger
museumoftechno
New one
New one


Joined: 05 Jun 2007
Posts: 2
Location: London, UK

PostPosted: Tue Jun 05, 2007 11:23 am    Post subject: Reply with quote

Embarassed Sorry everybody - writing that post clarified the problem to me, and I went away and found the answer: it's a question of wrapping the HTML in my XML file in a CDATA section.

I think the problem was due to the HTML being parsed as structured XML, so I couldn't just grab it as if it was a text value. Creating a CDATA section in the XML (wrapping the HTML between "<![CDATA[" and "]]>") prevents the HTML from being treated as part of the XML's DOM, so I can then read it as a text value and write it into a DIV tag. If it helps anyone, here's the corrected version of the processing PHP script.

Oh - and by "corrected" I mean "working OK for now," not "beautiful, finished code that people should necessarily copy". Have a good week!

Dave

Code:
<?php
//  Send header to set content-type of response to XML
header("content-type: text/xml");

//  Catch rnd parameter from URL and generate a random number if none received
if(is_numeric($_GET['rnd'])){
    $rnd = $_GET['rnd'];
} else {
    srand((double) microtime( )*1000000);
    $rnd = rand();
}

//  Generate XML
echo "<response><recordid>12</recordid><feedback><![CDATA[<h2>Failed</h2><p>It is a hard-knock life, so it is!</p>]]></feedback><rnd>$rnd</rnd></response>";
die();
?>
Back to top
View user's profile Send private message Visit poster's website MSN Messenger
Display posts from previous:   
Post new topic   Reply to topic    Ajaxtalk.com Forum Index -> AJAX Help All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
 Advertisements
 XML & Copyright Notice 
    


Powered by phpBB © 2001, 2005 phpBB Group

What is according to Wikipedia: Ajax Web2.0 XML E4X


Link to our site:

  


del.icio.us digg spurl wists simpy newsvine blinklist furl blogmarks yahoo! myweb smarking ma.gnolia segnalo reddit fark technorati cosmos


Normal Bookmark


Partner Button Links:
Codecrunch.com: Webmaster Tutorials    One Ajax


Partner Text Links:
quomon | web20log | ajaxmatters | tableless | 456bereastreet | music charts | gift ideas | competitions | free xbox 360 | link trade ?


Credits:
it consultancy & project management lead generation zoekmachine optimalisatie steal these buttons seo expert