简体   繁体   中英

Refresh table after request Ajax is success

I am beginner with Ajax. I try refresh a table when user select an option in form-select filter. I use Symfony and Twig.

I get the new datas in the Json format in my console when i select a new filter, but the table does'nt show with the new datas. I failed to find the solution when my request ajax is success.

My Select filter:

    {{ form_start(form) }}
    <div class="container-fluid">
        <div class="row">
            <div class="col-fluid">
                {{ form_row(form.isAttending) }}
            </div>
            <button type="submit" class="btn btn-outline-success mb-2">{{ button_label|default('Envoyer') }}</button>
        </div>
    </div>

    <div class="container-fluid">
        <div class="row">
            <div class="col-1-fluid">
                {{ form_row(form.active) }}
            </div>
        </div>
    </div>
    {{ form_end(form) }}

In my Controller:

 /**
     * @Route("/ajax", methods={"GET", "POST"})
     */
    public function testAjax(Request $request)
    {
        if (!$request->isXmlHttpRequest()) {
            return new JsonResponse(array(
                'status' => 'Error',
                'message' => 'Error'),
                400);
        }

        if($request->request->has('isAttending')) {
            $preSelect = $request->request->get('isAttending');
            return new JsonResponse(
                $this->queryFollowingFilter($preSelect),
                200);
        }
    }

In my Template:

    <script>
        $(document).on('change', '#campagnes_tel_isAttending', function () {
            $('#flash').remove();
            let $field = $(this)
            let $preselect = $('#campagnes_tel_isAttending')
            let $form = $field.closest('form')
            let data = {}
            data['isAttending'] = $field.val()
            console.log(data)
            $.ajax({
                type: "POST",
                url: "/campagnestel/ajax",
                data: data,
                dataType: "json",
                success: function(response) {
                    console.log(response);
                }
            });
        });
    </script>

Any ideas?

According to your question and comments your problem is not Symfony, not Ajax and also not Twig related. You get the correct data and you just do not know how to manipulate the DOM. DOM manipulation is a basic capability of JavaScript.

Here you can learn how to manipulate the DOM: https://www.w3schools.com/js/js_htmldom.asp

And here you can learn how to easily can manipulate it with jQuery which you are obviously using: https://www.w3schools.com/js/js_jquery_dom.asp

Sample:

$('#my-table').append(response.myWhatever);

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