Submit form without page reloading

ajax, forms, html, javascript

Solution

Editor's Note: This answer was historically accepted as correct, but is now outdated. While the code still works, if your target browser(s) support the FormData and Fetch APIs (ie. nearly all modern browsers), consider checking out this answer instead.

You'll need to submit an AJAX request to send the email without reloading the page. Take a look at http://api.jquery.com/jQuery.ajax/

Your code should be something along the lines of:

$('#submit').click(function() {
    $.ajax({
        url: 'send_email.php',
        type: 'POST',
        data: {
            email: 'email@example.com',
            message: 'hello world!'
        },
        success: function(msg) {
            alert('Email Sent');
        }               
    });
});

The form will submit in the background to the `send_email.php` page which will need to handle the request and send the email.

Problem

I have a classifieds website, and on the page where ads are showed, I am creating a "Send a tip to a friend" form... So anybody who wants can send a tip of the ad to some friends email-adress. I am guessing the form must be submitted to a php page right? ``` <form name="tip" method="post" action="tip.php"> Tip somebody: <input name="tip_email" type="text" size="30" onfocus="tip_div(1);" onblur="tip_div(2);" /> <input type="submit" value="Skicka Tips" /> <input type="hidden" name="ad_id" /> </form> ``` When submitting the form, the page gets reloaded... I don't want that... Is there any way to make it not reload and still send the mail? Preferrably without ajax or jquery...

Original source

Related problems