Jump to content

How it is possible that form initiates AJAX request to URL different from form's action?


Clarity
 Share

Recommended Posts

Hello everyone!

I have a HTML code for the form:

                   
<form class="contact-form" action="/ajax-handler/" method="POST">
	<input type="text" placeholder="Name">
	<input type="text" placeholder="Phone">
	<input type="text" placeholder="Message">
 	<button type="submit">Submit</button>
</form>
 
I have an JS code which handles it via AJAX request:
 
 
$(function() {
 
	var form = $('.contact-form');
 
	$(form).submit(function(e) {
		e.preventDefault();
		var formData = $(form).serialize();
		$.ajax({
			type: 'POST',
			url: $(form).attr('action'),
			data: formData
		})
		.done(function(response) {
			alert(1);
		})
	});
});
 
However, when I open "Network" tab in Dev Tools, I see that the request goes to the same page where the form is being placed, not to /ajax-handler/ page. Can you please tell me where I was wrong?
Link to comment
Share on other sites

I dunno, it works for me. I did add names to the inputs, because they wouldn't get serialised without them, but the javascript is the same as yours:

grafik.thumb.png.f1d3fe11f9f785446ff1793b95a7b99d.png

Note that action="/ajax-handler/" with the "/" at the beginning will submit the request to "example.com/ajax-handler/" regardless of the original url. If you want to request a relative path, remove the first "/".

  • Like 1
Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...