2

I have an array of tags and I want to test them on Instagram to get media_count. Then I want to send the data I get to my symfony controller. This code is working and I reach the alert in my Success function.

for (var i = 0; i < 1; i++) {
    var tagname = tags[i];      
    var url = "https://api.instagram.com/v1/tags/" + tagname + "?client_id=" + clientID;
    $.ajax({
        type: "GET",
        dataType: "jsonp",
        cache: false,
        url: url,
        success: function (res) { 
            var data = "{'name':'" + res.data.name + "','count':'" + res.data.media_count + "'}";
            $.ajax({  
                type: "POST",  
                url: controller-url, 
                data: data,
                success: function(response) {
                    alert(data);
                    
                }
            });             
        }
    });     
}   

Then I use the solution in this answer to decode my data in controller, like this:

public function createAction(Request $request) {
    $params = array();
    $content = $this->get("request")->getContent();
    $params = json_decode($content, true); // 2nd param to get as array
    ...
} 

But when I try to send $params to a template, it is empty. Why is that, and what am I doing wrong?

Community
  • 1
  • 1
tofu
  • 311
  • 5
  • 11

2 Answers2

2

2 years late, but I had the same problem today and found this unanswered question :

In your callback function, assuming your data is correctly stringified (it looks like so), you forgot to specify the contentType:"application/json"

success: function (res) {
    var data = "{'name':'" + res.data.name + "','count':'" + res.data.media_count + "'}";
        $.ajax({  
            type: "POST",
            contentType : 'application/json',
            url: controller-url, 
            data: data,
            success: function(response) {
                alert(data);

            }

Otherwise, in your Symfony Controller, if you return :

$req->headers->get("Content-Type")

...you'll see that it's been sent with the default x-www-form-urlencoded

Hope it'll help someone in the future.

Yow
  • 63
  • 8
2

I looked this:

public function createAction(Request $request) {
    $params = array();
    $content = $this->get("request")->getContent();
    $params = json_decode($content, true); // 2nd param to get as array
   ...
}

The problem is that you don't take the $request from the function createAction.

public function createAction(Request $request) {
    $params = array();
    $content = $request->getContent();
    if (!empty($content)) {
        $params = json_decode($content, true);
    }
   ...
}

Now you'll get the JSON content from $request.

Cheers!

Harold29
  • 23
  • 2