Return xml in jquery ajax

My problem is that I want to return the xml file from the server back to the client and parse it using jQuery jQuery. This is the code:

Client:

$("#submit").click(function(){ $.ajax({ type: "POST", url: "search.php", data: "whatever", dataType: "xml", async: false, success: function(xml){ var data = $('doctor',xml).text(); alert(data); } }); }); 

Server (php file),

 header('Content-type: text/xml'); echo '<?xml version="1.0" encoding="utf-8"?>'; echo "<tables>"; echo "<doctor>Someone</doctor>"; echo "</tables>"; 

I have an empty warning and I don’t know why ??


ok i found it. my php file was in this form
 //some code include("other.php"); //some other code 

where the other.php file was the file that I posted above. I cut / paste the header so the last php file is

 //some code header('Content-type: text/xml'); include("other.php"); //some other code 

and other.php

 echo '<?xml version="1.0" encoding="utf-8"?>'; echo "<tables>"; echo "<doctor>Someone</doctor>"; echo "</tables>"; 

Now it works fine. Thanks for your quick answers!

+6
source share
4 answers

It works fine

Post.php file

 if($_GET['id']!=""){ $array = array('satyam' => 'satyam', 'class' => 'B.TECH', 'company' => 'Ranosys'); } $new ='<?xml version="1.0" encoding="iso-8859-1"?><data>'; foreach($array as $key => $values){ $new .= "<$key>$values</$key>"; } echo $new.'</data>'; ================= function load_data(){ $.ajax({ url: "post.php", async: false, // stop browser for another activity data: "id=satyam", // dataType :'xml', error: function(e, b, error) { for(var i in e){ // alert(i); } alert(e.respone); }, success: function(msg) { //alert($response); var data = $(msg).find("satyam").text(); alert(data); } }); } 
+2
source

Try the following: var data = $(xml).find('doctor').text()

In your example, "xml" is not a jQuery object.

+1
source

You need to parse this XML (I really don't understand why, but ...), you can do this by doing the following:

 $(xml).find('doctor').text(); 

Bye. :)

0
source

You must change your function:

 $("#submit").click(function(){ $.ajax({ type: "POST", url: "search.php", data: "whatever", dataType: "xml", async: false, success: function(xml){ var xmlDoc; if (window.DOMParser) { parser = new DOMParser(); xmlDoc = parser.parseFromString(xml, "text/xml"); } else {// Internet Explorer xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = "false"; xmlDoc.loadXML(xml); } var $response = $(xmlDoc); var data = $response.find("doctor").text() alert(data); } }); }); 

The reason for if (window.DOMParser) { is that you have a problem with IE parsing.

0
source

Source: https://habr.com/ru/post/888484/


All Articles