We help IT Professionals succeed at work.

How do I serialize data in a button's surrounding form?

SiobhanElara
SiobhanElara asked
on
High Priority
49 Views
Last Modified: 2020-02-26
I have a simple form:
<div id="notify-alert"></div>
<form method="post">
<input type="hidden" name="memberID" value="5">
<input type="hidden" name="requestID" value="23">
<input type="button" name="submitNotify" value="Notify" onclick="SubmitNotification();">
</form>

Open in new window


the SubmitNotification function is as follows:
function SubmitNotification(){
	//these next four lines were to check what was going on
	var thisData = $(this).closest('form').serialize(); 
	console.log('begin');
	console.log(thisData);
	console.log('end');
	$.ajax({
		type: "POST",
		url: "ajax-notify.cfm",
		data: $(this).closest('form').serialize(),
		dataType: "text",
		success: function(data, status) {
			$('#notify-alert').html(data);
		},
		error: function(data, status) {
			$('#notify-alert').html(data);
		}
	});
};

Open in new window


$(this).closest('form').serialize(); is just returning an empty string. I've found several questions about how to serialize the surrounding form of a button and this appears to be to the correct way... where is this going awry? (I've also tried $(this).parent('form') with the same issue. Incidentally, I'm not using an ID for this because there are multiple forms on the page created by a loop.) Thanks!
Comment
Watch Question

Prepress/OMS Specialist
CERTIFIED EXPERT
Commented:
I would suggest a couple of changes to your approach.  First use an actual BUTTON element in your HTML.  You can also strip out the name, unless you are specifically using it on your back-end.
<div id="notify-alert"></div>
<form method="post">
  <input type="hidden" name="memberID" value="5" />
  <input type="hidden" name="requestID" value="23" />
  <input type="button" name="submitNotify" value="Notify" />
</form>

Open in new window

Next, I would use an event listener, rather than using the onClick on the input tag.
$('input:button[name="submitNotify"]').on("click", function(e) {
  e.preventDefault();
  formData = $(this).closest('form').serialize();
  $.ajax({
    type: "POST",
    url: "ajax-notify.cfm",
    data: formData,
    dataType: "text",
    success: function(data, status) {
      $('#notify-alert').html(data);
    },
    error: function(data, status) {
      $('#notify-alert').html(data);
    }
  });
});

Open in new window

What the above code does is to attach an event listener to all buttons on the page with a name of "submitNotify".  I would suggest adding a class to the input buttons rather than relying on the name.

Let me know if the above does what you are looking for, or if you have any other questions.

Author

Commented:
Perfect, thank you!