I have the following code:
On the route I defined it like this:
ajaxordersku:
path: /ajaxordersku
defaults: { _controller: AppBundle:Admin:orderskufororderid }
methods: [GET]
In the controller that you belong to the path defined above, I have this:
public function orderskufororderidAction(Request $request)
{
//$data = $request->get('idn');
$data=$request->query->get('data');
if($request->isXmlHttpRequest())
{
$encoders = array(new JsonEncoder());
$normalizers = array(new ObjectNormalizer());
$serializer = new Serializer($normalizers, $encoders);
$em = $this->getDoctrine()->getManager();
$dql = "select os
from BackendBundle:Orderskus os
where os.ordersOrderid=:ordersOrderid";
$query=$em->createQuery($dql);
$query->setParameter('ordersOrderid', 1);
$posts=$query->getResult();
$response = new JsonResponse();
$response->setStatusCode(200);
$response->setData(array(
'response' => 'success',
'posts' => $serializer->serialize($posts, 'json')
));
return $response;
}
}
and in javascript with jquery this:
<script>
$(function(){
console.log('desperate for');
var buttonOrders = $('#idn');
buttonOrders.click(function(evt){
var data = {request : $('#idn').val()};
$.ajax({
method: "GET",
url: "{{ url('ajaxordersku') }}",
dataType: 'json',
data: {
"data": "some_var_value"
},
success: function(data)
{
if(data.hasOwnProperty("response") && data.response === "success")
{
if(data.hasOwnProperty("posts"))
{
//http://stackoverflow.com/questions/3710204/how-to-check-if-a-string-is-a-valid-json-string-in-javascript-without-using-try/3710226
if (/^[\],:{}\s]*$/.test(data.posts.replace(/\["\\/bfnrtu]/g, '@').
replace(/"[^"\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, '')))
{
var posts = JSON.parse(data.posts);
if(posts.length > 0)
{
var html = "";
for(d in posts)
{
html += "<p>" + JSON.stringify(posts[d]) + "</p>";
}
$("#containerajaxordersku").append(html);
}
}
else
{
console.log("INVALID JSON STRING");
}
}
else
{
console.log("POSTS NOT FOUND");
}
}
},
error: function(jqXHR, exception)
{
if(jqXHR.status === 405)
{
console.error("METHOD NOT ALLOWED!");
}
}
});
});
});
</script>
After crushing the button:
<button id="idn" class="btn btn-primary btn-orders" data-orders={{ordenes.orderid }}>Click for Details Order</button>
Show me this:
Two things are pending: How do I pass the value of the button to the controller, to use the variable $ data? What is missing to pass that value from javascript?
And how do I show the json code in a table in twig, or do I modify it in jquery so that I can present it in a table?