Json response displayed

I'm new to both symfony and ajax , i want to submit a form without refreshing the page everytime i was following along with this tutorial , everything working the page does submit to the database but the problem is that i get this message in the browser

{"message":"Success!"}

This is what i have in my controller .

$bon = new Bons();
    $form = $this->createForm('AppBundle\Form\BonsType', $bon);

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($bon);
        $em->flush();

        return new JsonResponse(array('message' => 'Success!'), 200);
    }

    return $this->render('bons/new.html.twig', array(
        'bon' => $bon,
        'form' => $form->createView(),
    ));

The ajax part :

$(document).ready(function() {
        $('body').on('submit', '.myForm', function (e) {

            e.preventDefault();

            $.ajax({
                type: $(this).attr('method'),
                url: $(this).attr('action'),
                data: $(this).serialize()
            })
            .done(function (data) {
                if (typeof data.message !== 'undefined') {
                    alert(data.message);
                }
            })
            .fail(function (jqXHR, textStatus, errorThrown) {
                if (typeof jqXHR.responseJSON !== 'undefined') {
                    if (jqXHR.responseJSON.hasOwnProperty('form')) {
                        $('#form_body').html(jqXHR.responseJSON.form);
                    }

                    $('.form_error').html(jqXHR.responseJSON.message);

                } else {
                    alert(errorThrown);
                }

            });
        });
    });

is there any way to submit the form without redirecting or refreshing the page

Answers 1

  • Turns out your problem was really simple. You just need to add the dataType like so:

    $.ajax({
        type: $(this).attr('method'),
        dataType: "json",
        url: $(this).attr('action'),
        data: $(this).serialize()
    })
    

    I want to show you what I normally do

    My php file looks like this:

    $json = array();
    $my_variable = $_POST('variable_name'); // or however I get the value
    if(something == something)
        $json['success'] = 'It was successful';
    else
        $json['error'] = 'Something went wrong';
    die(json_encode($json));
    

    My JS looks like this:

    $('.update_class').click(function(){
        var variable_I_am_sending = $(this).data('something');
        $.post('path_to_php', {variable_name: variable_I_am_sending}, function(data, result, xhr){
            if(result == 'success')
                if(data.success)
                    alert(data.success);
                else
                    alert(data.error);
            else
                alert('ajax call failed');
        }, "json");
    });
    

Related Articles