Reputation: 1699
I am using annotations for my routing. In my index.twig template I wrote some JQuery like
$(document).ready(function(){
$('#sortable').NestedSortable(
{
accept: 'sort',
noNestingClass: "no-children",
helperclass: 'helper',
autoScroll: true,
onChange: function(serialized) {
},
onStop : function(){
var element_id = $(this).attr("id");
var parent_id = $(this).parent().attr("id");
var prev_sibling_id = $(this).prev().attr("id");
if(prev_sibling_id=='trash'){
var data = {PID:element_id};
$.ajax({
type: "POST",
data: data,
url:"{{ path('v2_pm_patentgroups_trash') }}",
cache: false,
success: function(data) {
document.location.reload(true);
});
}
else if(parent_id=='sortable'){
var p_sibling = $(this).prev().attr("value");
if(p_sibling == null){var p_sibling = 0;}
var n_sibling = $(this).next().attr("value");
if(n_sibling == null){var n_sibling = 0;}
var order = (p_sibling + n_sibling)/2;
var data = {ID:element_id, ORD:order};
$.ajax({
type: "POST",
data: data,
url:"{{ path('v2_pm_patentgroups_sortgroups') }}",
cache: false
});
}
Now you see there are two ajax callsone is called when a group is trashed and other one is called when the group is sorted.
The group is an li tag which is in my twig file
<li id="{{ portfolio_group.id }}" class="sort group" value={{ portfolio_group.order }}>
<span class="drag-image groupimage"> </span>
<a class='expand'>{{ portfolio_group.name }}</a>
<a class="button3" href="{{ path('v2_pm_patentgroups_edit', { 'patentgroupId': portfolio_group.id }) }}" ><span> Edit </span></a>
<a class="button3" href="{{ path('v2_pm_patentgroups_delete', { 'patentgroupId': portfolio_group.id }) }}" ><span> Delete </span></a>
<hr class="separator">
</li>
Can anyone giude me how to give path to url from my inside my JS. I dont want to use routing file.
Thanks
Upvotes: 0
Views: 1815
Reputation: 6927
When I need to pass data from the controller/view to the javascript I usually set data attributes on the relevant HTML tags. For example, if I need a route for an AJAX request I will write:
<a href="#updateTarget" class="ajaxTrigger" data-ajax-route="{{ path('my_ajax_route') }}">click here for ajax</a>
and then access it with:
$('.ajaxTrigger').on('click', function(){
$.getJSON($(this).data('ajax-route'), function(response) {
// do something with response
});
});
There is also a bundle to do much more sophisticated things with dynamic JS routing https://github.com/FriendsOfSymfony/FOSJsRoutingBundle
edit:
For your specific case you could set the route data on the container of the group, the <ul>
<ul id="portfolioContainer"
data-ajax-trash="{{ path('v2_pm_patentgroups_sortgroups') }}"
data-ajax-sort="{{ path('v2_pm_patentgroups_sortgroups') }}">
and then from your JS file you would refer to those data attributes:
$.ajax({
type: "POST",
data: data,
url:$('#portfolioContainer').data('ajax-trash'),
cache: false,
success: function(data) {
document.location.reload(true);
});
Upvotes: 2