Accepting JSON calls

Permalink 1 user found helpful
Hello,

From my_single_page.php I want to post JSON data to an AJAX-handler. so first I made a controller file to handle this AJAX request in my_package/controllers/ajax.php with the following method:

public function say_whats_posted(){
        var_dump($this->post());
 }


and I route an URL to this method in my_package/src/Routehelper.php

//Route to AJAX handler
        Route::register(
            Router::route(array('/ajax', 'my_package')),
            '\Concrete\Package\my_package\Controller\Ajax::say_whats_posted'
        )


I tested this setup and say_whats_posted() does return an array of the posted variables when used Header application/x-www-form-urlencoded, but when I try this with the following JSON data

{name: 'John'}


it just returns an empty array.
array(0) { }


TL;DR : How do I make an ajax json handler function in concrete5.7?

 
MrKDilkington replied on at Permalink Reply
MrKDilkington
I am also interested in this topic.
JohntheFish replied on at Permalink Reply
JohntheFish
I think its because you are dumping a php array, not a json string.

Have a look at the ajax helper. It takes care of all of the header and json encoding for you.
titanve replied on at Permalink Reply
titanve
Hello,

<?php
    echo json_encode($this->post());


Try that!
iaezzy replied on at Permalink Reply
$data = json_decode($this->request->getContent(), true);