0

It might be a duplicate question but I am stuck with parsing json. Since I am intermediate with jQuery so I fall to the problem.

I am implementing autocomplete with CakePhp.

my response function returns correct json. Here is my function

    public function jsonSongs() {
        $json_output = '';
        $role = $this->Auth->user('role');
        $userId = $this->Auth->user('id');
        $condition = array("Song.name LIKE " => "%" . $this->request->data['Song_name'] . "%");
        $song_name = $this->Song->find('list', array('conditions' => $condition, 'limit' => $this->request->data['Song_maxRows'], 'recursive' => '-1', 'order' => 'Song.name'));
        foreach ($song_name as $key => $name) {
            $json_output[] = array("id" => $key, "label" => $key." - ".$name, "value" => $name);
        }
        echo json_encode($json_output);
        $this->layout = $this->autoLayout = $this->autoRender = false;
    }

Returned json is

[{"id":8,"label":"8 - .Dhal gayaa aafataab ai saaqii","value":".Dhal gayaa aafataab ai saaqii"},{"id":32,"label":"32 - a.nga.DaaI par a.nga.DaaI letii hai raat judaaI kii","value":"a.nga.DaaI par a.nga.DaaI letii hai raat judaaI kii"},{"id":34,"label":"34 - aa.Nkh ko jaam samajh baiThaa thaa a.njaane me.n","value":"aa.Nkh ko jaam samajh baiThaa thaa a.njaane me.n"},{"id":35,"label":"35 - aa.Nkh se aa.Nkh milaa baat banaataa kyuu.N hai","value":"aa.Nkh se aa.Nkh milaa baat banaataa kyuu.N hai"},{"id":36,"label":"36 - aa.Nkh se duur naa ho dil se utar jaayegaa","value":"aa.Nkh se duur naa ho dil se utar jaayegaa"},{"id":37,"label":"37 - aa.Nkho.n kaa thaa qasuur naa dil kaa qasuur thaa","value":"aa.Nkho.n kaa thaa qasuur naa dil kaa qasuur thaa"},{"id":38,"label":"38 - aa.Nkho.n me.n jal rahaa hai kyuu.N bujhataa nahii.n dhu.Naa","value":"aa.Nkho.n me.n jal rahaa hai kyuu.N bujhataa nahii.n dhu.Naa"},{"id":39,"label":"39 - aa.Nkho.n se yuu.N aa.Nsuu .Dhalake","value":"aa.Nkho.n se yuu.N aa.Nsuu .Dhalake"},{"id":40,"label":"40 - aadamii aadamii ko kyaa degaa","value":"aadamii aadamii ko kyaa degaa"},{"id":41,"label":"41 - aae hai.n samajhaane log","value":"aae hai.n samajhaane log"},{"id":43,"label":"43 - aah ko chaahiye ik umr asar hone tak","value":"aah ko chaahiye ik umr asar hone tak"},{"id":44,"label":"44 - aaho.n me.n hai asar magar farq asar asar me.n hai","value":"aaho.n me.n hai asar magar farq asar asar me.n hai"}]

and finally my jquery function is ..

           $(function () {
            function log(message) {
                $("<div/>").text(message).prependTo("#log");
                $("#log").scrollTop(0);
            }

            $("#song").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        minLength: 2,
                        method: "post",
                        url: "<?php echo HTTP_PATH; ?>/songs/jsonSongs",
                        dataType: "jsonp",
                        data: {
                            'Song.maxRows': 12,
                            'Song.name': request.term
                        },
                        success: function (data) {
                        var obj = $.parseJSON(data);
                        alert( obj.id === "8" );
                            response($.map(data, function (item) {
                                return {
                                    label: item.label,
                                    value: item.id
                                }
                            }));
                        }
                    });
                },
                select: function (event, ui) {
                    log(ui.item ?
                        "Selected: " + ui.item.label :
                        "Nothing selected, input was " + this.value);
                },
                open: function () {
                    $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
                },
                close: function () {
                    $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
                }
            });
        });

I want to show suggestion and when user click on any it just writed to hidden text box. I can't even alert my json.

1 Answer 1

2

If your ajax request url is on same domain then do the followings and check

  1. change dataType: "jsonp", to dataType: "json",
  2. Add header('Content-type: application/json'); before echo json_encode($json_output);
  3. Remove var obj = $.parseJSON(data); alert( obj.id === "8" ); No need to parse

jsFiddle

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

4 Comments

it halts me with error in FireBug console. TypeError: e is undefined
I have done this n (result) { var data = $.parseJSON(result); response($.map(data, function (item) { // console.log(item.id + " - "+item.label); return { label: item.label, value: item.id } })); } THough issue is solved but how can I write it to hidden text box.
What you want to store in hidden text?, if you want to store label then you can do like this $('#hiddenInputId').val(item.label); replace hiddenInputId with your hidden input id and this will set last item label as hidden input value
I have seleceted it as correct but I had to add the statement ` var obj = $.parseJSON(data);` else it halts me with error I have mentioned in my first comment.

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.