1

I'm using a Symfony2 Controller to return a JSON string:

return new Response(json_encode(array('errors' => $errors)));

Basically, I want to return errors to the form. But when I call the action, the JSON output is displayed in my browser. But I want to call the JSON in a callback function in JavaScript (jQuery).

I tried to set the Content-Type to application/json, but it doesn't work in IE because IE wants to save the file.

My JavaScript:

$("#form").submit(function() {
    var url = $(this).attr("action");

    $.ajax({
        type: "POST",
        url: url,
        data: $(this).serialize(),
        success: function(data, textStatus, jqXHR) {
            // Ouptut errors
        }
    });
});

What can I do?

1
  • I guess you are using your javascript wrong. Show us your javascript Commented Aug 6, 2012 at 13:29

1 Answer 1

2

You need to prevent the form submission on click so that it is only submit via $.ajax():

$("#form").submit(function(e) {
    e.preventDefault(); // stop the form being submit on click

    var url = $(this).attr("action");    
    $.ajax({
        type: "POST",
        url: url,
        data: $(this).serialize(),
        success: function(data, textStatus, jqXHR) {
            // Ouptut errors
        }
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you (; That does work for Firefox, but not for IE. So I added a return false statement at the end of the function.

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.