Reputation: 217
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);
}
Upvotes: 3
Views: 1332
Reputation: 335
Your form id in html is form_newsletter. form id in JS is frm_newsletter.
Typo?
Upvotes: 0
Reputation: 3432
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)
Upvotes: 2