Solution ajax function [closed]

1

I need to register data with ajax, jquery and php, on each page.php I have the following code:

<script>
            function registrar(){
                var nombre=document.getElementById("nombre").value
                var ap=document.getElementById("ap_paterno").value

                $.ajax({
                    type:"POST",
                    url:"registrar.php",
                    data:{nombreUsuario:nombre,ap_paterno:ap},
                    success: function(datos)
                    {
                        swal({
                            title: "Guardar usuarios",
                            text: "¿Desea guardar los datos?",
                            type: "info",
                            showCancelButton: true,
                            closeOnConfirm: false,
                            showLoaderOnConfirm: true,
                        },
                             function(){
                            setTimeout(function(datos){
                                swal("Los datos se guardaron correctamente!");
                            }, 1500);
                        });
                    },
                    });

            }
        </script>

Is there a way to create a single ajax function in a .js file without duplicating this code in each page.php?

    
asked by Gonzalo Alberto 12.11.2016 в 08:08
source

1 answer

0
function agregar(url, data, param) {
    $.ajax({
        url: url,
        type: "POST",
        data: data,
        success: function (resp) {
            {
                param(resp);

            }
        },
        error: function (msg) {
            alert(msg);
        }
    });
}

And you would use it like that

$('button, a, input').on('click', agregar);

or inside the button, link or input

<input onClick="agregar()" value"Agregar"/>
<button onClick="agregar()">Agregar</button>
<a onClick="agregar()">Agregar</a>
    
answered by 12.11.2016 в 08:27