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.
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.
Share Improve this question edited Sep 20, 2012 at 19:36 j0k 22.8k28 gold badges81 silver badges90 bronze badges asked May 12, 2012 at 19:03 HaritzHaritz 1,7527 gold badges33 silver badges50 bronze badges2 Answers
Reset to default 4In 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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745065740a4609244.html
评论列表(0条)