AJAX error, does not send the data

Asked

Viewed 89 times

-3

I do not understand yet why it does not send via POST the data in AJAX, goes straight to error, and opens the Modal saying that there was the error and quickly directs to the page, even this modal not being for this... I put Alert and it does the same thing, opens the Error Alert and directs to page...

I need to understand about this situation to send my data via POST and ajax

$(document).on("click", '#updateStatusEquip', function() {
    $.ajax({
      type: "POST",
      data:  { value_id : $('#admin_id').val() },      
      success: function(data) {
      // Check the output of ajax call on firebug console
        console.log(data);
        
        $(".modal-body-info").html("Sucesso: Status do Registro alterado com sucesso");
        $("#myModalMessage").modal("show");
      },
      error: function () {
        $(".modal-title").html("Erro");
        $(".modal-body-info").html("Erro: Registro não foi inserido");
        $("#myModalMessage").modal("show");
      }
    });   
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- Modal - Message -->
<div class="modal fade" id="myModalMessage" tabindex="-1" role="dialog" aria-labelledby="myModalMessage">
 <form method="post" id="ze-form" >
 
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title"></h4>
        <button type="button" class="close" id="reloadTable" data-dismiss="modal" aria-label="Fechar"><span aria-hidden="true">&times;</span></button>
      </div>
      <div class="modal-body">
        <div class="modal-body-info">
        <b>Registro de:</b><br>Jonhy<input type="hidden" name="admin_id" id="admin_id" value="2"><br><b>Têm certeza que deseja alterar o status desse registro?</b><br>Poderá não ser capaz de acessar o Sistema</div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-danger" id="reloadTable" data-dismiss="modal">Fechar</button>
        <div class="modal-footer-button"><button type="submit" name="updateStatusEquip" id="updateStatusEquip" title="Alterar..." class="btn btn-warning">Alterar <i class="fas fa-level-up-alt ze-icon-m"></i><i class="fas fa-level-down-alt ze-icon-m"></i> </button></div>
      </div>
    </div>
  </div>
 </form>
</div>

  • 1

    Friend, I think you forgot to inform the data sending url

  • But to avoid creating several php... wanted it to be on the same page... where opens the modal within sucess, I put an Insert in php with isset condition of the value in POST

  • You must enter the url to which this data will be sent... If you want to send to the same URL, enter the url you are.

  • Even added, nothing has changed.... url: 'index.php? page=equipList',

  • So I think you better give me another url so that this data is sent, it would be more organized and I believe that it would not break so much the head as this...

  • What I am checking that even with another URL as propos, does not go to Sucess... The parameters are being sent, but is being directed to the error, and even with Alert, it opens the Alert and directs quickly to the main page... I think it should be related to the . js files of the page, because I see no other explanation... I’ve used $.post as well and other templates... Do they have to do with jquery I use? 3.4.1?

Show 1 more comment

3 answers

0

Matheus,

 // AJAX - Deletar
  $(document).on("click", "#deleteEquip", function() {

    var dados = {
      buttonAcess: $('#acessDeleteEquip').val(),
      value_id: $('#admin_id').val(),
    }

    $.ajax({
      type: "POST",
      data:  dados,
      async : true,
      cache : false,
      dataType : 'html',
      contentType: "application/x-www-form-urlencoded;charset=UTF-8",      
      success: function(data) {
        console.log(data);
        table.ajax.reload();      
        $('.modal-title').html('Deletar');
        <?php

        if(isset($_POST) && !empty(utf8_decode($_POST['buttonAcess']))){
            
          $update = $datasource->deleteEquip($_POST['value_id']);
            
          if ($update) {                        
          ?>        
            $(".modal-body-info").html("<div class='alert alert-success ze-center'>Registro deletado com sucesso<br><i class='fas fa-thumbs-up ze-icon-g'></i></div>");     
          <?php }
          else{ ?>
            $(".modal-body-info").html("<div class='alert alert-danger ze-center'>Erro: Envio [1] (PHP)<br><i class='fas fa-thumbs-down ze-icon-g'></i></div>");     
          <?php
          }
        }
        else{ ?>
          $(".modal-body-info").html("<div class='alert alert-danger ze-center'>Erro: Envio [2] (PHP)<br><i class='fas fa-thumbs-down ze-icon-g'></i><?php echo $_POST['value_id']; ?></div>");
        <?php } ?>

        $('.modal-footer-button').html('');
        $("#myModalMessage").modal("show");
      },
      error: function(error) {
        console.error(error);
        $('.modal-title').html('Deletar');
        $(".modal-body-info").html("<div class='alert alert-danger ze-center'>Erro: Envio [3] (AJAX)<br><i class='fas fa-thumbs-down ze-icon-g'></i></div>");     
        $('.modal-footer-button').html('');
        $("#myModalMessage").modal("show");
      }    
    });
  });
  // AJAX - Deletar - End

0


Sending with ajax(1) and form(2)

<?php

if(isset($_POST) && !empty($_POST['value_id'])){
    echo $_POST['value_id'];
    exit;
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Post Ajax to Same Page</title>
</head>
<body>

    <form id="myForm" action="" method="post">
        <input type="text" id="admin_id" value="2" />
        <button type="submit">Via form</button>
    </form><br>

    <button id="buttonAjax">Via ajax</button>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>

        //1
        $(document).on("click", "#buttonAjax", function() {
            $.ajax({
                type: "POST",
                data:  { value_id : $('#admin_id').val() },      
                success: function(data) {
                    console.log(data);
                },
                error: function (error) {
                    console.error(error);
                }
            });   
        });

        //2
        $(document).on("submit", "#myForm", function(event) {

            $.ajax({
                type: "POST",
                data:  { value_id : $('#admin_id').val() },      
                success: function(data) {
                    console.log(data);
                },
                error: function (error) {
                    console.error(error);
                }
            });

            event.preventDefault();

        });

    </script>

</body>
</html>

1

Note that you are trying to send with ajax, but the button with id="updateStatusEquip" is inside a form with the method="post" and that button has the type="submit". That is, possibly the error occurs by trying to send two POST requests simultaneously, one via form and the other via ajax.

2

If the origin of the data sent is a modal, you can leave the type="submit" button inside the modal form and make your javascript capture form Submit event, only that you will stop this event, with event.preventDefault() and create an ajax request as before. This will allow you to send the data and prevent page refresh.

I hope I’ve helped.

  • Thanks Matheus, I’m adjusting and I get it, but the e.preventDefault(); I put how and where? Sorry but I’m starting

  • You put it in the same way I used it in the code above. I modified the code to illustrate it for you. I have tested and is working both ways: with ajax directly and with form. Repair the code below the //2.

  • Matheus, Another question that even in yours did not work... I see in the browser that the value runs in the POST, but does not capture in PHP... Can you tell me why? I believe it is something between the form of sending before entering the ajax... Output goes to sucess and when enter does not capture value...

  • What exactly do you mean by "but not in PHP"? If you modify the snippet of my code "echo $_POST['value_id'];" to "echo $_POST['value_id'] + 2;" in the case of sending a numeric value in value_id you will notice that in the javascript Success you will return the value passed + 2. This means that you can perform an operation processed by PHP. Is that it? If the answer was helpful to your initial doubt, please vote yes.

  • What I want is to put a php IF after sucess capturing the value_id, so I avoid creating several phps files for each upload I have to do... So I see that the value ran in the "value_id=13" console for example, but in PHP, isset($_POST... did not "capture" this value... so it does not perform the change function in the BD... Got it? ...

  • Dude, you shouldn’t mix javascript and php like this. The code is ineligible. As some have already put it, the correct thing, in fact, would be to separate your html code such as links, menus, text and modals from your php code and also your javascript code into DISTINCT files. But no problem, then look for Separation of Concerns. I understand you want to delete a record from the database that has the id sent. You should move all the php code to the top of the file, as my example, and give an "echo" in some variable that will tell if the operation in BD has successfully occurred or not.

  • This return of php’s "echo", will be in the variable date in javascript Success. With it (date variable), you can do the IFS and ELSES, in the javascript itself, to define what will be displayed or not to the user, as the fill that is doing like this: "$(".modal-body-info"). html()". Understands?

  • I understand that we should separate, but if the received value is in POST and PHP get this value when it is sent, I believe I have no problems.. But anything I will have to create several sending phps files to work with ajax... That’s what I said in the last comment, I need to take the value of the "date" that comes from AJAX and so in the $_POST captures it, and so runs PHP... I am using the same Modal for all actions, soon finishing this "model", the rest will be easy to do

  • For example, that java event I put like this... became more practical... and it worked... $("#defaultForm"). Submit(Function(Ev) { Ev.preventDefault(); });

Show 4 more comments

0

So,

I got it this way, but the page makes the refresh... and only using Alert... When I put to open a Modal, gives error... must be something else wrong.

Even taking the type of button (Submit)... after Alert Success he gives the refresh on the page... How do I solve this?

// AJAX - Alterar Status

$(document).on("click", '#updateStatusEquip', function() {

  // dados de exemplo
  var dados = {
    admin_id: $('#admin_id').val(),
  }

  $.ajax({
    type : "POST",
    url : "php_action/updateStatusEquip.php",
    data : dados, 
    async : false,
    cache : false,
    dataType : 'html',
    contentType: "application/x-www-form-urlencoded;charset=UTF-8",
    success: function(response) {
      alert("Cadastrado com sucesso!");
    },

    error: function(error) {
      alert("Erro ao tentar realizar o cadastro!");
    }    
  });   
});
// AJAX - Alterar Status - End

Browser other questions tagged

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