问题
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.
回答1:
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.
回答2:
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 :)
来源:https://stackoverflow.com/questions/13540762/contact-form-submit-button-disable-redirect