Ulises R.S. Ulises R.S. - 9 months ago 27
JSON Question

How te read Elements of WebService Response in Javascript

I'm new in Javascript, PHP and XML.
My question goes like this.
I'm using this web service http://www.webservicex.net/country.asmx?op=GetCountries
(This is the WSDL: http://www.webservicex.net/country.asmx?WSDL)
I'm using Jquery BTW.
And as part of my app, I'm trying to get every country from the response into an HTML select via Javascript.
But I can't find how to get access to every specific element of that response (countries).

These are my pieces of code so far:

PHP

<?php
$url1 = "http://www.webservicex.net/country.asmx?WSDL";
$client = new SoapClient($url1);
$Res = $client->GetCountries();
echo json_encode($Res);
?>


Javascript

Here I should populate the select when load, but I can't even get access to an element of the response so I'm just trying to print something in a div element for testing purposes.

window.onload = function() {
$.post("process.php", {}, function(response) {
var str_res = JSON.parse(response);
document.getElementById("Section2").innerHTML = str_res[1];
console.log(response);
}
}


I know that "str_res[1]" won't work, but that's exactly whay I'm trying to figure out. How do I access the response elements.
For example get "Aruba" and print it or add it to the select I mentioned.
I hope I was able to explain my concern, and thanks in advance!

Answer Source

Try this

test.html file

<html>
    <body>
        this is html page, wait to load result

        <select id="dropdown"></select>

        <script
                      src="https://code.jquery.com/jquery-3.1.1.min.js"
                      integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
                      crossorigin="anonymous"></script>
        <script type="text/javascript">
        $.post("test.php", {}, function(response) {
                var str_res = JSON.parse(response); 
               //   console.log(str_res);
                $.each(str_res, function(i, item) {
                    //console.log(str_res[i]);
                    //console.log('-------');   

                    $('#dropdown').append($('<option>', { 
                        value: str_res[i],
                        text : str_res[i] 
                    }));
                });


            });
        </script>


    </body>
</html>

test.php file

<?php
    $url1 = "http://www.webservicex.net/country.asmx?WSDL";
    $client = new SoapClient($url1);
    $Res = $client->GetCountries();

    $xml = simplexml_load_string($Res->GetCountriesResult);
    $data = array();
    foreach ($xml->Table as $key => $value) {
        array_push($data,(string)$value->Name);
    }

    //print_r($data);
    echo json_encode($data);
?>