skip to Main Content

I’m trying to concatenate and return all 94 results into #title1.

All of the code below is working correctly in terms of displaying the information when ran, but rather than having 94 lines for each country returned when the user clicks the button. Im trying to get it to loop on the countryName tag and add to an array of results that is then pushed to #title1 once the looping comes to an end at country 94.

Any help?

$('#PostalCodeCountryInfoBtn').click(function() {

    $.ajax({
        url: "libs/php/getPostalCodeCountryInfo.php",
        type: 'GET',
        dataType: 'json',
        
        success: function(result) {

            console.log(JSON.stringify(result));

            if (result.status.name == "ok") {

                $('#title1').html(result['data'][0]['countryName'] + " " + result['data'][1]['countryName']);
                $('#title2').html(result['data'][1]['countryName']);
                $('#title3').html(result['data'][2]['countryName']);
                $('#title4').html(result['data'][3]['countryName']);
                $('#title5').html(result['data'][4]['countryName']);
                $('#title6').html(result['data'][94]['countryName']);

            }
        
        },
        error: function(jqXHR, textStatus, errorThrown) {
            // error code
        }
    }); 

});

2

Answers


  1. You can try something like this
    This will loop through the result.data array and select the country name per and appends it to title 1

    $('#PostalCodeCountryInfoBtn').click(function() {
    
    $.ajax({
        url: "libs/php/getPostalCodeCountryInfo.php",
        type: 'GET',
        dataType: 'json',
        
        success: function(result) {
    
            console.log(JSON.stringify(result));
             
            if (result.status.name == "ok") {
                if(result.data.length > 0){
                  for(var i = 0; i < result.data.length; i++){
                    $('#title1').append(result['data'][i]['countryName'])
                  }
                }
          }
        
        },
        error: function(jqXHR, textStatus, errorThrown) {
            // error code
        }
    }); 
    
    });
    
    Login or Signup to reply.
  2. If you want it all one line it is a simple map and join.

    var names = result['data'].map(function(country){return country.countryName}).join(" ");
    $('#title1').text(names);
    

    If you have 94 different elements you can loop over the elements (using a common class)

    $(".commonClass").text(function (index) {
      return result['data'][index].countryName;
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search