I am currently trying to find an address based on zip code using Ajax.
When I execute it, it returns an unexpected display. Instead of having a list of addresses with a search form, the list is repeated several times until it returns an error.
Can anyone provide any clarification?
The file :index.html.twig
<div class="loading"></div>
{% include 'LesproduwebBundle:Adresse:index.html.twig' with {'entities':entities } %}
<script>
$(".loading").hide();
$("#form_recherche").submit(function(){
$(".loading").show();
var codePostal = $("#codepostal").val();
var DATA = 'codePostal=' + codePostal;
$.ajax({
type: "POST",
url: "{{ path('adresse_recherhe')}}",
data: DATA,
cache: false,
success: function(data){
$('#resultats_recherche').html(data);
$(".loading").hide();
}
});
return false;
});
</script>
The Controller
public function rechercherAction()
{
$request = $this->container->get('request');
if($request->isXmlHttpRequest())
{
$codePostal = '';
$codePostal = $request->request->get('codePostal');
$em = $this->container->get('doctrine')->getEntityManager();
if($codePostal != '')
{
$qb = $em->createQueryBuilder();
$qb->select('a')
->from('LesproduwebBundle:Adresse', 'a')
->where("a.codePostal LIKE :codePostal")
->setParameter('codePostal', '%'.$codePostal.'%');
$query = $qb->getQuery();
$entities = $query->getResult();
}
else {
$adresse = $em->getRepository('LesproduwebBundle:Adresse')->findAll();
}
return $this->container->get('templating')->renderResponse('LesproduwebBundle:Adresse:index.html.twig', array(
'entities ' => $entities
));
}
else {
return $this->indexAction();
}
</div>