How to call a jquery function from form?

Super noob to html/php, hopefully you go easy on me :slight_smile: I think I learned just enough to be dangerous lol

Trying to cobble together a basic contact form on a small website project, found a html5 template and some basic code to validate the form variables, and use PHPMailer to send. I am trying to call what seems like a function in jquery, from the form elements to verify the variable entries. Using this as my project to wrap my head around working with scripting in html so far.

Here are the html form elements from index.php:

<form method="post" action="#">
                           <div class="fields">
                              <div class="field">
                              <label for="name">Name</label>
                              <input type="text" name="name" id="name" />
                           </div>
                           <div class="field">
                              <label for="email">Email</label>
                          <div..............
                          </div>
                          <ul class="actions">
                          <li><input type="submit" onclick="sendEmail()" value="Send Message"/></li>
                          </ul>
</form>

<!-- Code to verify form input Credit: Senaid Bacinovic-->
            <script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" >
            <script type="text/javascript">
                function sendEmail() {
                    var name = $("#name");
                    var email = $("#email");
                    var subject = $("#subject");
                    var body = $("#body");

                        if (isNotEmpty(name) && isNotEmpty(email) && isNotEmpty(subject) && isNotEmpty(body)) {
                            $.ajax({
                            url: 'sendEmail.php',
                            method: 'POST',
                            dataType: 'json',
                            data: {
                                name: name.val(),
                                email: email.val(),
                                subject: subject.val(),
                                body: body.val()
                            }, success: function (response) {
                                    if (response.status == "success")
                                        alert('Email Has Been Sent!');
                                    else {
                                        alert('Please Try Again!');
                                        console.log(response);
                                    }
                            }
                            });

It seems I have two action items,
<form method="post" action="#">
wants a script name,

and the other line:
<li><input type="submit" onclick="sendEmail()" value="Send Message"/></li>
Does nothing when clicked. The code works as I have it on my sandbox server, but it does not run the entry validation checks on the fields. and doesn’t handle the response, just reloads the index page.

Can anyone point me to examples when calling jquery functions from php/html forms? I am still learning syntax by example if it doesn’t show lol Any help would be greatly appreciated. I am working on much simpler example code, and everything works - or so I think I have my head wrapped around it, then I get lost as soon as I want to add a bit more logic.

Thanks!

Both <script ... sections in the posted code are incomplete, are producing errors in your browser, and are not being executed at all. See the browser’s developer tools console and network tabs for debugging purposes.

Client-side validation is only a nicety for legitimate visitors. You must have server-side validation, since data submitted to the server can come from anywhere (not just your form), can be anything, and cannot be trusted.

For client-side validation, rather than write out bespoke code for each form field, just add a required attribute to all the form fields, and let the browser do the validation for you.

For the required attribute to work, you must allow the form submission event to occur, i.e. you cannot use an onclick event in the submit button, you must use an onsubmit event, and the onsubmit is put into the <form ... tag.

Also, rather than write out bespoke code to get the value for each field, just get all the form data at once, using the formData object.

See this example code -

<script
  src="https://code.jquery.com/jquery-3.6.0.min.js"
  integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
  crossorigin="anonymous">
 </script>

<script>
function submit_form(e) {

	// get all the 'successful' form data from the current form
	var formData = new FormData(e);
	// add an (optional) ajax indicator. uncomment the following line -
	// formData.append('via ajax', 'y');

	$.ajax({
		url: 'sendEmail.php',
		method: 'post',
		datatype: 'json',
		data: formData,
		// because the data is a formData object, which may contain $_FILES data, the following two lines are needed to prevent it from being modified by jquery
		processData: false,
		contentType: false,
		success: function(response){
			if (response.status == "success") {
				alert('Email Has Been Sent!');
			}
			else {
				alert('Please Try Again!');
				console.log(response);
			}
		}
	});
	// prevent the submit button from submitting the form a 2nd time
	return false; 
}
</script>


<form method="post" onsubmit="return submit_form(this);">
   <div class="fields">
	  <div class="field">
	  <label for="name">Name</label>
	  <input type="text" name="name" id="name" required>
   </div>
   <div class="field">
	  <label for="email">Email</label>
	  <input type="text" name="email" id="email" required>
  </div>
  <ul class="actions">
  <li><input type="submit" value="Send Message"/></li>
  </ul>
</form>
Sponsor our Newsletter | Privacy Policy | Terms of Service