简体   繁体   中英

Symfony2 controller and Javascript argument passing

I am developing an application using symfony2. I would like to know how I can receive arguments from a template in a controller because I want to store the value of the argument in the data base. The argument will get its value in a JavaScript script inside the template and must be passed to the controller when submitting a button. This is the script:

$("MatchedTag").click(function () 
 {
       $(this).toggleClass("highlight");

       var IdOfTag = this.id;  

 }); 

The variable I want to receive in the controller is IdOfTag. How can I do this? Thanks.

In our applications we use two approaches.

First approach

First approach is to create the "configuration" file in twig, that would be included somewhere in header. This file contains all JS variables you would need in the script. These values of these variables are passed from the controller. Then in twig template of the "parameters" file you simply add them in appropriate places:

   <script>
       myObj.var = "{{ var_from_controller }}";
   </script>

Second approach

Another approach is to put needed variables into additional custom attributes of html tag. We usually do it, when we need to take certain route.

   <p id="myDataHolder" data-src="{{ path('MyUserBundle_ajax_route') }}">blah</p>

And then, in your JS you just parse an attribute of that tag.

You can pass the variable using AJAX (take a look at $.ajax , $.post , $.get - jQuery) or add a hidden input field to form with the desired value.

Example

If you want to pass IdOfTag to /path/controller/tags (as example) using jQuery.ajax your code will looks like this:

$("MatchedTag").click(function () 
 {
       $(this).toggleClass("highlight");

       var IdOfTag = this.id;  
       $.ajax({
          url: "/path/controller/tags",
          type: "POST",
          data: { "tag_id" : idOfTag },
          success: function(data) {
             //(success) do something...
             //variable "data" contains data returned by the controller. 
          }
       });
});

Then in the controller you can get the value of idOfTag through $_POST["tag_id"]

Good look and check the links above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM