skip to Main Content

I’m trying hit the API over jquery ajax with the URL and parameter with post method. here I’m checking delivery is available or not for the given Pincode for one of e-com website,please help me out on how to check or receive data from the API response.

My Script :

<script type="text/javascript"> 
$(document).ready(function () {
    $('#check').click(function(){
        var api_url = 'http://example.com/webservices/b2cpincodecheck.jsp';
        var key = '4A8DA5E635656'; 
        var pincode = 604408 ;

        if(pincode=="") {
            alert("please enter the pincode");
        } else {
            $.ajax({
                url:api_url+"?reqid="+key+"&pincode="+pincode,
                dataType: "text/json",
                type: "POST",
                success: function(result){
                    //console.log(result);
                    if(result) {
                        alert("Delivery is available!");
                    } else {
                        alert("Delivery is not available!");
                    }
                }
            })
        }  
    });
});
</script> 

As per the API response in the given document, I would get data in XML format

Their response :

<response>
<result>successful</result>
<pinCode>604408</pinCode>
<ouCode>abc</ouCode>
</response>

Please help me out on how to check or receive data from the API response.
Thanks in advance.

2

Answers


  1. jQuery AJAX Method is to load data from external website by calling APIs, and get the response in JSON or XML formats. this example shows you how easy it is to make such API calls in jQuery AJAX.something like this

    $(document).ready(function () {
        $("#submit").click(function (e) {
            var validate = Validate();
            $("#message").html(validate);
            if (validate.length == 0) {
                $.ajax({
                    type: "POST",
                    url: "http://api.openweathermap.org/data/2.5/weather?id=" + $("#citySelect").val() + "&appid=API-KEY&units=metric",
                    dataType: "json",
                    success: function (result, status, xhr) {
                        var table = $("<p>Weather Description</p>");
    
                        table.append("<p>City:</p>" + result["name"] + "</p>");
                        table.append("<p>Country:</p>" + result["sys"]["country"] + "</p>");
                        table.append("<p>Current Temperature:</p>" + result["main"]["temp"] + "°C</p>");
                        table.append("<p>Humidity:</p>" + result["main"]["humidity"] + "</p>");
                        table.append("<tr><td>Weather:</p>" + result["weather"][0]["description"] + "</p>");
    
                        $("#message").html(p);
                    },
                    error: function (xhr, status, error) {
                        alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
                    }
                });
            }
        });
    

    To get result <div id="message"></div>

    Login or Signup to reply.
  2. $(document).ready(function () {
        $('#check').click(function(){
            var api_url = 'http://example.com/webservices/b2cpincodecheck.jsp';
            var key = '4A8DA5E635656'; 
            var pincode = 604408 ;
    
            if(pincode=="") {
                alert("please enter the pincode");
            } else {
                $.ajax({
                    url:api_url+"?reqid="+key+"&pincode="+pincode,
                    dataType: "xml",
                    type: "POST",
                    success: function(result, status, jqXHR){
                        console.log(loadData(result || jqXHR.responseText))
                    }
                })
            }
        });
    });
    
    function loadData(xml) {
      var incubator;
      if (typeof xml === "string") {
        incubator = document.createElement("div");
        incubator.innerHTML = xml;
      } else {
        incubator = xml;
      }
      return {
        "response": {
          "result": incubator.querySelector("result").textContent,
          "pinCode": incubator.querySelector("pinCode").textContent,
          "ouCode": incubator.querySelector("ouCode").textContent,
        }
      }
    }
    
    function xmlToObject(xml) {
      var incubator = document.createElement("div");
      incubator.innerHTML = xml;
      return Array.prototype.map.call(incubator.childNodes, nodeToObject)
    }
    
    function nodeToObject(node) {
      if (node.nodeType === Node.ELEMENT_NODE) {
        return {
          nodeName: node.nodeName.toLowerCase(),
          attributes: nodeAttributesToObject(node),
          childNodes: Array.prototype.map.call(node.childNodes, nodeToObject)
        };
      }
      if (node.nodeType === Node.TEXT_NODE) {
        return node.textContent;
      }
    }
    
    function nodeAttributesToObject(node) {
      var result = {};
      Array.prototype.forEach.call(node.attributes, function (attr) {
        result[attr.name] = attr.value;
      });
      return result;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    Here is two example of data extraction from xml :

    1. the function loadData get exaclty the field you expect
    2. the function xmlToObject can help you to walk an XML as if it was a simple JavaScript object.

    Please be careful: jQuery ajax setting dataType should be empty or the direct format (ie: "json", not "text/json"), here you should set it to "xml".

    Hope it will help you!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search