Send post data when redirecting with javascript

2

The form takes some data to obtain filtered products in an online store.

If the form has data-container = '# results_store' the answer (products) must be painted on the div with id #results_shop.

On the other hand if you do not have data-container the form has to be processed in / store? process = be and the results will be painted in that other url, this url has this code that collects the $ _POST data and paint in an already defined container:

// Búsqueda Externa des de otra página
else if (proceso == 'be')
{
    // Recogemos los datos POST
    var datos_post = <?=json_encode($_POST,JSON_HEX_QUOT | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS)?>;

    r_ajax( '/procesosajax_ec.php?proceso=ec_resultados_index&subproceso=buscador', 
            datos_post, 
            "#contenido_ajax", 
            'post',
            function(){goto_resultados()})
}

Therefore I have to do a conditional process:

  • If the form has data-container I paint the result ajax in that container

  • If the form does not have data-container redirected so that the url / store is responsible for processing the form.

I have tried using .submit () or .trigger () for the second case, but I am looping.

The Jquery code would be contained here:

    $(document.body).on( "submit", ".form_ec_buscador", function(ev) {

ev.preventDefault();

if (typeof modal_form_buscador_ec != 'undefined') {modal_form_buscador_ec.close();}

// Si hay contenedor, ejecutamos ajax y pontamos el resultado en él.
if ($(this).attr('data-contenedor'))
{
    // Si hay contenedor pintamos aquí, sino redirigimos a 
    // /tienda?proceso=be para que lo procese.
    var contenedor = $(this).data("contenedor");

    // Enviamos el formulario usando AJAX
    $.ajax({
        cache: false,
        type: 'POST',
        url: '/procesosajax_ec.php?proceso=ec_resultados_index&subproceso=buscador',
        data: $(this).serialize(),
        beforeSend: function(){
            $("body").append ('<div class="espera"></div>');
        },                  
        // Mostramos un mensaje con la respuesta de PHP
        success: function(data) {

            $(".espera").remove();
            $("#" + contenedor).html(data);
            $("html, body").animate({ scrollTop: $("#" + contenedor).offset().top }, 1000);
        },
        error: function(){
            $(".espera").remove();
            swal("¡Error!", "Se ha producido un error.", "error"); 
        }
    });
}
else
{
    $(this).attr('action', '/tienda?proceso=be');
    $(this).submit();
}


    });

And here inside would treat the previous condition.

I FOUND THIS SOLUTION THAT SEEMS TO WORK

If I have to do the submit, I do it by creating another form with a few lines of code, look at the else of this code, so I do not loop with the submit of the main form:

// Run the search / filter form // either paints the result or redirects to / store? process = be // Everything depends on the container being indicated. $ (document.body) .on ("submit", ".form_ec_buscador", function (ev) {

ev.preventDefault();

// Si hay contenedor, ejecutamos ajax y pontamos el resultado en él.
if ($(this).attr('data-contenedor'))
{
    if (typeof modal_form_buscador_ec != 'undefined') {modal_form_buscador_ec.close();}

    // Si hay contenedor pintamos aquí, sino redirigimos a 
    // /tienda?proceso=be para que lo procese.
    var contenedor = $(this).data("contenedor");

    // Enviamos el formulario usando AJAX
    $.ajax({
        cache: false,
        type: 'POST',
        url: '/procesosajax_ec.php?proceso=ec_resultados_index&subproceso=buscador',
        data: $(this).serialize(),
        beforeSend: function(){
            $("body").append ('<div class="espera"></div>');
        },                  
        // Mostramos un mensaje con la respuesta de PHP
        success: function(data) {

            $(".espera").remove();
            $("#" + contenedor).html(data);
            $("html, body").animate({ scrollTop: $("#" + contenedor).offset().top }, 1000);
        },
        error: function(){
            $(".espera").remove();
            swal("¡Error!", "Se ha producido un error.", "error"); 
        }
    });
}
else 
{
    // Creamos un objeto formulario.
    var form = $('<form></form>');

    console.log('Hacemos envío del formulario a /tienda.');

    // Le añadimos el action y el método post
    form.attr("method", "post");
    form.attr("action", '/tienda?proceso=be');

    // Del formulario lanzado, cogemos todos los campos y 
    // los añadimos al nuevo formulario.
    $.each( $(this).serializeArray(), function( indice, data ) 
    {
        var field = $('<input></input>');

        console.log('Campo: ' + indice);
        console.log('Nombre: ' + data.name);
        console.log('Valor: ' + data.value);

        field.attr("type", "hidden");
        field.attr("name", data.name);
        field.attr("value", data.value);

        form.append(field);
    });

    // Y ejecutamos un submit sobre el nuevo formulario.
    $(form).appendTo('body').submit();
}

});

    
asked by Manu Burrero Sánchez 12.12.2018 в 13:04
source

0 answers