jeudi 13 août 2015

Working with $_POST from ajax in symfony controller

I'm beginner to symfony. I have a twig template with 2 buttons that calls an external .js that executes an ajax call.

Button 1 calls function 'delete', and this is the js code:

    var path = $("#abc").attr("data-path");
 /*grabs it from some div in the twig template.. <div id="abc" data-path="{{path('delete')}}"></div>*/

    function delete(n){
        $.ajax({
          type: "POST",     
          url: path,
          data: {id : n},
          "success":function(data){
          alert('ok');
          }
          });
    }

Button 2 calls function 'edit' which is the same code except that the 'url' goes to another 'action', and the 'data' is not a json, (it is data: formData)

Routing.yml for function delete is:

    delete:
        pattern:  /delete
        defaults: {_controller: TPMainBundle:Default:delete }  

And this is the controller action:

public function deleteAction()
    {
 $id = $_POST['id']; 
 /*other code to work with doctrine making queries to delete from database*/ 
}

(The js code is from a webpage done without symfony and it works fine)

I was told the right way to retrieve the POST in the action, reglardless it was whether a json or formData, was using the same that I used in PHP:

 $id = $_POST['id']; 

Here, I have 2 problems.

First, I don't know if this is correct because it doesn't work.

Second, I don't know how can I know if i'm retrieving the POST OK !!

When I did this without symfony, I checked if I was getting the POST with the command 'fwrite', because the ajax went to a PHP file instead of an Action, and then with the command fwrite I created a .txt file with the output of an echo to see if the $_POST was recovered or not.

But here in symfony I don't know how to check it, so I'm driving myself crazy.. trying to implement the solutions I read without being sure if they work..

and with the extra problem that since I'm newbie for me it's a bit confusing trying to install some external bundles for debug. Please help



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire