0

I want to provice and country_id together in view via json_encode but it's show the message [object] [object]

public function get_province()
{
    $country_id=$this->input->post('country_id');
    $provinces=$this->ajax->get_province($country_id);

    if(count($provinces)>0)
    {
        $pro_select_box='';
        $pro_select_box .='<option value="">-Select Province-</option>';
        foreach($provinces as $province)
        {
            $pro_select_box .='<option value="'.$province->province_id.'">'.$province->province_name.'</option>';
        }
        $cid=$province->province_id;
        $data=array(
            'pro'=>$pro_select_box,
            'cid'=>$cid
        );

        echo json_encode($data);
    }
}

Here is the javascript:

$.ajax({
    url:"get_province",
    type:"POST",
    data:{'country_id':country_id},
    dataType:'json', success:function(data){
        $('#province').html(data);
        $('#cid').val(data);
    },
    error:function(){ alert('Errror'); }
});
6
  • Are you decoding it? Commented Sep 13, 2017 at 15:31
  • Possible duplicate of How can I parse a JSON file with PHP? Commented Sep 13, 2017 at 15:31
  • Are you by any chance using alert for debugging instead of the console. Commented Sep 13, 2017 at 15:34
  • data is object so: $('#province').html(data.pro); $('#cid').val(data.cid); Commented Sep 13, 2017 at 15:42
  • maybe this link will help you'r problem stackoverflow.com/a/12056253/6768455 Commented Sep 13, 2017 at 15:45

1 Answer 1

0

You are getting back JSON data and trying to output it to the page as HTML. You have to build some appropriate HTML in javascript using your JSON data from the server, and then write that to the page. Something like:

success:function(data){
    $('#province').html(data.pro);
    $('#cid').val(data.cid);
}

Also worth a mention: your current setup builds the HTML in PHP and then passes it back to javascript to add to the page. You're probably better off simply passing the data down (i.e. the list of provinces) and then letting javascript build the HTML and add it to the page.

Also, you have no code to handle the possibility that there won't be any provinces found. That may be an issue for you in the long run.

Sign up to request clarification or add additional context in comments.

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.