1

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

2
  • First you said you did this code because you didn't want to refresh the page every time and at the bottom you ask if there is a way to refresh the page... which is it? Commented Mar 25, 2016 at 1:33
  • Oh , i didn't notice that , i actually meant the first , submitting without refreshing Commented Mar 25, 2016 at 1:40

1 Answer 1

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");
});
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for replying Chris , what i'm getting is {"message":"Success!"} in the browser , instead i want to get that message in an alert box
If data.message is giving you {"message": "Success!"} It means that the object actually looks like this: {"message": {"message": "Success!"}}. So what you could try is this: data.message.message Can you please do me a favor and add this before your alert and tell me what it outputs in the console: console.log(data);
This is what i get after clicking the submit button . link , i also tried data.message.message but got the same result .
Oh your problem is actually really simple... just add dataType: "json"
I added it to the answer, you can check it out and try it, I am sure it will solve your problem.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.