0

Hello guys I have a problem. And I don't know how to solve it. I am a beginner in ajax processing. I hope you can help me.

I have an ajax data from the success. And I want to put this in an array. Because I want to put the json data in an options select box.

Here's my code:

In my controller I have this

$('#state').on('change',function(){

            var state_code = $('#state').val();

            var city_url = '<?php echo site_url("locations/displayCity/' + state_code + '"); ?>';

            $.ajax({

                type: 'POST',
                url: city_url,
                data: '',
                dataType: 'json',
                async: false,
                success: function(i){

                    console.log(i)

                }

            });

        });

And here's the select box options that i need to fill using json data

<select id="city" name="city">
    <option value="">---Select City---</option>
</select>

Here's the json reponse

[{"id":"1054","name":"Altavas"},{"id":"1055","name":"Balete"},{"id":"1056","name":"Banga"},{"id":"1057","name":"Batan"},{"id":"1058","name":"Buruanga"},{"id":"1059","name":"Ibajay"},{"id":"1060","name":"Kalibo"},{"id":"1061","name":"Lezo"},{"id":"1062","name":"Libacao"},{"id":"1063","name":"Madalag"},{"id":"1064","name":"Makato"},{"id":"1065","name":"Malay"},{"id":"1066","name":"Malinao"},{"id":"1067","name":"Nabas"},{"id":"1068","name":"New Washington"},{"id":"1069","name":"Numancia"},{"id":"1070","name":"Tangalan"}]

In my console.log I have this:

[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
0: Object
1: Object
2: Object
3: Object
4: Object
5: Object
6: Object
7: Object
8: Object
9: Object
10: Object
11: Object
length: 12

proto: Array[0]

If I clicked the arrow in the objects I will get this:

Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
0: Object
id: "1028"
name: "Butuan City"
__proto__: Object
1: Object
id: "1029"
name: "Buenavista"
__proto__: Object
2: Object
3: Object
4: Object
5: Object
6: Object
7: Object
8: Object
9: Object
10: Object
11: Object
length: 12
__proto__: Array[0]

That's all guys. Thanks.

2
  • 4
    show your response data (json ) it will helpfull Commented Nov 27, 2013 at 7:00
  • Ok I will update my post Commented Nov 27, 2013 at 7:00

11 Answers 11

4

just replace

success: function(i){
    console.log(i)
}

with

success: function(data){
    $.each($.parseJSON(data),function(index,value){
        $('#city').append('<option value="'+value.id+'">'+value.name+'</option>');
    });
}
Sign up to request clarification or add additional context in comments.

2 Comments

JSON.parse(i) first so it will become object
I think the return value of my code is in object. Check my edit if I am right.
2

Your response is already an array. Just iterate over it using jQuery.each(i, function(index, item) {...})

1 Comment

its jQuery.each(array, function(index, item) {}) by the way
2

use this -

$.each(i, function(key,val){

 $('#city').append("<option value='" + key + ">" + val + "</option>");

});

Comments

2
  function(i){

     $.each(i,function(index,value){ 
       $("#city").append("<option value='"+value.id+"'>"+value.name+"</option>")
     });
  }

Comments

2

Don't use append by this it every time append on select box first make a string then set full html in select-box it is fast then append

var str='';
$.each(i, function(index,value){
str +="<option value='"+value.id+"'>"+value.name+"</option>";


});
 $('#city').html(str);

Comments

2

I understand when you console.log(i); you get the right response. Now what you need to do, is to JSON.parse the object and then set it on the select option.

With my experince, thats the tricky part, because select option can not be auto set by html.

So here is what might be some usable code(if you want something to be prefixed).

$(document).ready(function () {
    var size =    $('select').children('option').length;
    for (i=0;i<size;i++)
    {
        if ( $('select').children('option')[i].value === resultingObj.whatever)
        {
             $('select').children('option')[i].selected=true;
        }
    }
});

Good luck

Comments

2

try something like this

    $.ajax({
           type: 'POST',
           url: city_url,
           data: '',
           dataType: 'json',
           async: false,
           success: function(response){
            var resp_length = response.length;
            var option = '';
            for(var i = 0; i< resp_length;i++){
                option += '<option value="'+response[i].id+'">'+response[i].name+'</option>';
            }
            $('#city').append(option);//Opertation on DOM only one time.
           }
       });

Comments

2

Use following script

$.ajax({
  ...
  ...
  success: function(response){
    var option = null;
    //iterate each json record
    $(response).each(function(index, record){

      //create option tag with value and record name
      option = $('<li>').attr('value', record.id).html(record.name);

      //append this option tag to select box
      $('#city').append(option);
    });
  }

});

Comments

2

parse first your json to object then use $.each

success: function(i){
    json = JSON.parse(i);
    $.each(json,function(index,value){
        $('#city').append('<option value="'+value.id+'">'+value.name+'</option>');
    });
}

1 Comment

Doesn't append as well. I will try to create a fiddle.
1

From your code I modified it to do what you would like.

success: function(i)
{
var resultingObj = JSON.parse(i);

    for(var iterator = 0; iterator < resultingObj.length; iterator++)
    {
        //perform actions
        $('#city').append('<option value="' + resultingObj[iterator].id + '">' + resultingObj[iterator].name + '</option>');
    }
}

2 Comments

iterator is not a reserved word in javascript
Yeah running on very little sleep and caffeine. I'm working through it :P.
1

Try this-

var select=$('#city');
for (var j=0; j<i.length; j++)
{
   select.append('<option value="'+i[j].id+'">'+i[j].name+'</option>');
}

3 Comments

I dont think so, its working here: jsfiddle.net/A4fjL . By mistake i just used the variable name wrong :P
Ok I did that But it is not appending
What are you getting with console.log(i[0].id) ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.