How to: Use Ajax to submit forms with default actions after submit

I suggest nixing out this jQuery stuff to get more maintainable code. Depending on what you need to do you may have to expand on this but as you can see is doing the same and costing much less.

const form = document.getElementById('wf-form-name')
form.addEventListener('submit', event => {
  const params = new URLSearchParams(new FormData(event.target))
  req.open('POST', 'https://example.com/api/v1/forms/formname', false)
  req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
  req.send(params)
})

Hey Chris, does your code work as a replacement of the jQuery code mentioned above? If so, where would this code go? Forgive my ignorance.

1 Like

Hi
I have a question about this similar topic above. Maybe someone can help me.
I have one form where I use the Ajax form action. If I push the submit button, the Ajax call happens in the background and in foreground it shows the Success- or Errormessage. This works perfect.
But if I have two forms or more, it doesn’t work anymore. How can I spezify the form for the Ajax call? Should I give a ID or a name? What should i change/add in code below?

<script>
makeWebflowFormAjax = function( forms, successCallback, errorCallback ) {
forms.each(function(){
	var form = $(this);
	form.on("submit", function(){
		var container = 	form.parent();
		var doneBlock  =	$(".w-form-done", container);
		var failBlock  =	$(".w-form-fail", container);
	
		var action = 		form.attr("action");
		var method = 		form.attr("method");
		var data = 			form.serialize();
		
		// call via ajax
		$.ajax({
			type: method,
			url: action,
			data: data,
			success: function (resultData) {
				if (typeof successCallback === 'function') {
					// call custom callback
					result = successCallback(resultData);
					if ( ! result ) {
						// show error (fail) block
						form.show();
						doneBlock.hide();
						failBlock.show();
						console.log(e);
						
						return;
					}
				}
				
				// show success (done) block
				form.hide();
				doneBlock.show();
				failBlock.hide();
			},

			error: function (e) {
				// call custom callback
				if (typeof errorCallback === 'function') {
					errorCallback(e)
				}
				
				// show error (fail) block
				form.show();
				doneBlock.hide();
				failBlock.show();
				console.log(e);
			}
		});
		
		// prevent default webdlow action
		return false;
	});
});
}

var Webflow = Webflow || [];
Webflow.push(function() {

 // === Custom Form Handling ===

  // unbind webflow form handling
  $(document).off('submit');
  makeWebflowFormAjax( $("form") );

  // new form handling
  $('form').submit(function(evt) {
    evt.preventDefault();
  });
});
</script>

Thanks a lot for your help.

@TWith - do you have a published page I can look at? The function should work for multiple forms, based on the .each() function. However, I’m not sure I’ve ever tried on a page with multiple forms so I can’t say for sure without looking.

The read-only link from the webflowpage contact.
https://preview.webflow.com/preview/search-for?utm_medium=preview_link&utm_source=designer&utm_content=search-for&preview=1495696a9cf93bdf3581d6b099fcd276&pageId=610ada82f285c21f1a852c63&workflow=preview

@TWith - sorry can’t troubleshoot custom code from within Webflow. I need a published link.

@sam-g - The published link: Kontakt search-for.ch | FreizeitaktivitƤten & Events

Sorry about total noobie questions, but I’m unsure about implementing this.
So the main long code goes (in settings) inside the head tag or before body?
What is the URL that goes in the form settings action field?
Or is it an external form code address that goes into the action field? If so what code is that?

So I guess these codes here are not all that it takes to send the form info to the recipient?

You can use the $.post() method in combination with the serialize() method to submit a form using AJAX in jQuery.

The following form will use jQuery to process a form without a page refresh (using AJAX) and display a success message.

$("#idForm").submit(function(e) {
  e.preventDefault();
  var form = $(this);
  var actionUrl = form.attr('action');
  $.ajax({
    type: "POST",
    url: actionUrl,
    data: form.serialize(), // serializes the form's elements.
    success: function(data)
    {
      alert(data); // show response.
    }
  });
});

Anyone receiving a success message frontend but not seeing the form info in the Settings → Forms?

Hi, maybe a little to late, but I have come with this post today that I was struggling with this same problem. I use the exact piece of code that you post it, but if you want to link it to a specific form you have to name it where it says $(ā€œformā€) and $(ā€˜form’), replace ā€œformā€ with (in my case use the id of the form) $(ā€˜#id_of_your_form’). That should work perfectly.