简体   繁体   中英

Contact form submit button - disable redirect

I am using a simple php form I found here http://www.1stwebdesigner.com/tutorials/custom-php-contact-forms/comment-page-2/#comments

But I am having few issues with it. When clicking the submit button I want to be able to stay on my website instead of being redirected on mail.php and just print/echo the sent message on my website instead.

Also I want to make the fields have requirements, like not being empty which I know how to do in php but I must first solve the redirect issue.

What you need is $.ajax from jQuery . This will send a POST request without reloading the page.

Lets say your button is called myButton then for the onClick() event you would call the function

$.ajax({
  type: "POST",
  url: "some.php",
  data: { name: "John", location: "Boston" }
}).success(function( msg ) {
  alert( "Data Saved: " + msg );
});

In your some.php you would then just use $_POST['name'] and $_POST['location'] to retrieve the information.

Edit

Suppose you had an input field. You can retrieve information from such a field via jQuery as well. You can just then send the information from the input field via ajax to you php script

$('#yourInputField').val();

where yourInputField is the ID of the input field. With this you can get this information to the script. If you have multiple elements in a form you might want to look at the function serialize() . Does the same thing in principle, just compresses all the information into a JSON string.

With the staying on the same page you just set the form action to your current page then you could use :

if (isset ($_POST['submit'])){
(php code to run goes in here)
echo 'blah blah';
}

That will run the php code when the submit button is pressed :)

This however will still reload the page but it won't direct you to a different php page. If you dont want the page to reload at all then you can use ajax :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM