Alert de Sucesso

Asked

Viewed 44 times

0

I have a modal to mark friends, when the user clicks to mark, I call the onclick that makes the request to the controller.

I want to send a message of success to the user, I have a div with None display and I want to make it visible when the POST occurs.

However, with the POST the page is reloaded and the div is back to display None without even appearing the message.

 <div class="alert alert-success" role="alert" style="display:none;">
  Amigo marcado!</div>


function marcar(e){

        $.ajax({
          url: '/MarcarAmigo/MarcarAmigos/',
          type: "POST", 
          cache: false,
          data: {'publicacao': publicacao, 'amigos_marcados': amigos_marcados},
          success: function () {
            $(".alert").css("display", "block");
          }
        });    }  

2 answers

0

Oops, try to give a defaults Prevent

function funcaoComAjax(e) {
   e.preventDefault();
   alert("SEM RELOAD");
   // FAZ TUA REQUISIÇÃO AJAX
}
<a href="https://answall.com" onclick="funcaoComAjax(event);">Clica</a>

[editing]

I made a fiddle using jQuery (not required) with the idea of the comment, puts the default Prevent in the form Submit and makes the request ajax with the form data https://jsfiddle.net/evandrobm/xpvt214o/876386/

  • This does not serve because I need the POST for the request on the server and save the data in the database, is a Submit button because I need the Submit.

  • You can put the preventDefault in the form Submit, do the ajax with the form data, and in return ajax do the same thing

  • @Biancac. I edited the answer with an example

  • @Biancac. That solved your problem?

  • No, as I said e.preventDefault() takes the Submit function from my form

  • But do you need the form to be submitted? I thought the form action was done by the AJAX request

  • What is your form action and what does it do? And this URL /MarcarAmigo/MarcarAmigos/call on Ajax does what?

Show 2 more comments

0

The example below shows your code displaying the successful div to run ajax successfully.

function marcar(e) {

  $.ajax({
    url: '/MarcarAmigo/MarcarAmigos/',
    type: "POST",
    cache: false,
    data: {
      'publicacao': publicacao,
      'amigos_marcados': amigos_marcados
    },
    success: function() {
      //fadeIn() ou show() faz aparecer uma div oculta
      $(".alert").fadeIn()
    }
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!--Botão para chamar o evento da função ajax -->
<button onclick="marcar()">Executar Ajax</button>

<!--Sua div de sucesso oculta-->
<div class="alert alert-success" role="alert" hidden>
   Amigo marcado!
</div>

Browser other questions tagged

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