javascript - poltergeist: jquery ajax does not accept one of two equals responses
working with symfony 2.8 I'm trying to make an AJAX call to a controller that returns a JSON that contains one array.
CONTROLER:
public function seguimientoAction(Request $request){
$idUnico = $request->query->get('plan-id');
$em = $this->getDoctrine()->getManager();
$idPlan = $em->getRepository('UsuariosBundle:Plan')->findOneByIdUnico($idUnico);
$seguimientos = $em->getRepository('UsuariosBundle:Seguimiento')->findByPlan($idPlan);
$contenedor = array();
foreach ($seguimientos as $seguimiento){
$fecha = $seguimiento->getFecha();
$fecha = $fecha->format('d-m-y');
$peso = $seguimiento->getPeso();
$contenedor[] = ['fecha' => $fecha, 'peso' => $peso];
}
return new JsonResponse($contenedor);
}
JAVASCRIPT:
var selectorSeguimiento = $(".plan-seguimiento");
selectorSeguimiento.click(function(event){
event.preventDefault();
var planid = $(this).attr("data-id");
$.ajax({
type: "POST",
dataType: 'json',
ContentType: 'application/json',
url: Routing.generate('usuarios_dashboard_planes_seguimiento', {planid}),
success: function(data){
console.log(data);
If I write the url that call the controller in the browser I can see this:
[{"fecha":"26-02-18","peso":"67.0"},{"fecha":"28-02-18","peso":"66.0"},{"fecha":"03-03-18","peso":"64.0"}]
So, I understand that the problem is that javascript doesn't take the data..., but... ...If I change the array in controller and I make an identical array "artesanal way"...
CONTROLER(test):
{-code-3}
...I receive this:
Array(3) [ {…}, {…}, {…} ] localhost:90:25
Array(3) [ "67.0", "66.0", "64.0" ] localhost:99:25
Array(3) [ "26-02-18", "28-02-18", "03-03-18" ] localhost:100:25
And for additional check, I turn back to call with the browser and I obtain this:
[{"fecha":"26-02-18","peso":"67.0"},{"fecha":"28-02-18","peso":"66.0"},{"fecha":"03-03-18","peso":"64.0"}]
Exactly the same that the other case
So, the question is, Why does jquery ajax method "likes" the response with the second array and it "dislikes" the first one (being the same array)?
EDIT: Here you can see a var_dump() of the arrays before the json_encode():
Array $contenedor
{-code-4}
Array $miarray
{-code-4}
Answer
Answer
Answer
Answer
Solution:
You should pass params to
Routing
as a valid javascript object, changing this line:Routing.generate('usuarios_dashboard_planes_seguimiento', {planid})
by:
Routing.generate('usuarios_dashboard_planes_seguimiento', {'plan-id': planid})
Answer
Solution:
Have a look at the headers of the request. Is the content-type returned by the server, the same in both instances?
You could also try removing dataType: 'json' for a moment to let jquery "Guess"