ram933 ram933 - 1 year ago 66
Ajax Question

Read XML node using ajax

I need to use ajax to read xml node values and use those values further in existing JavaScript function.

Sample XML -


<car mfgdate="1 Jan 15" name="Ford" id="1">
<engine litres="3.0" cylinders="6"/>

<car mfgdate="1 Feb 15" name="Toyota" id="2">
<engine litres="2.2" cylinders="4"/>


Here I need to display details of one car (Ex.Ford) at a time on screen.
There are separate fields on UI to display details like name, mfgdate, litres and cylinders.

If user press next button then next car(Ex. Toyota) details should appear on screen. I need to make ajax calls to do it.

Any help is much appreciated.


Ajax Call

$.ajax({ type: "GET",
url: "Cars.xml",
dataType: "xml",
success: function (xml) {
var xmlDoc = $.parseXML(xml);
$xml = $(xmlDoc);
$xml.find('events event date').each(function () {
alert($(this).text() + "<br />");

Answer Source

You can find here an example but you have just to put the parse part inside your ajax response call (and also for use as you designed your style ) :

var xmlString = '<cars>'+
                   '<car mfgdate="1 Jan 15" name="Ford" id="1">'+
                      '<engine litres="3.0" cylinders="6"/>'+
                   '<car mfgdate="1 Feb 15" name="Toyota" id="2">'+
                      '<engine litres="2.2" cylinders="4"/>'+
                   '<car mfgdate="1 Jan 16" name="SONACOM" id="3">'+
                      '<engine litres="4.0" cylinders="8"/>'+
// used to inc or decrements throw cars 
var i = 0;

  xml = $.parseXML( xmlString );
  $xml = $( xml );
  $cars = $xml.find( "car" );
  function getCar(cars) {
    var html ="";
    if(cars.length != 'undefined') {
      if(cars.length > 0) {
           var name = $(cars[i]).attr('name');
           var mfgdate = $(cars[i]).attr('mfgdate')
           var $engine = $(cars[i]).find('engine');
           var litres = $($engine).attr('litres');
           var cylinders = $($engine).attr('cylinders');
           html += "<div>Name : "+name+"</div>";
           html += "<div>Mfgdate : "+mfgdate+"</div>";
           html += "<div>Litres : "+litres+"</div>";
           html += "<div>Cylinders : "+cylinders+"</div>";

  function btnClick() {
    i == 0 ? $("#btnprev").attr("disabled","disabled") :$("#btnprev").removeAttr("disabled");
    i == $cars.length-1 ? $("#btnnext").attr("disabled","disabled") : $("#btnnext").removeAttr("disabled");

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="btnprev" disabled>prev</button>
<button id="btnnext" disabled>next</button>
<br>  <br>  
<div id ="carinfo">

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download