Functions with ajax

Asked

Viewed 58 times

0

I use this code to work with ajax. It works perfectly. However it is a fixed code, but I would like to put ALL the codes I do via ajax and put in a single file and then call via functions.

Example:

arquivodefuncoes.js

cadastroUsuario(){
//aqui dentro meu ajax
}

cadastroDependentes(){
//aqui dentro meu ajax
}

I don’t know how to work with functions and calling those functions. With this, I work via form Ubmit. However, I have to keep putting the code under every form I have, so it gets messy my files.

How could I work creating functions and calling on button instead of putting the code under the </form>?

<form method=post id="simples-formulario-ajax">
<button class="btn btn-primary" type="submit" name="enviar" value="enviar" id="enviar" disabled>
        Selecione a Cor para Prosseguir :)
    </button> 
</form>


<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$('#simples-formulario-ajax').submit(function(e){
    e.preventDefault();

    if($('#enviar').val() == 'Enviando...'){
        return(false);
    }

    $.ajax({
        url: 'carrinho.php',
        type: 'post',
        dataType: 'html',
        data: {
            'acao': $('#acao').val(),
            'cod': $('#cod').val(),
            'cor': $('input:radio[name=cor]:checked').val()
        }
    }).done(function(data){
        window.location.href = "cart&";                                                                         
        //alert(data);
    });

});
</script>
  • The question is not clear enough. Do you want to take content from preventDefault() to Alert() and reuse elsewhere? That’s it?

  • Actually no. I’m calling via Ubmit, but instead of Ubmit I’d like to do via function. For so I have a file with distinct functions and not several code equal to the above scattered in various places of my project

  • Yeah, I didn’t understand the question even then.

  • I’ll edit my question

  • @epx edited my question

  • You can swap the <script> containing code for a <script src=arquivodefuncoes.js></script> and move everything inside the <script> into that file.

  • Note that you do not need to put the code in a function, you can leave it in the main scope, then it will run as soon as the file.js is loaded.

  • There are several ways to do what you want, if you stick to evento(click, blur, focus, submit, etc...) , the forms of incluir(o ou os arquivos contendo as funções), the escopo...

  • @Magichat is just what I need, but I can’t do it. You can adapt my code to onClick?

  • That’s not how things work, you can tailor your code to the use of onclick. If you have specific questions, you can ask...

Show 5 more comments

1 answer

0

You can do it this way:

Put a class in the forms you want to send via AJAX. For example, .form-ajax, and also the action where it will be sent (no need to id nor of method):

<form class="form-ajax" action="carrinho.php">
        ↑                 ↑

At the event .submit you will use as selector the class .form-ajax, that is, any form that has this class will be sent via AJAX:

$('.form-ajax').submit(function(e){

Now you need to assign the form that triggered the event submit in a variable, as it can be used inside the $.ajax:

var $this = $(this);

In the option url from AJAX you will get the attribute action form:

url: $this.attr("action"),

And on the option data, you will use the method .serializeArray(), which returns all form fields in object form:

data: $this.serializeArray()

The code will look like this:

$('.form-ajax').submit(function(e){
   e.preventDefault();

   var $this = $(this);

   if($('#enviar').val() == 'Enviando...'){
      return false;
   }

   $.ajax({
      url: $this.attr("action"),
      type: 'post',
      dataType: 'html',
      data: $this.serializeArray()
   }).done(function(data){
      window.location.href = "cart&";                                                                         
   });

});

In the case of redirection window.location.href = "cart&";, which may vary depending on the form, you can do as follows by placing a data-redir in form:

data-redir="cart&"

And in the .done you will fetch the value of this attribute data-redir. If it doesn’t exist, it does nothing:

if($this.data("redir")){
   window.location.href = "cart&";                                                                         
}

So the form would look like this now:

<form class="form-ajax" action="carrinho.php" data-redir="cart&">

And the code:

$('.form-ajax').submit(function(e){
   e.preventDefault();

   var $this = $(this);

   if($('#enviar').val() == 'Enviando...'){
      return false;
   }

   $.ajax({
      url: $this.attr("action"),
      type: 'post',
      dataType: 'html',
      data: $this.serializeArray()
   }).done(function(data){
      if($this.data("redir")){
         window.location.href = $this.data("redir");                                                                         
      }
   });

});

Browser other questions tagged

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