blueprintChris blueprintChris - 5 months ago 7
HTML Question

Using AJAX to launch PHP without reloading page

I have the following HTML form:

<form class="clearfix" method="POST">
<input name="name" type="textbox" placeholder="Name:">
<input name="email" type="textbox" placeholder="Email:">
<textarea name="message" placeholder="Message:"></textarea>
<input name="submit" type="submit" id="submit" value="submit">
</form>


Which launches a PHP script (which works) but re-directs the user to the empty page containing the PHP (ie. goes to mywebpage.com/send_mail.php). Using AJAX, how can I launch the PHP script in the background without re-loading the page?

I have the following AJAX request but it doesn't seem to work:

$('#submit').click(function(e) {
e.preventDefault();
var data = {
name: $("#name").val(),
email: $("#email").val(),
message: $("#msg").val()
};

$.ajax({
url: '../send_mail.php',
type: 'POST',
data: data,
success: function(msg) {
alert('Email Sent');
}
});
});


Any assistance as to why it's not working? At the moment, all it does (when hitting submit) is go straight to the PHP page and seems to ignore the AJAX

Answer

It's getting reload because it's a submit button and that is added inside form so it's submitting the form on click without waiting for AJAX to get submitted.

You can use preventDefault() jQuery method to stop the page redirect. Like this,

$('#submit').click(function(e) {
 e.preventDefault();
 var data = {
    name: $("#name").val(),
    email: $("#email").val(),
    message: $("#msg").val()
 };

 $.ajax({
    url: '../send_mail.php',
    type: 'POST',
    data: data,
    success: function(msg) {
        alert('Email Sent');
    }
 });
});

When preventDefault(); method is called, the default action of the event will not be triggered.

You've also missed quotes to specify URL in .ajax().

jsFiddle: https://jsfiddle.net/3Lpft17y/