Prevent redirect after submitting the form

Asked

Viewed 1,667 times

0

I’m a beginner in programming and I have a little problem here. I have already done a good research here in stackoverflow, both in Portuguese and in English, but I could not adapt or put a solution in practice here. I apologize if the code hurts in your eye, but start is start, hehehe.

Here’s the thing, there’s a form that calls with action the code "contact.php" and when it clicks to send, it executes a function in javascript, a simple validation that checks if the required fields are filled with something and then the form is sent to an email. All this works very well, it turns out that after sending, it redirects to the page "contact.php" and I wanted her to do nothing, just stay on the page where appears a text saying that the message was sent. The solutions I saw were to put something like:

header("url: contato.html?sent=true");

But if I try this, it ends up returning this mistake to me:

Cannot Modify header information - headers already sent by (output >Started at /Applications/MAMP/htdocs/Contact_colab/contact.php:1)

Other solutions were in the use of AJAX, but were targeted to those who already knew how it works and I don’t know anything about it yet. There is my question, is there any way to prevent this redirection without using AJAX? Or I will have to learn emergentially?

Form

<form name="form_contato" action="contato.php"  onsubmit="return validateForm()" method="post">

  <input id="nome" name="nome" type="text"  placeholder="Nome Completo*" class="celulaContato" >
  <input name="telefone" type="text" placeholder="Telefone" class="celulaContatoESQ">
  <input name="email" type="text"  placeholder="E-mail*" class="celulaContato" >
  <input name="site" type="text"  placeholder="Website" class="celulaContatoESQ">
  <input name="empresa" type="text"  placeholder="Empresa" class="celulaContato">
  <input name="cargo" type="text"  placeholder="Cargo" class="celulaContatoESQ">
  <input name="assunto" type="message"  placeholder="Assunto*" class="celulaContatoASSUNTO" >
  <textarea name="mensagem" rows="4" placeholder="Sua mensagem*" >
</textarea>
<input  id="enviar" name="enviar" type="submit" value="Enviar">
<div id="check"><input name="newsletter" type="checkbox"> <p>Receber Newsletter</p></div>

php contact.

<?php
    $nome = $_POST["nome"] ;
    $telefone = $_POST["telefone"] ;
    $email = $_POST["email"] ;
    $site = $_POST["site"] ;
    $empresa = $_POST["empresa"] ;
    $cargo = $_POST["cargo"] ;
    $assunto = $_POST["assunto"] ;
    $mensagem = $_POST["mensagem"] ;
    $from = "Formulário de Contato - Site Colab";
    $to = "[email protected]";
    $subject = "blablabla";

    $body = "De = $nome\n E-mail: $email\n Website: $site\n Empresa: $empresa\n Cargo: $cargo\n Assunto: $assunto\n  Mensagem:\n $mensagem" ;

    if ($_POST['enviar']) {
    mail ($to, $subject, $body, $from);     
    }   

?> 

validate form.

var x = document.forms["form_contato"]["nome"].value;
    if (x == "") {
        document.getElementById("invalido_form").innerHTML = "O campo nome deve ser preenchido";
        return false
    }
        var x = document.forms["form_contato"]["email"].value;
    if (x == "") {
        document.getElementById("invalido_form").innerHTML = "O campo E-mail deve ser preenchido";
        return false;
    }
        var x = document.forms["form_contato"]["assunto"].value;
    if (x == "") {
        document.getElementById("invalido_form").innerHTML = "O campo Assunto deve ser preenchido";
        return false;
    }
        var x = document.forms["form_contato"]["mensagem"].value;
    if (x == "") {
        document.getElementById("invalido_form").innerHTML = "O campo Mensagem deve ser preenchido";
        return false;
         }

    else {
        document.getElementById("invalido_form").innerHTML = "Sua mensagem foi enviada!";
        return true;
    }
}
  • Where is the request in your javascript that you are doing ?

  • I tried to put the latter to false, but then it does not send the email. Sorry, but I didn’t quite understand what you meant by the request in my javascript, what I have of javascript is inside <script> in html

  • Learn ajax urgently bro, it is very simple and very effective if you want to show a php code that I am using ajax

3 answers

2


Insert a iframe hidden on the page:

<iframe style="display:none;" name="contato" src="contato.php"></iframe>

Add to <form> the attribute target="contato".

