Ajax Json request failed

Hi,
Please could you help me???
I try to use ajax json to display data from mysql, but the request is allways failed.
Please, someone could help me ?
here is my code: using Zend 3.

In my controller:

public function remplirAction(){
    $data = $this->entityManager->getRepository(Entite::class)->findAll();
    $request = $this->getRequest(); 
    $query = $request->getQuery(); 
    if ($request->isXmlHttpRequest()) { 
        $jsonData = array(); 
        $idx = 0; 
        foreach($data as $sampledata) { 
            $temp = array( 
                'id' => $sampledata->getId(), 
                'nom' => $sampledata->getNom(), 
                'adresse' => $sampledata->getAdresse() 
            ); 
            $jsonData[$idx++] = $temp; 
        } 
        $view = new JsonModel($jsonData); 
        $view->setTerminal(true); 
    } else { 
        $view = new ViewModel(); 
    } 
    return $view; 
}

In my view (index.phtml):

<script language = "javascript"> 
  $(document).ready(function(){ 
    $("#loadbook").on("click", function(event){ 
      $.ajax({ 
        url: '/remplir', 
        type: 'POST', 
        dataType: 'json', 
        async: true, 

        success: function(data, status) { 
          var e = $('<tr><th>ID</th><th>Nom</th><th>Adresse</th></tr>'); 
          $('#book').html(''); 
          $('#book').append(e); 

          for(i = 0; i < data.length; i++) { 
            book = data[i]; 
            var e = $('<tr><td id = "id"></td><td id = "nom"></td><td id = "adresse"></td></tr>'); 
            $('#id', e).html(book['id']); 
            $('#nom', e).html(book['nom']); 
            $('#adresse', e).html(book['adresse']); 
            $('#book').append(e); 
          } 
        }, 
        error : function(xhr, textStatus, errorThrown) { 
          alert('Ajax request failed.'); 
        } 
      }); 
    }); 
  }); 
</script>

Thanks in advance Guys.

That’s not much to help you with. I’m guessing you get that specific error message from javascript as an alert.

  • I suggest to use console.log and dump the request details instead of an alert popup. Maybe it gives some more details about what exactly fails.
  • Also check your application/php/server log. Maybe there are more hints.
  • You can check if that url is actually working (maybe the route is not configured correctly or the query throws an exception). curl or phpstorm and it’s rest client might help out.