How to do twing {{path ('')}} call as jquery ajax url

I am using an ajax request from a modal block to store data in my symfony2 application. Modal markup is displayed when the modal window is called. Therefore, I cannot use the "" signs everywhere in my layout of modal boxes.

My code is:

var path = {{ path('_inserttask') }}; $.ajax({ type: 'POST', url: path, data: { myid: 123456 }, success: function(data) { $('#mask , .login-popup').fadeOut(300 , function() { $('#mask').remove(); }); } }); 

It throws an error in the console when calling ajax. I determined that if I use a hard coded url - it works! But using {{ path('_inserttask') }} as url gives an error. I understand that I do not use quotation marks. How to solve a problem? he already killed 2 hours: - (

+2
source share
1 answer

From what I see above, you do not put double quotes on the value of the path variable. Try it -

 var path = "{{ path('_inserttask') }}"; $.ajax({ type: 'POST', url: path, data: { myid: 123456 }, success: function(data) { $('#mask , .login-popup').fadeOut(300 , function() { $('#mask').remove(); }); } }); 

And think more: do you embed this script in a branch template that will later display html and then send to the browser correctly? If so, I think the above change will solve the problem.

If you are trying to use a branch in a pure javascript file. I do not think this will work. If you do that. I think you are trying to put the path value in html, and then use javascript to get that value, and then call ajax instead. eg. I would choose to embed this path url into one of the div attributes.

In my twig template file (e.g. index.html.twig)

 <div id="abc" data-path="{{path('_inserttask')}}"> </div> 

In my javascript file (e.g. abc.js)

 var path = $("#abc").attr("data-path"); $.ajax({ type: 'POST', url: path, data: { myid: 123456 }, success: function(data) { $('#mask , .login-popup').fadeOut(300 , function() { $('#mask').remove(); }); } }); 
+11
source

All Articles