I need to know that what is the error in my code because everything is correct but form data could not be submitted and in php file the error popups that undefined index lname while submiting the form that means form is submitting through jquery but data is not going in backend. so please resolve this error or help me find out what the error is in code.
this is the html code:-
<span id="answer"></span>
<form id='contact_form' method="post">
<div class="modal-body">
<div id='name_error' class='error'>Please enter your name.</div>
<div>
<input type='text' name='lname' id='name' class="form-control" placeholder="Your Name" required>
</div>
<div id='email_error' class='error'>Please enter your valid E-mail ID.</div>
<div>
<input type='email' name='email' id='email' class="form-control" placeholder="Your Email" required>
</div>
<div id='phone_error' class='error'>Please enter your phone number.</div>
<div>
<input type='text' name='phone' id='phone' class="form-control" placeholder="Your Phone" required>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" onclick="formSubmit(event);" class="btn btn-primary">I Agree</button>
</div>
</form>
This is the jquery code:-
$('#subButton').click(function(e) {
console.log('in');
e.preventDefault();
var FormData = $('#contact-form').submit();
$.ajax({
type: "POST",
url: "admin/backend/leads.php",
data: FormData,
dataType: "json",
success: function(data) {
var html = '';
if (data.errors) {
html = '<div class="alert alert-danger">' + data.errors + '</div>';
}
if (data.success) {
html = '<div class="alert alert-success">' + data.success + '</div>';
$('#contact-form')[0].reset();
localStorage.setItem('#phone', true);
}
$('#answer').html(html);
},
error: function(data) {
html = '<div class="alert alert-danger">' + data.errors + '</div>';
$('#answer').html(html);
}
});
});
2
Answers
Problems in your code are…
id="subButton"
formSubmit
function$('#contact-form').submit()
submits the form normally which you don’t want. It also returns ajQuery
object, not the form data.First, remove the
onClick
from your submit button.Second, either add
id="subButton"
to your<button>
or, as is my preference, listen to the submit event on the form instead.Third, use jQuery’s .serialize() to capture all the form data
It’s 2022 and you might not need jQuery
Try this,