3

Am using Symfony2, doctrine2 and twig. Am trying submit a form using ajax. The ajax function always returns this message: "This is not ajax!". I didn't find the problem. I hope you can help me.
Twig code:

<form id="form_newsletter" action="{{ path('portofolio_front_newsletter') }}" method="post" {{ form_enctype(newsletterForm) }}>
 <!-- form errors -->
 {{ form_errors(newsletterForm.email) }}
    <div class="input-group">
      {{ form_widget(newsletterForm.email, {'attr': {'class' : 'form-control email', 'placeholder' : 'Enter your email'} }) }} 
        {{ form_rest(newsletterForm) }}
          <span class="input-group-btn">
            <button class="btn btn-danger" id="btnSubmit" type="submit">Go!</button>
          </span>
     </div>
</form>

Jquery code:

<script type="text/javascript">
            $(document).ready(function() {
                $("#form_newsletter").submit(function(e) {
                    e.preventDefault();
                    var email = $('.email').val();
                    alert(email);
                    var DATA = 'email=' + email;
                    alert(DATA);
                    var url = $("#form_newsletter").attr("action");
                    $.ajax({
                        type: "POST",
                        url: url,
                        data: DATA,
                        cache: false,
                        success: function(data) {
                            console.log(data);
                        }
                    });                       

                });
            });

</script>  

Controller code:

public function newsletterAction(Request $request) {
    if ($request->isXMLHttpRequest()) {
        return new JsonResponse(array('data' => 'this is a json response'));
    }

    return new Response('This is not ajax!', 400);
}

2 Answers 2

2

It seems your form get submitted normally after the ajax request is made, because the normal default submit event is triggered even though you have already issued a request. Have you tried to add :

e.preventDefault():

in :

$("#frm_newsletter").submit(function(e) { 
   e.preventDefault();
   // rest of your code
}

? (note the e in the function parameters)

Sign up to request clarification or add additional context in comments.

Comments

0

Your form id in html is form_newsletter. form id in JS is frm_newsletter.

Typo?

2 Comments

Probably as he's getting a response and not checking for anything data related yet.
Now, it is working. I forgot to add use Symfony\Component\HttpFoundation\JsonResponse;. Thank you all.

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.