Search code examples
javascriptajaxsymfonysymfony-formsdata-manipulation

How to manipulate data by Symfony Form (with JS, AJAX)?


I've got a short question. Let's say I have the data from database in my Symfony app and on the same page I have a form which is responsible for manipulate these data. Saying "manipulate" I mean: displaying or hiding some data and sorting them. I think the best way to achieve this would be use a JavaScript/AJAX. The thing is I never wrote even JavaScript in my Symfony apps and I completly don't know how to go about it.

Have you got some link to documentation, tutorial or article which will show me how to manipulate data by JavaScript/AJAX in Symfony? Or could you please explain me it in a few words?

Thank you in advance for helping!


Solution

  • In Symfony, we use and compile JS files as assets in order to use them on pages. You might want to use JQuery when performing AJAX-requests. Using JQuery, AJAX can be coded by the following way:

    $.ajax({
       url: <insert url here>,
       type: <insert type here, for example, GET>,
       dataType: <insert data type here, for example, json>,
       success:function(data) {
          <Implement a function which is applied after a successful request. Variable "data" is the result of the request.>
       }
       error:function(data) {
          <Optionally, implement a function which shows information when request was not successful.>
       }
    });         
    

    For example, you have the class .cl on page and want to change HTML code of it. Then use $('.cl').replaceWith($(data).find('.cl')) in the success function.