Victor Ribero Guasch Victor Ribero Guasch - 2 months ago 11
Ajax Question

Error getting data from POST ajax petition Symfony2

It has been a rough night and morning today hahaha. I'm trying to get some

data
with
symfony2
from an
AJAX
'POST'
petition.

Actually I want to sent an array and get it in the controller but I'm receiving an error like this variable is
null
. I think I'm trying to get it in a right way but... Let's take a look!

This is the JS AJAX petition, I'm getting the ul#sortable.children() order to update it on the dataBase, so I sent an array with the position and id.


example: ["1", "3", "2"]. So the object with id=1 in the db is going to be in the position 1. The element with id=3 is going to be in the position 2 and the element with id=2 is going to be in the position 3.


$('#ordenar').click(function(){
var $children = $('#sortable').children();
var numElementos = $children.length;
var socialSorted = [];

for(var i=0; i<numElementos; i++){
socialSorted.push($children[i].id);
}

$.ajax({
url: ' {{ path('admin_update_social_position') }} ',
datos: socialSorted,
method: 'POST'
}).done(function (data) {
if(data.type == 'OK'){
window.location.reload();
}
if(data.type == 'ERROR'){
$('#error-message').slideDown();
}
});
});


And here is the controller

/**
* @Route("/admin/update/order/social", name="admin_update_social_position")
*/
public function orderSocial(Request $request)
{
$em = $this->getDoctrine()->getManager();

$socialSorted = $request->request->get('socialSorted');
$numElementos = count($socialSorted);

for($i=0; $i<$numElementos; $i++)
{
$social = $em->getRepository('AppBundle:Social')->findById($socialSorted[$i]);
$social->setPosition($i+1);
$em->persist($social);
}

if (empty($socialSorted)) {
$this->sendResponseStatus('ERROR');

return new JSONResponse($this->getData());
}

$em->flush();

$this->sendResponseStatus('OK');

// Generamos los datos para la respuesta ajax
return new JSONResponse($this->getData());
}


I tried many ways... sending the array, sending a
JSON
with an array in and also different ways to get the data from the
controller
... any advice/solution?

Thanks you to all of you

Answer

Try this:

        $.ajax({
            url: ' {{ path('admin_update_social_position') }} ',
            data: {
                socialSorted: socialSorted,
            },
            method: 'POST'
        }).done(function (data) {
            if(data.type == 'OK'){
                window.location.reload();
            }
            if(data.type == 'ERROR'){
                $('#error-message').slideDown();
            }
        });

You need to send the data as an array. You ask for socialSorted key in request, but actually you don't send it

Comments