convert $ .getJSON script to $ .post

0

I have a problem I am trying to pass a series of $ .getJSON script to $ .post:

$(document).ready(function(){
    //getdeails será nuestra función para enviar la solicitud ajax
    var getdetails = function(id){
        return $.getJSON( "index.php", { "id" : id });
    }

    //al hacer click sobre cualquier elemento que tenga el atributo data-user.....
    $('[data-user]').click(function(e){
        //Detenemos el comportamiento normal del evento click sobre el elemento clicado
        e.preventDefault();
        //Mostramos texto de que la solicitud está en curso
        $("#response-container").html("<p>Buscando...</p>");
        //this hace referencia al elemento que ha lanzado el evento click
        //con el método .data('user') obtenemos el valor del atributo data-user de dicho elemento y lo pasamos a la función getdetails definida anteriormente
        getdetails($(this).data('user'))
        .done( function( response ) {
            //done() es ejecutada cuándo se recibe la respuesta del servidor. response es el objeto JSON recibido
            if( response.success ) {

                var output = "<h1>" + response.data.message + "</h1>";
                //recorremos cada usuario
                $.each(response.data.users, function( key, value ) {
                    output += "<h2>Detalles del usuario " + value['ID'] + "</h2>";
                    //recorremos los valores de cada usuario
                    $.each( value, function ( userkey, uservalue) {
                        output += '<ul>';
                        output += '<li>' + userkey + ': ' + uservalue + "</li>";
                        output += '</ul>';
                    });
                });

                //Actualizamos el HTML del elemento con id="#response-container"
                $("#response-container").html(output);

                } else {
                //response.success no es true
                $("#response-container").html('No ha habido suerte: ' + response.data.message);
            }
        })
        .fail(function( jqXHR, textStatus, errorThrown ) {
            $("#response-container").html("Algo ha fallado: " +  textStatus);
        });
    });
}); 

Due to the limitations to pass "N" quantities of characters per Get, in the attempt to pass it to $ .post I have this code:

var getdetails = function(id){
    return $.post('index.php',{"id":id},"json");
}

but it gives me a parseError and I have no idea what I'm doing wrong, since I think it was only necessary to change the method, send it to the server. Can you help me solve this by keeping the idea?

    
asked by Francisco Núñez 30.10.2017 в 19:36
source

2 answers

2

Analyzing the way in which you take the data of the response of the ajax function, you will have to use deferred to be able to handle the function .done()

$(document).ready(function(){
    $def = $.Deferred();
    //getdeails será nuestra función para enviar la solicitud ajax
    var getdetails = function(id){
        $.post('personas.php',{id:id}, function(respuesta){
            $def.resolve(respuesta);
        }, "json");
        return $def;
    }

//al hacer click sobre cualquier elemento que tenga el atributo data-user.....
$('[data-user]').click(function(e){
    //Detenemos el comportamiento normal del evento click sobre el elemento clicado
    e.preventDefault();
    //Mostramos texto de que la solicitud está en curso
    $("#response-container").html("<p>Buscando...</p>");
    //this hace referencia al elemento que ha lanzado el evento click
    //con el método .data('user') obtenemos el valor del atributo data-user de dicho elemento y lo pasamos a la función getdetails definida anteriormente
    getdetails($(this).data('user'))
    .done( function( response ) {
        //done() es ejecutada cuándo se recibe la respuesta del servidor. response es el objeto JSON recibido
        if( response.success ) {

            var output = "<h1>" + response.data.message + "</h1>";
            //recorremos cada usuario
            $.each(response.data.users, function( key, value ) {
                output += "<h2>Detalles del usuario " + value['ID'] + "</h2>";
                //recorremos los valores de cada usuario
                $.each( value, function ( userkey, uservalue) {
                    output += '<ul>';
                    output += '<li>' + userkey + ': ' + uservalue + "</li>";
                    output += '</ul>';
                });
            });

            //Actualizamos el HTML del elemento con id="#response-container"
            $("#response-container").html(output);

            } else {
            //response.success no es true
            $("#response-container").html('No ha habido suerte: ' + response.data.message);
        }
    })
    .fail(function( jqXHR, textStatus, errorThrown ) {
        $("#response-container").html("Algo ha fallado: " +  textStatus);
    });
});

});

The variable $ def is only a promise (deferred) of jQuery that you return in your function getdetails, which when resolved resolve() will send the function done() with all the code inside it.

    
answered by 30.10.2017 / 19:52
source
0

When in a $.post you are passing the value of dataType it is mandatory that you also execute the function success that returns the returned values, it would be something like this:

var getdetails = function(id){
    $.post('index.php',{id:id}, function(respuesta){
        return respuesta
    }, "json");
}

Although if you do not need a function that returns the values you can declare it as null :

var getdetails = function(id){
    $.post('index.php',{id:id}, null, "json");
}
    
answered by 30.10.2017 в 19:42