MarGa
MarGa

Reputation: 731

Twig and javascript

i'm creating a page that shows a chart depending on the type selected in the combo box

<div id="chartdiv"></div>

<select name="graphe" id="identifiantDeMonSelect">
<option value="Column2D">Column2D
<option value="Column3D">Column3D
<option value="Pie3D">Pie3D
<option value="Pie2D">Pie2D
</select>
<input type="submit" value="Afficher" onclick="ajax()">


<script type="text/javascript">
function ajax(){
    var xhr

    if (window.XMLHttpRequest) { 
        xhr = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) 
    {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }

    if (xhr !=null)  {
    xhr.onreadystatechange = function() { type1(xhr); };
    xhr.open("GET", "{{ path('Ajax')}}", true);
    xhr.send(null);
    } else {

     alert("The XMLHttpRequest not supported");

  }}

function type1(xhr){
            var docXML= xhr.responseText;
            var val_type = getSelectValue('identifiantDeMonSelect');
            var type = val_type+"";
            var str="{{ asset('Charts/Pie2D.swf') }}";
            var chart = new FusionCharts(str, "ChartId", "600", "400", "0", "0");
            chart.setXMLData(docXML);                               
            chart.render("chartdiv");
            }
function getSelectValue(selectId)
{
    var selectElmt = document.getElementById(selectId);
    return selectElmt.options[selectElmt.selectedIndex].value;
}

</script>

Now when i simply replace var str="{{ asset('Charts/Pie2D.swf') }}"; with "{{asset('Charts/'+type+'.swf') }}" in order to dynamically change the the type of the chart i obtain the following symfony error : "Variable "type" does not exist in ". And when i put "{{ asset('Charts/"+type+".swf') }}" (i just replaced ' by ") i get the page and when i click the submit button nothing happens, and inside the console (chrome's console) i get this error "GET http://127.0.0.1:8888/dashboard2/Symfony/web/Charts/&quot;+type+&quot;.swf 404 (Not Found) ". It takes it as it is &quot;+type+&quot; Obviously i need help, i don't know if it's a concatenation problem or it has something to do with the twig and the asset function. Thanks in advance

Upvotes: 2

Views: 6494

Answers (1)

ivoba
ivoba

Reputation: 5986

I guess that is not possible. you cant mix javascript vars with twig because one is client the other is server.

Instead of using {{asset}} here you could make a route to fetch your asset and use asset functionality in the action. you then can use this: https://github.com/FriendsOfSymfony/FOSJsRoutingBundle

or a cheap workaround like this:

route = "{{ path('myassetroute', { 'pie': "PLACEHOLDER" }) }}";
route = route.replace("PLACEHOLDER", type);

Upvotes: 6

Related Questions