Alex Alex - 1 month ago 9
Ajax Question

Ajax does not process the form that was generated by Javascript

I am having a problem where when I create an HTML form with javascript, the ajax does not process it at all and will just send me to the blank action PHP page. This page is blank because I added a check to see if the form fields are empty or not.

Form created with Javascript:

function createForm() {
var f = document.createElement('form');
f.setAttribute('method','post');
f.setAttribute('action','action.php');
f.setAttribute('class', 'ajax');
f.innerHTML = '<span style="color: black; display: inline;">Name: <input class="popup-form-fields" id="inputName" onkeyup="validateName(); theCheck();" onkeydown="validateEmail(); theCheck();" onclick="validateName();" type="text" name="name" autocomplete="off"></span><label id="commentName" class="label1"></label>';
f.innerHTML += '<div class="space"></div>';
f.innerHTML += '<span style="color: black; display: inline;">Email address: <input class="popup-form-fields" id="inputEmail" onkeyup="validateEmail(); theCheck();" onkeydown="validateEmail(); theCheck();" onclick="validateEmail();" type="email" name="email" autocomplete="off"></span><label id="commentEmail" class="label1"></label>'
f.innerHTML += '<div class="space"></div>';
f.innerHTML += '<span style="color: black; display: inline;">Phone number: <input class="popup-form-fields" id="inputPhone" onkeyup="validatePhone(); theCheck();" onkeydown="validatePhone(); theCheck();" onclick="validatePhone();" type="tel" name="phone" autocomplete="off"></span><label id="commentPhone" class="label1"></label>';
f.innerHTML += '<div class="space"></div>';
f.innerHTML += '<span style="vertical-align: top; color: black; display: inline;">Details: <textarea class="popup-form-fields" id="inputDetail" onkeyup="validateDetail(); theCheck();" onkeydown="validateDetail(); theCheck();" onclick="validateDetail();" name="details" autocomplete="off"></textarea></span><label id="commentDetail" class="label1"></label>';
f.innerHTML += '<div class="space"></div>';
f.innerHTML += '<input id="sub" type="submit" value="Send">';
}


Form created without Javascript:

<form method="POST" action="book-priv-party-complete.php" class="ajax">
<span style="color: black; display: inline;">Name: <input class="popup-form-fields" id="inputName" onkeyup="
validateName(); theCheck();" onkeydown="validateName(); theCheck();" onclick="validateName();" type="text"
name="name" autocomplete="off"></span><label id="commentName" class="label1"></label>
<div class="space"></div>
<span style="color: black; display: inline;">Email address: <input class="popup-form-fields" id="inputEmail"
onkeyup="validateEmail(); theCheck();" onkeydown="validateEmail(); theCheck();" onclick="validateEmail();" type=
"email" name="email" autocomplete="off"></span><label id="commentEmail" class="label1"></label>
<div class="space"></div>
<span style="color: black; display: inline;">Phone number: <input class="popup-form-fields" id="inputPhone"
onkeyup="validatePhone(); theCheck();" onkeydown="validatePhone(); theCheck();" onclick="validatePhone();" type=
"tel" name="phone" autocomplete="off"></span><label id="commentPhone" class="label1"></label>
<div class="space"></div>
<span style="vertical-align: top; color: black; display: inline;">Details: <textarea class="popup-form-fields"
id="inputDetail" onkeyup="validateDetail(); theCheck();" onkeydown="validateDetail(); theCheck();" onclick="
validateDetail();" name="details" autocomplete="off"></textarea></span><label id="commentDetail" class="label1
"></label>
<div class="space"></div>
<input id="sub" type="submit" value="Send">
</form>


The ajax:

$('form.ajax').on('submit', function () {
var that = $(this),
url = 'action.php',
type = 'post',
data = {};
that.find('[name]').each(function (index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function () {
removeElement();
document.getElementById('errorCode').innerHTML = "Your message was sent";
document.getElementById('errorCode').style.color = "green";
setTimeout(function () {document.getElementById('errorCode').style.display = "none";}, 2000);
alert("It worked");
},
error: function () {
removeElement();
document.getElementById('errorCode').innerHTML = "Your message was not sent";
document.getElementById('errorCode').style.color = "red";
setTimeout(function () {document.getElementById('errorCode').style.display = "none";}, 2000);
}
});
return false;
});


Is is possible that the cause of this issue is when and where the Javascript is being run?

Answer

A possible reason for the submit function not getting triggered in your javascript function is because you create this form element dynamically. When I say dynamically, I mean this element is created definitely after the initial page render is complete. When the browser initially renders your page, it creates the DOM tree, parses the javascript and binds all the event handlers.

So, the $('form.ajax').on('submit',.. looks for form element and binds the submit function to a callback at a time when the form element might not have been created. That could be a reason why you don't get any response.

I would suggest reading about event delegation.

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.

So you basically bind listeners to a parent container that is guaranteed to be in the DOM and then just find the target of that event.

For instance suppose I want to listen to a click event of a button with id foo that I create dynamically inside a div with id container. I can listen to that click by doing this:

$( "div#container" ).on("click", function( event ) {
   console.log( "clicked: " + event.target.nodeName ); //Will output button when this element is clicked.
});

Another really good article on event order in browsers is referenced here.

Hope it gets you started in the right direction.

Comments