118

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...

  • 12
    To send a form you must make an HTTP request, making HTTP requests without loading the page is what Ajax means. Might as well try to drive to town without a vehicle. – Quentin May 19 '10 at 13:53
  • 11
    "without ajax or jquery" sounds like "I want a car without wheels" – Your Common Sense May 19 '10 at 13:54
  • 13
    @Keith Almost, ` – alex May 19 '10 at 13:56
  • You aren't using XmlHttpRequest specifically, but you are still calling the server asynchronously with javascript. That falls under Ajax. – Keith Rousseau May 19 '10 at 13:57
  • 16
    I read the title and thought "Ah, he just need Ajax". I was reading the question further while nipping my coffee and preparing an answer in my head. At end of the question my coffee is all over the screen... – BalusC May 19 '10 at 13:58
  • @BalusC: I completely agree. It boggles my mind that people are still afraid of using Ajax and 3rd party js libs these days – Keith Rousseau May 19 '10 at 14:08
  • @Keith The way I mentioned did not use JavaScript, so I guess you could call it *Ax* (Asynchronous XHTML) or something... :P http://jsbin.com/upize/edit – alex May 19 '10 at 14:13
  • Use the following jQuery plugin to achieve this :https://github.com/jinujd/jQuery-Async-Form – Jinu Joseph Daniel Aug 20 '15 at 20:57
  • See also https://stackoverflow.com/questions/18169933/submit-form-without-reloading-page. It was closed for being a duplicate, but offers some other useful examples. – CubicInfinity Feb 09 '22 at 20:30
  • See also modern approach to data exchange: https://stackoverflow.com/questions/29775797/fetch-post-json-data – Nik Mar 14 '23 at 01:42

18 Answers18

114

I've found what I think is an easier way. If you put an Iframe in the page, you can redirect the exit of the action there and make it show up. You can do nothing, of course. In that case, you can set the iframe display to none.

<iframe name="votar" style="display:none;"></iframe>
<form action="tip.php" method="post" target="votar">
    <input type="submit" value="Skicka Tips">
    <input type="hidden" name="ad_id" value="2">            
</form>
user2988879
  • 379
  • 2
  • 6
  • 18
Juan Diego
  • 1,165
  • 1
  • 7
  • 2
  • 3
    I used `action="about:blank"` – ThorSummoner Mar 17 '15 at 17:51
  • 4
    With this, can you still grab the values such as: `$_POST["ad_id"]` – William Sep 12 '16 at 12:21
  • Unfortunately this solution won't work for me because submitting the form causes the javascript to run again and the document-ready event is invoked. – bgh Oct 18 '18 at 06:19
  • 1
    This looks like a very good answer. But with this approach it would be impossible to handle different error codes and validation errors. But for creating some example code for someone, this could come in handy. – He Nrik Jun 11 '21 at 11:56
82

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.

Kinrany
  • 99
  • 1
  • 9
jkilbride
  • 1,333
  • 8
  • 13
24

Fastest and easiest way is to use an iframe. Put a frame at the bottom of your page.

<iframe name="frame"></iframe>

And in your form do this.

<form target="frame">
</form>

and to make the frame invisible in your css.

iframe{
  display: none;
}
Dragan Marjanovic
  • 1,287
  • 5
  • 16
  • 27
21

You either use AJAX or you

  • create and append an iframe to the document
  • set the iframes name to 'foo'
  • set the forms target to 'foo'
  • submit
  • have the forms action render javascript with 'parent.notify(...)' to give feedback
  • optionally you can remove the iframe
Sean Kinsey
  • 37,689
  • 7
  • 52
  • 71
17

SUBMITTING THE FORM WITHOUT RELOADING THE PAGE AND GET THE RESULT OF SUBMITTED DATA ON THE SAME PAGE.

Here's some of the code I found on the internet that solves this problem :

1.) IFRAME

When the form is submitted, The action will be executed and target the specific iframe to reload.

index.php

<iframe name="content" style="">
</iframe>
<form action="iframe_content.php" method="post" target="content">
<input type="text" name="Name" value="">
<input type="submit" name="Submit" value="Submit">
</form>

iframe_content.php

<?php
$Submit = isset($_POST['Submit']) ? $_POST['Submit'] : false;
$Name = isset($_POST['Name']) ? $_POST['Name'] : '';
if($Submit){
 echo $Name;
}
?>

2.) AJAX

Index.php:

<form >
    <input type="" name="name" id="name">
    <input type="" name="descr" id="descr">
    <input type="submit" name="" value="submit" onclick="return clickButton();">
</form>
<p id="msg"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
function clickButton(){
    var name=document.getElementById('name').value;
    var descr=document.getElementById('descr').value;
    $.ajax({
        type:"post",
        url:"server_action.php",
        data: 
        {  
           'name' :name,
           'descr' :descr
        },
        cache:false,
        success: function (html) 
        {
           alert('Data Send');
           $('#msg').html(html);
        }
    });
    return false;
 }
</script>

server_action.php

<?php 
$name = isset($_POST['name']) ? $_POST['name'] : '';
$descr = isset($_POST['descr']) ? $_POST['descr'] : '';


echo $name;
echo $descr;

?>

Tags:

  • I have searched a lot times on internet. I was using Jquery, but Jquery sometimes works and sometimes not, So i think ajax is best that is mention in your answer. – Sorry IwontTell Feb 26 '20 at 10:11
7

A further possibility is to make a direct javascript link to your function:

<form action="javascript:your_function();" method="post">

...

5

It's a must to take help of jquery-ajax in this case. Without ajax, there is currently no solution.

First, call a JavaScript function when the form is submitted. Just set onsubmit="func()". Even if the function is called, the default action of the submission would be performed. If it is performed there would be no way of stoping the page from refreshing or redirecting. So, next task is to prevent the default action. Insert the following line at the start of func().

event.preventDefault()

Now, there will be no redirecting or refreshing. So, you simply make an ajax call from func() and do whatever you want to do when call ends.

Example:

Form:

<form id="form-id" onsubmit="func()">
    <input id="input-id" type="text">
</form>

Javascript:

function func(){
    event.preventDefault();
    var newValue = $('#input-field-id').val();
    $.ajax({
        type: 'POST',
        url: '...',
        data: {...},
        datatype: 'JSON',
        success: function(data){...},
        error: function(){...},
    });
}
taufique
  • 2,701
  • 1
  • 26
  • 40
4

This should solve your problem.
In this code after submit button click we call jquery ajax and we pass url to post
type POST/GET
data: data information you can select input fields or any other.
sucess: callback if everything is ok from server
function parameter text, html or json, response from server
in sucess you can write write warnings if data you got is in some kind of state and so on. or execute your code what to do next.

<form id='tip'>
Tip somebody: <input name="tip_email" id="tip_email" type="text" size="30" onfocus="tip_div(1);" onblur="tip_div(2);"/>
 <input type="submit" id="submit" value="Skicka Tips"/>
 <input type="hidden" id="ad_id" name="ad_id" />
 </form>
<script>
$( "#tip" ).submit(function( e ) {
    e.preventDefault();
    $.ajax({
        url: tip.php,
        type:'POST',
        data:
        {
            tip_email: $('#tip_email').val(),
            ad_id: $('#ad_id').val()
        },
        success: function(msg)
        {

            alert('Email Sent');
        }               
    });
});
</script>
doğukan
  • 23,073
  • 13
  • 57
  • 69
Matas Lesinskas
  • 414
  • 6
  • 13
  • While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please [include an explanation for your code](//meta.stackexchange.com/q/114762/269535), as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. **Flaggers / reviewers:** [For code-only answers such as this one, downvote, don't delete!](//meta.stackoverflow.com/a/260413/2747593) – Scott Weldon Nov 03 '16 at 18:39
4

this is exactly how it CAN work without jQuery and AJAX and it's working very well using a simple iFrame. I LOVE IT, works in Opera10, FF3 and IE6. Thanks to some of the above posters pointing me the right direction, that's the only reason I am posting here:

<select name="aAddToPage[65654]" 
onchange="
    if (bCanAddMore) {
        addToPage(65654,this);
    }
    else {
        alert('Could not add another, wait until previous is added.'); 
        this.options[0].selected = true;
    };
" />
<option value="">Add to page..</option>
[more options with values here]</select>

<script type="text/javascript">
function addToPage(iProduct, oSelect){
    iPage = oSelect.options[oSelect.selectedIndex].value;
    if (iPage != "") {
        bCanAddMore = false;
        window.hiddenFrame.document.formFrame.iProduct.value = iProduct;
        window.hiddenFrame.document.formFrame.iAddToPage.value = iPage;
        window.hiddenFrame.document.formFrame.submit();
    }
}
var bCanAddMore = true;</script> 

<iframe name="hiddenFrame" style="display:none;" src="frame.php?p=addProductToPage" onload="bCanAddMore = true;"></iframe>

the php code generating the page that is being called above:

if( $_GET['p'] == 'addProductToPage' ){  // hidden form processing
  if(!empty($_POST['iAddToPage'])) {
    //.. do something with it.. 
  }
  print('
    <html>
        <body>
            <form name="formFrame" id="formFrameId" style="display:none;" method="POST" action="frame.php?p=addProductToPage" >
                <input type="hidden" name="iProduct" value="" />
                <input type="hidden" name="iAddToPage" value="" />
            </form>
        </body>
    </html>
  ');
}
Community
  • 1
  • 1
Tyler
  • 349
  • 4
  • 11
  • 3
    Don't use PHP `print` to print HTML code. Just close php tag `?>` and add the html code after. And avoid using `exit` it it isn't necessary (fatal errors, ...) – Oriol Feb 25 '13 at 20:42
  • yeah, thanks for pointing it out. This is just a necessary example, I don't really have it done this way in my system. – Tyler Mar 15 '13 at 00:33
  • That's a lot of work on this answer, but there are many others. – ReinstateMonica3167040 Oct 14 '17 at 00:53
  • the only side issue to this is the get() in it because I wouldn't want the form state book markable/cacheable. – drtechno Apr 23 '18 at 14:41
3

You can try setting the target attribute of your form to a hidden iframe, so the page containing the form won't get reloaded.

I tried it with file uploads (which we know can't be done via AJAX), and it worked beautifully.

wtaniguchi
  • 1,324
  • 14
  • 22
2

Have you tried using an iFrame? No ajax, and the original page will not load.

You can display the submit form as a separate page inside the iframe, and when it gets submitted the outer/container page will not reload. This solution will not make use of any kind of ajax.

DanC
  • 8,595
  • 9
  • 42
  • 64
1
function Foo(){  
   event.preventDefault(); 
 $.ajax(   {  
      url:"<?php echo base_url();?>Controllername/ctlr_function",
      type:"POST",
      data:'email='+$("#email").val(),
      success:function(msg)      {  
         alert('You are subscribed');
      }
   }   );
}

I tried many times for a good solution and answer by @taufique helped me to arrive at this answer.

NB : Don't forget to put event.preventDefault(); at the beginning of the body of the function .

Smita Ahinave
  • 1,901
  • 7
  • 23
  • 42
Dayz
  • 269
  • 2
  • 12
1

I did something similar to the jquery above, but I needed to reset my form data and graphic attachment canvases. So here is what I came up with:

    <script>
   $(document).ready(function(){

   $("#text_only_radio_button_id").click(function(){
       $("#single_pic_div").hide();
       $("#multi_pic_div").hide();
   });

   $("#pic_radio_button_id").click(function(){
      $("#single_pic_div").show();
      $("#multi_pic_div").hide();
    });

   $("#gallery_radio_button_id").click(function(){
       $("#single_pic_div").hide();
       $("#multi_pic_div").show();
                 });
    $("#my_Submit_button_ID").click(function() {
          $("#single_pic_div").hide();
          $("#multi_pic_div").hide();
          var url = "script_the_form_gets_posted_to.php"; 

       $.ajax({
       type: "POST",
       url: url,
       data: $("#html_form_id").serialize(), 
       success: function(){  
       document.getElementById("html_form_id").reset();
           var canvas=document.getElementById("canvas");
    var canvasA=document.getElementById("canvasA");
    var canvasB=document.getElementById("canvasB");
    var canvasC=document.getElementById("canvasC");
    var canvasD=document.getElementById("canvasD");

              var ctx=canvas.getContext("2d");
              var ctxA=canvasA.getContext("2d");
              var ctxB=canvasB.getContext("2d");
              var ctxC=canvasC.getContext("2d");
              var ctxD=canvasD.getContext("2d");
               ctx.clearRect(0, 0,480,480);
               ctxA.clearRect(0, 0,480,480);
               ctxB.clearRect(0, 0,480,480);        
               ctxC.clearRect(0, 0,480,480);
               ctxD.clearRect(0, 0,480,480);
               } });
           return false;
                });    });
           </script>

That works well for me, for your application of just an html form, we can simplify this jquery code like this:

       <script>
        $(document).ready(function(){

    $("#my_Submit_button_ID").click(function() {
        var url =  "script_the_form_gets_posted_to.php";
       $.ajax({
       type: "POST",
       url: url,
       data: $("#html_form_id").serialize(), 
       success: function(){  
       document.getElementById("html_form_id").reset();
            } });
           return false;
                });    });
           </script>
drtechno
  • 298
  • 2
  • 9
1

Modern Answer without XHR or jQuery

It's 2022, we don't need to use old tools like XHR or jQuery when we have the Fetch API and the FormData API!

The first thing we need to do is prevent the default form submission behavior from occurring with event.preventDefault():

form.addEventListener("submit", function(event){
    event.preventDefault();
    // ...
});

Now we need to replace the submission behavior with our own AJAX request. The Fetch API makes it pretty simple to post form data - just create a new FormData object, populating it with the form's values, and use it as the body of a fetch request:

fetch(form.action, {
    method: "post",
    body: new FormData(form)
});

Note that this submits an HTTP request using the multipart/form-data encoding type. If you need to post the data using the application/x-www-form-urlencoded format, create a new URLSearchParams object from the FormData object and use that as the fetch's body.1

fetch(form.action, {
    method: "post",
    body: new URLSearchParams(new FormData(form))
});

Finally, if you instead want to submit the HTTP request as JSON, use the following:2

fetch(form.action, {
    method: "post",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify(Object.fromEntries(new FormData(form)))
});

Here's a full code example:

let form = document.querySelector("form");

form.addEventListener("submit", function(event){
    event.preventDefault();
  
    fetch(form.action, {
        method: "post",
        body: new URLSearchParams(new FormData(form)) // for application/x-www-form-urlencoded
        // body: new FormData(form) // for multipart/form-data
    });
});
<form method="POST">
  <input name="name" placeholder="Name" />
  <input name="phone" type="tel" placeholder="Phone" />
  <input name="email" type="email" placeholder="Email" />
  <input name="submit" type="submit" />
</form>

1 What's the difference between the two encoding types?

2 Code based on this answer to "How to convert FormData (HTML5 object) to JSON". Note that if a key is duplicated, only the last value is used.

SuperStormer
  • 4,997
  • 5
  • 25
  • 35
  • Worked out perfectly! Very useful modern trick, especially with usage of `new URLSearchParams()` which is required to get same behavior as with normal submission, but is far not obvious. – Nik Mar 13 '23 at 23:28
  • By the way, @SuperStormer you should probably remove `new URLSearchParams(...)` in your first `fetch()` code snippet, as it duplicates below. Also, there another nice approach, which specifies that body content is 'JSON', allowing convenient and efficient general data exchange: `fetch("/api/func", { method: "POST", headers: { "Content-Type":"application/json" }, body: JSON.stringify({a:1,b:2}) });` – Nik Mar 14 '23 at 01:36
  • @Nik Oops, I must have copy-pasted the same code twice by accident. Fixed. – SuperStormer Mar 14 '23 at 07:33
-1

The page will get reloaded if you don't want to use javascript

baloo
  • 7,635
  • 4
  • 27
  • 35
-1

You will need to use JavaScript without resulting to an iframe (ugly approach).

You can do it in JavaScript; using jQuery will make it painless.

I suggest you check out AJAX and Posting.

alex
  • 479,566
  • 201
  • 878
  • 984
-1

I don't know JavaScript and I just started to learn PHP, so what helped for me from all those responses was:

  1. Create inedx.php and insert:
<iframe name="email" style=""></iframe>
<form action="email.php" method="post" target="email">
<input type="email" name="email" >
<input type="submit" name="Submit" value="Submit">
</form>
  1. Create email.php and insert this code to check if you are getting the data (you should see it on index.php in the iframe):
    <?php
    if (isset($_POST['Submit'])){
    $email = $_POST['email'];
    echo $email;
    }
    ?>
  1. If everything is ok, change the code on email.php to:
    <?php
    if (isset($_POST['Submit'])){
    $to = $_POST['email'];
    $subject = "Test email";
    $message = "Test message";
    $headers = "From: test@test.com \r\n";
    $headers .= "Reply-To: test@test.com \r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
    
    mail($to, $subject, $message, $headers);
    }
    ?>

Hope this helps for all other rookies like me :)

Viktoras
  • 1
  • 1
-5

Here is some jQuery for posting to a php page and getting html back:

$('form').submit(function() {
    $.post('tip.php', function(html) {
       // do what you need in your success callback
    }
    return false;
});
Keith Rousseau
  • 4,435
  • 1
  • 22
  • 28