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?
– epx
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
– Dionatan
Yeah, I didn’t understand the question even then.
– epx
I’ll edit my question
– Dionatan
@epx edited my question
– Dionatan
You can swap the <script> containing code for a <script src=arquivodefuncoes.js></script> and move everything inside the <script> into that file.
– epx
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.
– epx
There are several ways to do what you want, if you stick to
evento(click, blur, focus, submit, etc...)
, the forms ofincluir(o ou os arquivos contendo as funções)
, theescopo
...– MagicHat
@Magichat is just what I need, but I can’t do it. You can adapt my code to onClick?
– Dionatan
That’s not how things work, you can tailor your code to the use of
onclick
. If you have specific questions, you can ask...– MagicHat