I'm trying to work with ajax in symfony but is some hard for me. I have a form in twig where I get a value that I'm using for search a product in my database:
This is the form in twig:
<form id="myForm" method="post" action="{{ path('my_app_greeting') }}">
<div class="input-group">
<input id="name_id" name="name" type="text" class="form-control" placeholder="Buscar repuesto..." required />
<span class="input-group-btn">
<button id="search-button" class="btn btn-default" type="button">Buscar</button>
</span>
</div><!-- /input-group --></br>
</form>
This is my code using jquery in the same twig template for send the data with ajax:
$(document).ready(function(){
$("#myForm").submit(function(){
var value = $("#name_id").val();
$.ajax({
type: "POST",
data: { productValue: value },
url: "/ventas/test/ajax/"
})
.done(function(response){
template = response;
$('#output').html(template.content);
})
.fail(function(jqXHR, textStatus, errorThrown){
alert('Error : ' + errorThrown);
});
return false;
});
});
Later I read about how symfony works with ajax and I thought the best solution for my "problem" is create a new twig template called "ajaxContent.html.twig" for example and do this with the controller:
public function testAction()
{
$request = $this->get('request');
$name = $request->request->get('productValue');
$template = $this->renderView('AcmeDemoTwoBundle:Ventas:ajaxContent.html.twig', array('value' => $name));
$json = json_encode($template);
$response = new Response($json, 200);
$response->headers->set('Content-Type', 'application/json');
return new Response($response);
}
Of this way later I want to put all the html content inside my original template but I have a problem with json encode. I don't understand very well how it works and how is the better way for receive the data and show it in the twig template. How can I do this? ( I tried to show the data using $('#output').html(template.content);
but doesn't work).
Thanks for your help!