Thus, the form will be sent to iframe hidden inside the page itself.

  • Thanks, David! It worked smooth!

  • 1

    Very ingenious, this solution. I would particularly go for an ajax solution (but without jquery, just JS vanilla), but this is certainly the solution that requires less effort and the best to quickly make a site ready. After all, final customer doesn’t care about code aesthetics =]

  • 1

    @Jeffersonquesado It depends on the times. As the AP said it did not want Ajax, iframe would be the best solution.

  • 1

    Nor did I see this detail in the text, that ajax was not the focus. Very well repaired, if I were to answer I would take a negative for not paying attention

  • Simple and effective, but I would not leave the iframe hidden, but in a small area at the top of the form and visible, initially with src="about:blank" to a blank page and making the script write a successful or failed message as anything can happen at the time of saving to the database.

  • @Dudaskank I understand what you meant, but see, the iframe in this case is not useful for anything other than receiving the form data, so it does not need to appear... if you want to return any error, can do with javascript inside the iframe itself sending to the main screen. Iframe is a mere slave.

  • @Dudaskank It would be like in Ajax, where the page that receives the data does not appear, only processes the data.

  • @Dudaskank Making the iframe visible is good for debugging, see if it shows any errors.. after you have everything OK, hide it because it has no visual function on the page.

Show 3 more comments

1

Add the jQuery

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Form

<form name="form_contato" method="post">

  <input id="nome" name="nome" type="text"  placeholder="Nome Completo*" class="celulaContato" >
  <input name="telefone" type="text" placeholder="Telefone" class="celulaContatoESQ">
  <input name="email" type="text"  placeholder="E-mail*" class="celulaContato" >
  <input name="site" type="text"  placeholder="Website" class="celulaContatoESQ">
  <input name="empresa" type="text"  placeholder="Empresa" class="celulaContato">
  <input name="cargo" type="text"  placeholder="Cargo" class="celulaContatoESQ">
  <input name="assunto" type="message"  placeholder="Assunto*" class="celulaContatoASSUNTO" >
  <textarea name="mensagem" rows="4" placeholder="Sua mensagem*" >
</textarea>
<input  id="enviar" name="enviar" type="submit" value="Enviar">
<div id="check"><input name="newsletter" type="checkbox"> <p>Receber Newsletter</p></div>

php contact.

$nome = $_POST["nome"] ;
$telefone = $_POST["telefone"] ;
$email = $_POST["email"] ;
$site = $_POST["site"] ;
$empresa = $_POST["empresa"] ;
$cargo = $_POST["cargo"] ;
$assunto = $_POST["assunto"] ;
$mensagem = $_POST["mensagem"] ;
$from = "Formulário de Contato - Site Colab";
$to = "[email protected]";
$subject = "blablabla";

$body = "De = $nome\n E-mail: $email\n Website: $site\n Empresa: $empresa\n Cargo: $cargo\n Assunto: $assunto\n  Mensagem:\n $mensagem" ;

if ($_POST['enviar']) {
mail ($to, $subject, $body, $from);     
}

validate form.

$("#enviar").click(function(){
    var nome = $("input[name='none']").val();
    var email = $("input[name='email']").val();
    var assunto = $("input[name='assunto']").val();
    var mensagem = $("input[name='mensagem']").val();
    var invalido_form = $("#invalido_form");
    if (nome == "") {
        invalido_form.html("O campo nome deve ser preenchido");
        return false
    }
    if (email == "") {
        invalido_form.html("O campo E-mail deve ser preenchido");
        return false;
    }
    if (assunto == "") {
        invalido_form.html("O campo Assunto deve ser preenchido");
        return false;
    }
    if (mensagem == "") {
        invalido_form.html("O campo Mensagem deve ser preenchido");
        return false;
    }

    $.post("contato.php", $("form[name='form_contato']").serialize(), function(data) {
        invalido_form.html("Sua mensagem foi enviada!");
        alert(data);
    });
});
  • Good, Wéllingthon. It worked great! What you did was run php after the fields validated?

  • Using post via jQuery ajax, it gets more elegant and you can recover returned data.

0

I find the solution with iframe very good, simple and effective, and the solution with Ajax is very powerful too, and is not much more complicated, but requires that the user has enabled javascript on their page (iframe solution does not need).

The third solution, sending the form to the PHP page that does all the work, and it sending back a message in the URL, which you tried with header("url: contato.html?sent=true");, also works very well. In this option, however, the page is redirected, and maybe not the effect you seek.

To work, it is necessary to start the file without writing anything, nor with echo and not outside the tag <?php, normal HTML, or else it will take on the screen that error indicating that the header has already been sent.

To avoid this, start your file already opening the PHP tag and doing everything you need. Then resolve redirect will not have the error.

Or, use the function at the beginning [ob_start][1](), then in case you can write the will, because nothing is sent until the end of the script or even call the [ob_end_flush][1]():

<?php
ob_start();
echo 'isso vai no buffer, não direto para o browser';
header("url: contato.html?sent=true");

Now, if you have already guaranteed that there is no character before the tag in the first line and still takes the error, check without your file has not been saved as UTF-8 with GOOD (byte order Mask). This BOM is what disturbs, because it is sent before the tag, would need to save the file as UTF-8 without this BOM. I use Notepad++ on Windows, so just go to Format -> Convert to UTF-8 without GOOD and save.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.