Reputation: 1068
I am trying to use Jquery and AJAX to submit a small contact form without page refresh. I got the code from another Stackoverflow thread but when I try to submit a form and click submit button nothing happens. I don't even get any error messages on console also . So can any one tell me what I am doing wrong here. Here is the form
<form id="contactform" name="contactForm">
<input type="text" name="name"/><br/>
<input type="text" name="email"/><br/>
<textarea name="comment">
</textarea>
<p style='text-align:right;'><input type="submit"/></p>
</form>
Here is JS:
<script>
// variable to hold request
var request;
// bind to the submit event of our form
$("#contactform").submit(function(event){
// abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $form.serialize();
// let's disable the inputs for the duration of the ajax request
$inputs.prop("disabled", true);
// fire off the request to /form.php
request = $.ajax({
url: "form.php",
type: "post",
data: serializedData
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// log a message to the console
console.log("Hooray, it worked!");
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
console.error(
"The following error occured: "+
textStatus, errorThrown
);
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
// prevent default posting of form
event.preventDefault();
});
</script>
and finally here is post.php file.
<?php
echo $_POST['fullname']."<br/>";
echo $_POST['email']."<br/>";
echo $_POST['comment']."<br/>";
?>
Here is the url of the page which has the form: http://contestlancer.com/davidicus/
If you click on the small message icon in the header logo you will see contact form.
Regards Ahmar
Upvotes: 0
Views: 255
Reputation: 7888
You're sending request to form.php
and you said your file name is post.php
. Change this part:
request = $.ajax({
url: "form.php",
type: "post",
data: serializedData
});
To:
request = $.ajax({
url: "post.php",
type: "post",
data: serializedData
});
Upvotes: 5