0

When I pass the json request in ajax url following error occur. I have pass the 200 and above datas in ajax. All my data's come from "/search/searchendpoint" url

controller:

$searchitem = $this->MbPriceList->find('all' , [
  'fields' => [
    'id', 
    'name' => 't1.item_name'
  ],  
  'join' => [
     'table' => 'mb_item_list', 
     'alias' => 't1', 
     'type' => 'INNER', 
     'conditions' => [
       't1.item_code = MbPriceList.item_code'
     ]
  ] 
]) ->toArray();

$this->set([
  'response' => $searchitem,
  '_serialize' => ['response']
]);

JSON request:

<script>
  var myUrl = "/search/searchendpoint";
  $.mockjax({ 
    url: myUrl, 
    dataType: "json",            
    type: "get", 
    data: JSON.stringify(myUrl), 
    contentType: 'application/json; charset=utf-8', 
    response: function(data){
      alert(data) 
    }
  });
</script>
<script>
  $('#search').typeahead({
    ajax: '/search/searchendpoint'
  });
</script>

Error:

jquery-2.2.4.min.js:2 Uncaught TypeError: Cannot use 'in' operator to
search for 'length' in "/search/searchendpoint" at s
(jquery-2.2.4.min.js:2) at Function.each (jquery-2.2.4.min.js:2) at
isMockDataEqual (jquery.mockjax.js:67) at getMockForRequest
(jquery.mockjax.js:119) at Function.handleAjax [as ajax]
(jquery.mockjax.js:444) at Typeahead.execute
(bootstrap-typeahead.js:170) at f (jquery-2.2.4.min.js:2)

Jordan Kasper
  • 13,153
  • 3
  • 36
  • 55
Ganesh
  • 89
  • 6
  • I would guess that maybe your response data is not the format that typeahead is expecting. It would be helpful to see what actual JSON is generated by your controller. Also where does mockjax come into this? Are you testing the real controller, or not? – ADyson Oct 12 '17 at 09:15
  • Yes I'm already tested my controller.. json value is displayed correctly – Ganesh Oct 12 '17 at 09:40
  • So this result happens when using using mockjax instead of the real code? In which case why did you show us the controller code? It doesn't get used if you're mocking the ajax call. Your mockjax definition seems to be lacking any kind of mock result object, perhaps that's the problem. – ADyson Oct 12 '17 at 09:49

1 Answers1

0

try this. you have to echo out your variables that you intent to pass as a response to your view as JSON and then, very !important, exit the controller's code.

$this->set(['response' => $searchitem,'_serialize' => ['response']]);
echo json_encode('response');
exit();

and in your javascript you have to read that json, assuming you are using jquery you catch your php variable as a parameter on the success function, try this.

$ajax({
    type:"POST",
    data:data,
    url:URL,

    success:function(data){
        var jsresponse = $.parseJSON(data).response;
    }
});

Let me know if that worked for you. Cheerios !!

Rod
  • 96
  • 1
  • 3