Search code examples
phpjqueryajaxxmlquickblox

Parse the xml response Strange


I am trying to send request to an api by what i get response is strange one.

I am attaching the response as image.

enter image description here

Here is the Real XML Response in text

<data type="array" class_name="Location" skip="0" limit="0">
  <Location>
    <_id>558a8325535c1246bb00d5c5</_id>
    <_parent_id>test-api</_parent_id>
    <created-at type="integer">1435140901</created-at>
    <lat type="float">11.0270643</lat>
    <location>Avarampalayam, Coimbatore, Tamil Nadu, India</location>
    <long type="float">76.9830277</long>
    <updated-at type="integer">1435140901</updated-at>
    <user-id type="integer">3566216</user-id>
  </Location>
  <Location>
    <_id>558a83dd535c12843900dbbe</_id>
    <_parent_id>test-api</_parent_id>
    <created-at type="integer">1435141085</created-at>
    <lat type="float">11.0310806</lat>
    <location>Mettupalayam Bus Stand, Mettupalayam Road, Tatabad, Coimbatore, Tamil Nadu, India</location>
    <long type="float">76.9525282</long>
    <updated-at type="integer">1435141085</updated-at>
    <user-id type="integer">3566216</user-id>
  </Location>
</data>

Which comes under #document

How can i fetch the values in the above given response?

Here is the way i use to request

$.ajax({
    url: 'https://api.quickblox.com/data/Location',
    data: { token:'662d3330f192b4af77d5eef8de58f7e8c01a12a7' },
    method: 'get',
    success: function(msg) {
        var value = msg;
        console.log(msg);
    }
})

Solution

  • You can use jQuery's standard DOM traversal functions on the returned XML to retrieve the values you require. Try this:

    $.ajax({
        url: 'https://api.quickblox.com/data/Location',
        data: {
            token:'662d3330f192b4af77d5eef8de58f7e8c01a12a7'
        },
        method: 'get',
        dataType: 'xml', // note this is optional as jQuery should detect and parse it for you automatically
        success: function(xml) {
            $(xml).filter('data').find('Location').each(function() {
                var id = $(this).find('_id').text();
                var parentId = $(this).find('_parent_id').text();
                var createdAt = new Date($(this).find('created-at').text());
                var lat = parseFloat($(this).find('lat').text());
                // retrieve the other properties...
    
                // work with them here...
            });            
        }
    });