jquery or json form stay on page when submitted

I have a form that uses Jquery to show a message for

*field required error message

I am trying to get it to show a success message if the form is submitted on the same page.
I know json can be used, but do not know where to start with json.

The form submits as long as the req fields are filled in.

Does anyone know how I can modify this code to show the "success" div if all the "req" fields are filled out just like the ".req" shows if the fields are empty.

** notes
in the php, I currently redirect to thanks.php for valid and spam.php for honeypot filled in

My brain is fried today.

Thanks


form.js
$(function() {
       function validateform() {
          var valid = true;
          $(".req").css("border","1px solid #ccc");
          $(".req").each(function() {
             if ( $(this).val() == "" || $(this).val().replace(/\s/g, '').length == 0 ) {
                $(this).css("border","1px solided");$(".required").css("display","block");
                valid = false;
             }
          });
          return valid;
       }    
       $("#submit").click( function() {
          $('#myform').submit( validateform );
          $('$name').submit();
       });  
   });

Open in new window


process.php
<?php
    // Clean up the input values
    foreach ( $_POST as $key => $value ) {
      if ( ini_get('magic_quotes_gpc') )
        $_POST[$key] = stripslashes( $_POST[$key] );

      $_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
    }

    // Honeypot don't send
    if ( !empty($_POST["confirm_email"] ) ) {
      header("location:spam.php");exit;
    }

    // Assign the input values to variables for easy reference
    $name = $_POST["name"];
    $email = $_POST["email"];
    $confirm = $_POST["confirm_email"];
    $phone = $_POST["phone"];
    $message = $_POST["message"];
    $mls = $_POST["mls"];


    // Send the email *****************************
    $to = "email@mywebsite.com"; 
    $subject = "Website message: $name";
    $message = "MLS Listing:\n$mls\n\nFrom:\n$name\n\nEmail:\n$email\n\nPhone:\n$phone\n\nMessage:\n$message";
    $headers = "From: $email";

    mail($to, $subject, $message, $headers);
    
echo("<script>location.href = 'thanks.php';</script>");

?>

Open in new window


form.html
<!--form-->
<form class="myform" id="myform" name="myform" action="process.php" method="post">

<div class="required">Red Highlights are required</div>

<div class="success">This is where the Succcess message is!</div>

<label>Name</label><input id="name" name="name" class="req" type="text"/>

<label>Email</label><input id="email" name="email" class="req" type="email" />

<label class="confirm_email">Confirm Email</label><input id="confirm_email" name="confirm_email" class="confirm_email" type="email" class="req2"/>

<label>Phone</label><input id="phone" name="phone" type="tel" />

<label>Message</label><textarea id="message" name="message" type="text" class="req"></textarea>

<input id="mls" name="mls" class="mls" value="MLS1234567" />

<input type="submit" id="submit" value="Submit Message" />
</form>
<!--form-end-->
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="form.js"></script>

Open in new window

mewebsAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Alexandre SimõesManager / Technology SpecialistCommented:
So the basic idea is that you don't actually submit the form.
You should serialize the form (to json) and perform an Ajax POST with the information, handling the success or error callbacks and behave as you wish. In your case showing a success message and probably redirecting out of there after right?

So the code for the save button (normal button, not a submit) click should be something like:

var form = $("#myform");
var url = form.attr("action");
var formData = form.serialize();

$.ajax({
	type: 'POST',
	data: formData,
	url: url,
    error: function(xhr, textStatus, err) {
        // something wrong happen
    },                
    success: function(data) {
        // show your success message
        // and get out of here to prevent the user to submit again
    }
});

Open in new window

0
Chris StanyonWebDevCommented:
Your validateform function is already returning true or false, so use that to see if all the values are filled in. If they are, then post your form through ajax and deal with the response. Bear in mind though that if your response is creating a redirect, then the success message won't be displayed (you'll have redirected!). Normally I would suggest you drop the redirect and just inject a 'Thanks for your form' kind of message:

$("#myform").submit(function(e) {

	//prevent the submit from firing - we'll do this with ajax!
	e.preventDefault();
	
	if (validateform()) {
		//the form is valid, so let's send it.
		myForm  = $(this);
		url = myForm.attr('action');
		data = myForm.serialize();

		//send the form data as an AJAX request
		$.ajax({
			url : url,
			data : data,
			type: 'post'
		})
		.done(function() {
			//all done
			$('<div>').html('Thanks for sending your form!').appendTo(myForm);
		});
	};
   	
});

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
mewebsAuthor Commented:
Thanks.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
jQuery

From novice to tech pro — start learning today.