AJAX POST WITHOUT REFRESH

Asked

Viewed 206 times

0

I’m wanting to do a post without refresh, where it opens a confirmation modal.

But it is re-updating the site when the post is submitted and when placed the e.preventDefault(); the post does not send, because the confirmation modal does not load the data.

<form id="addEvent" method="post" action="">
      <h2>Data</h2>
      <input type="date" name="date" id="date" >
               <div class='col-sm-4'>
                </div>
      <h2>Observações</h2>
      <textarea placeholder="Observações" name="notes" cols="30" rows="10"></textarea>
      <h2>Matéria</h2>
      <select name="tags" id="mat" >
          <?php 

          $add = new USER();

                      $stmt = $add->runQuery("SELECT * FROM materias ORDER BY id_mat");
        $stmt->execute();
        $m=$stmt->fetchAll(PDO::FETCH_ASSOC);
        foreach($m as $mat) {
          $materia = $mat['materia'];
          ?>
            <option  value="<?php echo $materia;?>"><?php echo $materia;?></option>   
            <?php }?>
        </select>
        <br>
        <br>
        <input type="submit" class="o-btn js-event__save md-trigger md-setperspective" data-modal="modal-18"  id="dataform" name="dataform" value="AGENDAR">
    </form>

   <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
       $("#dataform").click(function(){
       $.ajax({
           dataType:'html',
           url:"ag-monitoria.php",
           type:"POST",
           data:$(this).serialize(),

           beforeSend: function(data){ 

            }, success:function(data){
                alert("Dados Enviados");
            }, complete: function(data){}


           });


            });
    </script>

1 answer

3


You are using the wrong event to place the order.
Instead use the onclick should use onsubmit.

The event onsubmit is called from the moment you submit the form through the mouse click.

$(()=>{
    $('#myForm').on('submit', (e)=>{
        $.ajax({
            dataType:'html',
            url:"ag-monitoria.php",
            type:"POST",
            data:$(this).serialize(),

            beforeSend: function(data){ 

            }, success:function(data){
                alert("Dados Enviados");
            }, complete: function(data){}
        });

        e.preventDefault();

    });
});

References::

Documentation on onsubmit

(e)=>{} amounts to function(e){ }

Article about Arrow Functions

  • It for refresh, but still the variables do not pass, come back null and for example when the form is submitted it executes a PDO function, where this function records in the database the variables and every time the form is submitted to the database table is not changed. OBS : In the previous code without the e.preventDefault(); he registers at the bank.

Browser other questions tagged

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