0

Im new to JQuery AJAX thing, this is my script:

$(document).ready(function() {
  $("#city").change(function() {

    var city_id = $("#city").val();

    if (city_id != '') {
      $.ajax({
        type: "POST",
        url: "<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id,
        success: function(block_list) {
          // WHAT TO PUT HERE ?
        },
      });
    }
});

If i put console.log(block_list) it returns the right data with JSON type:

[{"id":"1601","id_city":"16","block":"A"},
{"id":"1602","id_city":"16","block":"B"}]

What is the correct way to loop the returned data? I did this to see what the loop returned:

$.each(block_list, function() {
  $.each(this, function(index, val) {
    console.log(index + '=' + val);
  });
});

But it was totally messed up :(, if the looped data is correct I also want to put the id as a value and block name as a text for my <option> tag how to do that? thank you.

UPDATE

Sorry, I have try both answer and its not working, I try to change my code to this:

$("#city").change(function(){

        var city_id = $("#city").val();

        $.get("<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id, function(data) {
          $.each(data, function(id, val) {
            console.log(val.id);
          });
        });

      });

it returns :

**UNDEFINED**

I also try to change it into val[id] or val['id'] still not working, help :(

3 Answers 3

2
$.each(block_list, function(id, block){
    console.log('<option value="' + block['id'] + '">' + block['block'] + '</option>')
});

The output would be:

<option value="1601">A</option>
<option value="1602">B</option>
Sign up to request clarification or add additional context in comments.

Comments

0

try something like:

success: function(data, textStatus, jqXHR) {
    if (typeof(data)=='object'){
          for (var i = 0; i < data.length; i++) {
            console.log(data[i].id + ':' + data[i].id_city);
           }
    }
}

Comments

0

if ur json output is in this format

[{"id":"1601","id_city":"16","block":"A"},
{"id":"1602","id_city":"16","block":"B"}]

then

var city_id = $("#city").val();
if (city_id != '') {
  $.ajax({
    type: "POST",
    url: "<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id,
    success: function(data) {
            $.each(data, function(index) 
            {
                console.log(data[index]['id']);
                $('#'+ddname+'')
                .append($("<option></option>")
                .text(data[index]['id']+"-"+data[index]['block']));
            });
    },
  });
}

Comments

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.