How to send form data via Javascript and redirect

Asked

Viewed 1,183 times

1

I need to have my form send data to another server page for it to enter in Mysql but redirect the user to another page but receive a success message. But for some reason, the message is missing.

Form + JS:

$().ready(function() {

    function onFinish() {
        //here you can do something, sent the form to server via ajax and show a success message with swal
        var nomep = $("#nome");
        var descricao = $("#descricao");
        var ponto_minimo = $("#ponto_minimo");
        var ponto_maximo = $("#ponto_maximo");
        var quantidade = $("#quantidade");
        var localizacao = $("#localizacao");
        var categoria_id = $("#categoria_id");
        var usuario = $("#usuario");
        var data = $("#data");
        var justificativa = $("#justificativa");

        $.post("assets/php/alterar-produto.php", {
            nome: nomep,
            descricao: descricao,
            ponto_minimo: ponto_minimo,
            ponto_maximo: ponto_maximo,
            quantidade: quantidade,
            localizacao: localizacao,
            categoria_id: categoria_id,
            usuario: usuario,
            data: data,
            justificativa: justificativa
        });

        setTimeout(function() {
            swal({
                title: "Sucesso!",
                text: "Alterações salvas com êxito",
                type: "success"
            }, function() {
                window.location = "redirectURL";
            });
        }, 1000);

    }
}
<form method="POST" action="#">
      <div class="row">
        <div class="col-md-10 col-md-offset-1">
          <div class="form-group">
            <label>Nome</label>
            <input type="text" placeholder="Insira um nome" class="form-control" value="<?=utf8_encode($produto['nome'])?>" name="nome">
          </div>
        </div>
      </div>
      
       ...Demais campos...
    </form>

Full form:

<div class="content">
  <form>
    <div class="row">
      <div class="col-md-10 col-md-offset-1">
        <div class="form-group">
          <label>Nome</label>
          <input type="text" placeholder="Insira um nome" class="form-control" value="<?=utf8_encode($produto['nome'])?>" name="nome">
        </div>
      </div>
    </div>


    <div class="row">
      <div class="col-md-10 col-md-offset-1">
        <div class="form-group">
          <label for="descricao">Descrição</label>
          <textarea class="form-control" placeholder="Insira a Descrição" rows="3" name="descricao"><?=utf8_encode($produto['descricao'])?></textarea>
        </div>
      </div>
    </div>

    <div class="row">
      <div class="col-md-5 col-md-offset-1">
        <div class="form-group">
          <label>Ponto mínimo</label>
          <input type="number" placeholder="Insira o Ponto mínimo" class="form-control" value="<?=utf8_encode($produto['ponto_minimo'])?>" name="ponto_minimo">
        </div>
      </div>
      <div class="col-md-5">
        <div class="form-group">
          <label>Ponto máximo</label>
          <input type="number" placeholder="Insira o Ponto máximo" class="form-control" value="<?=utf8_encode($produto['ponto_maximo'])?>" name="ponto_maximo">
        </div>
      </div>
    </div>

    <div class="row">
      <div class="col-md-10 col-md-offset-1">
        <div class="form-group">
          <label>Quantidade</label>
          <input type="number" placeholder="Insira uma quantidade" class="form-control" value="<?=utf8_encode($produto['quantidade'])?>" name="quantidade">
        </div>
      </div>
    </div>

    <div class="row">
      <div class="col-md-10 col-md-offset-1">
        <div class="form-group">
          <label>Localização</label>
          <input type="text" placeholder="Insira o Local" class="form-control" value="<?=utf8_encode($produto['localizacao'])?>" name="localizacao">
        </div>
      </div>
    </div>

    <?php $categorias = listaCategorias($conexao); ?>
    <div class="row">
      <div class="col-md-10 col-md-offset-1">
        <select name="categoria_id" class="selectpicker" data-title="Categoria" data-style="btn-default btn-block" data-menu-style="dropdown-blue">
                                        <?php foreach($categorias as $categoria) :
                                            $essaEhACategoria = $produto['categoria_id'] == $categoria['id'];
                                            $selecao = $essaEhACategoria ? "selected='selected'" : "";
                                            ?>
                                            <option value="<?=$categoria['id']?>" <?=$selecao?>>
                                                <?=utf8_encode($categoria['nome'])?>
                                            </option>
                                        <?php endforeach ?>
                                    </select>
      </div>
    </div>
    <br/>

    <input type="hidden" name="usuario" value="<?=$usuario?>">

    <input type="hidden" value="<?=$data = date('Y-m-d H:i'); ?>" name="data">
    <input type="hidden" value="<?=$produto['id']?>" name="id">

    <hr>

    <div class="row">
      <div class="col-md-10 col-md-offset-1">
        <div class="form-group">
          <label for="justificativa">Justificativa</label>
          <textarea class="form-control" placeholder="Insira a Justificativa" rows="3" name="justificativa" required></textarea>
        </div>
      </div>
    </div>

    <div class="row">
      <div class="col-md-10 ">
        <button type="submit" class="btn btn-fill btn-info center-block" onclick="onFinish()">Enviar</button>
      </div>
    </div>


  </form>

Inclusion of Sweetalert

<!-- Sweet Alert 2 plugin -->
<script src="assets/js/sweetalert2.js"></script>

link to what’s in the Sweetl file

https://pastebin.com/EM0nWWu0

2 answers

2

The method swal() has a Overload who receives a function, that performs the action after clicking on "Ok"

Follow an example using the library you use, Sweet Alert

 setTimeout(function() {
            swal({
              title: "Sucesso!",
              text: "Alterações salvas com êxito",
              type: "success"
            }, function() {
              window.location = "redirectURL";
            });
          }, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert-dev.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>

Javascript:

$().ready(function() {

      function onFinish() {
        //here you can do something, sent the form to server via ajax and show a success message with swal
        var nomep = $("#nome");
        var descricao = $("#descricao");
        var ponto_minimo = $("#ponto_minimo");
        var ponto_maximo = $("#ponto_maximo");
        var quantidade = $("#quantidade");
        var localizacao = $("#localizacao");
        var categoria_id = $("#categoria_id");
        var usuario = $("#usuario");
        var data = $("#data");
        var justificativa = $("#justificativa");

        $.post("assets/php/alterar-produto.php", {
          nome: nomep,
          descricao: descricao,
          ponto_minimo: ponto_minimo,
          ponto_maximo: ponto_maximo,
          quantidade: quantidade,
          localizacao: localizacao,
          categoria_id: categoria_id,
          usuario: usuario,
          data: data,
          justificativa: justificativa
        });

        setTimeout(function() {
          swal({
            title: "Sucesso!",
            text: "Alterações salvas com êxito",
            type: "success"
          }, function() {
            window.location = "redirectURL";
          });
        }, 1000);

      }
    }

html:

<form method="POST" action="#">
  <div class="row">
    <div class="col-md-10 col-md-offset-1">
      <div class="form-group">
        <label>Nome</label>
        <input type="text" placeholder="Insira um nome" class="form-control" value="<?=utf8_encode($produto['nome'])?>" name="nome">
      </div>
    </div>
  </div>

  ...Demais campos...
</form>
  • I need to put my button as "Submit"?

  • When I click the Submit button nothing happens

  • 1

    Naturally it will make the asynchronous requisition and activate the swal, after that click on the swal it will redirect.

  • 1

    But @Luhansalimena if you haven’t changed your old code, it will do the same as before, however I just added a "new parameter" that redirects when you click on the warning.

  • So I need to take the action out of the form?

  • 1

    @Luhansalimena Before, did it show the warning? If yes, when you clicked on the warning it did not redirect correctly?

  • No, neither before nor now

  • 1

    @Luhansalimena Aai gets hard kkk, you didn’t say the problem was Submit. But beauty, let’s solve your problem !

  • I tested again here and the insertion and not even the message work

  • I was able to send the data but I can’t get the message to appear

  • I will edit Javascript, correct there and see if it works.

  • @Luhansalimena you changed your JAVASCRIPT? edit the question please? thanks

  • I edited the question with the code

  • 1

    @Luhansalimena you are importing the Sweet Alert library straight ?

  • I use the code that came with my design I will ask the question

Show 11 more comments

1

use the setTimeout function, the message will appear and after a while, in case 2 seconds (2000) will redirect to your page.:

window.setTimeout("location.href='http://seusite.com'", 2000);

Browser other questions tagged

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