-1

I am working on a CakePHP 2.x app and trying to implement JSONP. It's my first time, so I don't know how can I do this:

$(function(){
 $.getJSON("https://www.example.com/myweb/api/getjsonp&jsoncallback=?",
 function(data){
    console.log(data);
    }
     );

        });

Controller:

public function getjsonp(){

$id = $this->Auth->user('idUser');
$messages = $this->Contact->getMessages($id);


$totalmessages = json_encode($messages);
echo $_GET['jsoncallback'] . '(' . $totalmessages . ')';

}

The code isn't working. Am I missing something?

caitlin
  • 2,769
  • 4
  • 29
  • 65
hellosheikh
  • 2,929
  • 8
  • 49
  • 115

2 Answers2

0

maybe you haven't open this in php try add this code at the top of php file

header("Access-Control-Allow-Origin: *");

BlackLaw
  • 37
  • 3
0

You are probably not rendering the correct layout/view. See this page on using Json and Xml views.

Steps:

  1. Add Router::parseExtensions('json'); to your router.php file.
  2. Load RequestHandlerComponent in your (App)Controller.
  3. Create a View (named app/View/Api/json/getjsonp.ctp).
  4. Fill View with:

    <?php
    $totalmessages = json_encode($messages);
    echo $_GET['jsoncallback'] . '(' . $totalmessages . ')';
    
  5. Pass $messages from controller like this:

    public function getjsonp() {
      $id = $this->Auth->user('idUser');
      $messages = $this->Contact->getMessages($id);
    
      $this->set(compact('messages'));
    }
    
  6. Change url from:

    https://www.site.com/myweb/api/getjsonp&jsoncallback=?

    to

    https://www.site.com/myweb/api/getjsonp.json&jsoncallback=?.

    Note the .json.

tersmitten
  • 1,310
  • 1
  • 9
  • 23
  • i didnt get the documnentation ... there is not any example there ..only explanation in plain english – hellosheikh Jul 29 '13 at 19:25
  • not working ... when i typed the url in the browser .. it cant find the class – hellosheikh Jul 30 '13 at 11:09
  • Did you add `Router::parseExtensions('json')`? – tersmitten Jul 30 '13 at 11:50
  • yup i have added ... when i try the url of my code which i have written in my question into the browser .. i can see the result .bot not in console tab in firebug ... but your code is not coding.it is not going to the correct url – hellosheikh Jul 30 '13 at 11:54