Ulises R.S. Ulises R.S. - 1 year ago 51
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:


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


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];

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

        this is html page, wait to load result

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

        <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) {

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



test.php file

    $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) {

    echo json_encode($data);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download