<commit_before>JavaScript helpers
==================

Overview
--------

Interactions on the client side, complex visual effects or asynchronous communication are common in web 2.0 applications. All that require JavaScript, but coding it by hand is often cumbersome and long to debug. Fortunately, symfony automates many of the common uses of JavaScript in the templates.

Introduction
------------

JavaScript has long been considered as a candy for beginners, without any real use in professional web applications due to the lack of compatibility between browsers. In the late 90s, the word 'DHTML' meant 'unreadable HTML code with embedded JavaScript written three times for compatibility', and it sometimes referred to dynamic web pages that didn't work. 

These days are now over, since the compatibility issues are (mostly) solved and some robust libraries allow to program complex interactions in JavaScript without the need for 200 lines of code and 20 hours of debugging. The most popular advance is called [AJAX](http://en.wikipedia.org/wiki/Ajax_%28programming%29), and will be treated a little further.

For now, all you need to know is... JavaScript. Or maybe forget a little about it, because what will be shown below is how NOT to use JavaScript to do what you would expect JavaScript for. Just reconsider this scripting language as an opportunity to manipulate the DOM on the client side, with all the power that it gives. 

All the helpers described here are available in templates provided you declare the use of the `Javascript` helper:

    [php]
    <?php echo use_helper('Javascript') ?>
    
Some of them output HTML code, some of the output JavaScript code. It will be specified for each of them.

Basic helpers
-------------

The most common use of JavaScript is in a hyperlink that triggers a particular script. In HTML, you would probably write it like that:

    [php]
    <a href="#" onClick="alert('foobar');return none;">Click me!</a>
    
Symfony proposes a helper to write it in a more concise way, the `link_to_function()`: 

    [php]
    <?php echo link_to_function("Click me!", "alert('foobar')") ?>
    
Like the `link_to()` [URL helper](templating_link_helpers.txt), you can add options to the `<a>` tag generated by a `link_to_function()`:

    [php]
    <?php echo link_to_function("Click me!", "alert('foobar')", "class=mylink style=color:#f00 alt=please click me" ) ?>

>**Note**: Just like the `link_to()` helper has a `button_to()` brother, you can trigger a JavaScript from a button (`<input type="button">`) by calling the `button_to_function()` helper. And if you prefer a clickable image, just call `link_to_function(image_tag('myimage'), "alert('foobar')")`.

If you want to write a piece of JavaScript code in your page, instead of writing manually something like:

    [php]
    <script type="text/javascript">
    //<![CDATA[ 
      function foobar()
      {
      ...
      }      
    //]]>
    </script>

You could try the `javascript_tag()` function:

    [php]
    <?php echo javascript_tag("
      function foobar()
      {
      ...
      }          
    ") ?>

One common task in applications that use JavaScript a lot is the update of an element in the page. This is something that you usually write:

    [php]
    <?php echo javascript_tag("
      document.getElementById("indicator").innerHTML = "<strong>Evacuation complete</strong>";
    ") ?>

Symfony provides a helper that produces JavaScript - not HTML - for this purpose, and it's called `update_element_function()`:

    [php]
    <?php echo javascript_tag(
      update_element_function('indicator', array(   
        'content'  => "<strong>Evacuation complete</strong>",
      ))
    ) ?>

You may ask: What's the interest of a helper if it is longer to write than the normal code? Sometimes, you want to insert content *before* an element, or *after* it; you may also want to *remove* an element instead of just updating it, or to do nothing according to a condition. In these cases, the JavaScript code becomes somehow messier, but the `update_element_function()` keeps very readable:

    [php]
    // insert content just after the 'indicator' element
    update_element_function('indicator', array(
      'position' => 'after',      
      'content'  => "<strong>Evacuation complete</strong>",
    ));
    
    // remove the element before the 'indicator' element, and only if $condition is true
    update_element_function('indicator', array(
      'action'   => $condition ? 'remove' : 'empty',
      'position' => 'before',      
    ))

The helper makes your templates easier to understand than any JavaScript code, and you have one single syntax for similar behaviours. That's also why the helper name is so long: It makes the code self-sufficient, without the need of extra commentaries.

AJAX helpers
------------

What if the function updating an element of the page was not in a JavaScript, but a PHP script executed by the server? This would give you the opportunity to change part of the page according to a server response. The `remote_function()` does exactly that:

    [php]
    <?php echo javascript_tag(
      remote_function(array(   
        'update'  => 'myzone',
        'url'     => 'mymodule/myaction',
      ))
    ) ?>

When called, this script will update the element of id `myzone` with the response or the request of the `mymodule/myaction` action. This kind of interaction is called AJAX, and it's the heart of highly interactive web applications. Here is how [Wikipedia](http://en.wikipedia.org/wiki/Ajax_%28programming%29) describes them:

>_AJAX makes web pages feel more responsive by exchanging small amounts of data with the server behind the scenes, so that the entire web page does not have to be reloaded each time the user makes a change. This is meant to increase the Web page's interactivity, speed, and usability._

AJAX relies on [XMLHttpRequest](http://en.wikipedia.org/wiki/XMLHttpRequest), a JavaScript object that behaves like a hidden frame, which you can update from a server request and reuse to manipulate the rest of your web page.

An AJAX interaction is made up of three parts: a caller (a link, a button or any control that the user manipulates to launch the action), a server action, and a zone in the page to display the result of the action to the user. Symfony provides multiple helpers to insert AJAX interaction in your templates by putting the caller in a link, a button, a form, or a clock. Beware that this time, these helpers output HTML code, not JavaScript.

For instance, imagine a link that would call a remote function. Symfony writes it like this:

    [php]
    <?php echo link_to_remote('Delete this post', array(
        'update' => 'indicator',<commit_msg>documented if_javascript() and end_if_javascript() helpers (related to r1614)<commit_after>JavaScript helpers
==================

Overview
--------

Interactions on the client side, complex visual effects or asynchronous communication are common in web 2.0 applications. All that require JavaScript, but coding it by hand is often cumbersome and long to debug. Fortunately, symfony automates many of the common uses of JavaScript in the templates.

Introduction
------------

JavaScript has long been considered as a candy for beginners, without any real use in professional web applications due to the lack of compatibility between browsers. In the late 90s, the word 'DHTML' meant 'unreadable HTML code with embedded JavaScript written three times for compatibility', and it sometimes referred to dynamic web pages that didn't work. 

These days are now over, since the compatibility issues are (mostly) solved and some robust libraries allow to program complex interactions in JavaScript without the need for 200 lines of code and 20 hours of debugging. The most popular advance is called [AJAX](http://en.wikipedia.org/wiki/Ajax_%28programming%29), and will be treated a little further.

For now, all you need to know is... JavaScript. Or maybe forget a little about it, because what will be shown below is how NOT to use JavaScript to do what you would expect JavaScript for. Just reconsider this scripting language as an opportunity to manipulate the DOM on the client side, with all the power that it gives. 

All the helpers described here are available in templates provided you declare the use of the `Javascript` helper:

    [php]
    <?php echo use_helper('Javascript') ?>
    
Some of them output HTML code, some of the output JavaScript code. It will be specified for each of them.

Basic helpers
-------------

### Clean XHTML JavaScript inclusion

If you want to write a piece of JavaScript code in your page, instead of writing manually something like:

    [php]
    <script type="text/javascript">
    //<![CDATA[ 
      function foobar()
      {
      ...
      }      
    //]]>
    </script>

You could try the `javascript_tag()` function:

    [php]
    <?php echo javascript_tag("
      function foobar()
      {
      ...
      }          
    ") ?>
    
### Link behavior

The most common use of JavaScript is in a hyperlink that triggers a particular script. In HTML, you would probably write it like that:

    [php]
    <a href="#" onClick="alert('foobar');return none;">Click me!</a>
    
Symfony proposes a helper to write it in a more concise way, the `link_to_function()`: 

    [php]
    <?php echo link_to_function("Click me!", "alert('foobar')") ?>
    
Like the `link_to()` [URL helper](templating_link_helpers.txt), you can add options to the `<a>` tag generated by a `link_to_function()`:

    [php]
    <?php echo link_to_function("Click me!", "alert('foobar')", "class=mylink style=color:#f00 alt=please click me" ) ?>

>**Note**: Just like the `link_to()` helper has a `button_to()` brother, you can trigger a JavaScript from a button (`<input type="button">`) by calling the `button_to_function()` helper. And if you prefer a clickable image, just call `link_to_function(image_tag('myimage'), "alert('foobar')")`.

### Updating an element

One common task in applications that use JavaScript a lot is the update of an element in the page. This is something that you usually write:

    [php]
    <?php echo javascript_tag("
      document.getElementById("indicator").innerHTML = "<strong>Evacuation complete</strong>";
    ") ?>

Symfony provides a helper that produces JavaScript - not HTML - for this purpose, and it's called `update_element_function()`:

    [php]
    <?php echo javascript_tag(
      update_element_function('indicator', array(   
        'content'  => "<strong>Evacuation complete</strong>",
      ))
    ) ?>

You may ask: What's the interest of a helper if it is longer to write than the normal code? Sometimes, you want to insert content *before* an element, or *after* it; you may also want to *remove* an element instead of just updating it, or to do nothing according to a condition. In these cases, the JavaScript code becomes somehow messier, but the `update_element_function()` keeps very readable:

    [php]
    // insert content just after the 'indicator' element
    update_element_function('indicator', array(
      'position' => 'after',      
      'content'  => "<strong>Evacuation complete</strong>",
    ));
    
    // remove the element before the 'indicator' element, and only if $condition is true
    update_element_function('indicator', array(
      'action'   => $condition ? 'remove' : 'empty',
      'position' => 'before',      
    ))

The helper makes your templates easier to understand than any JavaScript code, and you have one single syntax for similar behaviours. That's also why the helper name is so long: It makes the code self-sufficient, without the need of extra commentaries.

### Graceful degradation

You already know how to qualify some HTML code to make it executed only by browsers with no JavaScript support, uting the  `<noscript>` tags. What if you could do it the other way around, i.e. qualify some code so that it is executed only by browsers actually supporting JavaScript? Symfony provides two helpers just for that, and it facilitates the creation of applications that degrade gracefully.

    [php]
    <?php if_javascript(); ?>
      <p>You have JavaScript enabled.</p>
    <?php end_if_javascript(); ?>
    
    <noscript>
      <p>You don't have JavaScript enabled.</p>
    </noscript>
    
>**Note**: You don't need to include the `echo` when calling these two helpers.

AJAX helpers
------------

What if the function updating an element of the page was not in a JavaScript, but a PHP script executed by the server? This would give you the opportunity to change part of the page according to a server response. The `remote_function()` does exactly that:

    [php]
    <?php echo javascript_tag(
      remote_function(array(   
        'update'  => 'myzone',
        'url'     => 'mymodule/myaction',
      ))
    ) ?>

When called, this script will update the element of id `myzone` with the response or the request of the `mymodule/myaction` action. This kind of interaction is called AJAX, and it's the heart of highly interactive web applications. Here is how [Wikipedia](http://en.wikipedia.org/wiki/Ajax_%28programming%29) describes them:

>_AJAX makes web pages feel more responsive by exchanging small amounts of data with the server behind the scenes, so that the entire web page does not have to be reloaded each time the user makes a change. This is meant to increase the Web page's interactivity, speed, and usability._

AJAX relies on [XMLHttpRequest](http://en.wikipedia.org/wiki/XMLHttpRequest), a JavaScript object that behaves like a hidden frame, which you can update from a server request and reuse to manipulate the rest of your web page.

An AJAX interaction is made up of three parts: a caller (a link, a button or any control that the user manipulates to launch the action), a server action, and a zone in the page to display the result of the action to the user. Symfony provides multiple helpers to insert AJAX interaction in your templates by putting the caller in a link, a button, a form, or a clock. Beware that this time, these helpers output HTML code, not JavaScript.

For instance, imagine a link that would call a remote function. Symfony writes it like this:

    [php]
    <?php echo link_to_remote('Delete this post', array(
        'update' => 'indicator',
{'fraction_non_alphanumeric': 0.08690815546130849, 'fraction_numerical': 0.002920114023499965, 'mean_word_length': 3.7083469721767592, 'pattern_counts': {'":': 0, '<': 54, '<?xml version=': 0, '>': 73, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1760598', 'n_tokens_mistral': 3817, 'n_tokens_neox': 3595, 'n_words': 1910}