Ajax with jquery in Symfony

0

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?

    
asked by juanitourquiza 05.08.2017 в 00:16
source

1 answer

1

on the route

ajaxordersku:
    path: /ajaxordersku
    defaults: { _controller: AppBundle:Admin:orderskufororderid }
    methods: [POST]

in the controller

public function orderskufororderidAction(Request $request)
{

            //$data = $request->get('idn');
            $data=$request->request->get('data');
//demás código...

to pass the value to the controller, you must send it in the ajax.

$.post("{{ url('ajaxordersku') }}",
    {
        "data": data //Aquí van las variables que deseas enviar
    },
    function(response, status){
        alert("respuesta " + response + "\nEstado: " + status);
    });

or also

$.ajax({
                             method: "POST",
                             url: "{{ url('ajaxordersku') }}",
                             dataType: 'json',
                             data: {
            "data": data //Aquí van las variables que deseas enviar
             },

to show the json in a table in twig you can use the method

$jsonArray = json_decode($json, true); // el segundo parámetro "true" para que retorne un array y no un objeto

and you pass the variable jsonArray in the render to twig and you handle it as an array.

    
answered by 10.11.2017 / 21:55
source