简体   繁体   中英

php form : twig parameter from javascript or textarea html

i have a textarea defined by an id

<textarea id='vegetable'> Tomato </textarea>

i have a button

<button type="button" onclick="MyFunction()">generate vegetable</button>

which trig a javascript in order to modify the content of the textarea

<script>
function MyFunction()
{
    document.getElementById("vegetable").innerHTML = VegetableNameGenerator();
}
</script>

The problem is this php action :

<form action="{{ path('mypath', { 'myparam': ??? }) }}" method="post" > 
    <input type="submit" />
</form>

??? must be the content of the textarea (which is also known by the javascript code) but i don't know how to access it in twig. I guess there are several way of doing that : jquery, dom, global variable twig... any syntax example would be great.

This is impossible in the way you're describing it.

When a request is made to the server, twig renders the page, then it is sent to the browser, and then javascript can run.

There are options for how to make this work:

  1. Create a controller action which returns the rendered path when you call it using a GET request with the provided parameter. Then create an event listener on the submit button that blocks the submit process until it has retrieved the route via AJAX and modified the form's action attribute.

  2. Redirect from your controller to the path you want displayed. myparam will be included in the post data, so you can redirect from your controller action after you've handled the form.

     $this->redirect($this->get('router') ->generate('mypath', array('myparam'=> $this->getRequest()->get('myparam') ), true); 

Thanks for your response. I don't know if it fits to your suggestion but i find this link which give a detailled example and allow me to do what i need :

Call Symfony2 controller from jquery

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