Treat Javascript Postback

2

Opa,

I have a page that runs a SetInterval of seconds in javascript, this page captures the data of the divs and sends via post, being that this data sent is not fixed, sometimes it can be sent 1 or more than one.

In sending, I treat this amount of integers sent and separate it by commas, that is, the .php file is received in registro_id = 1, 3, 4, 5 format.

There in php I give an explode in value and a foreach for the data query and return in Json. The problem is that if more than one value is sent via javascript, the response amount obtained in the query will be returned via json.

The response format in json is:

Se enviado apenas um ID:
[{"registro":{"registro_id":"1","estado":"1","preco":"R$ 5,99","usuario_id":"18","usuario_nome" :"joao"}}]

Se enviado apenas mais de um ID:
[{"registro":{"registro_id":"1","estado":"1","preco":"R$ 5,99","usuario_id":"18","usuario_nome" :"joao"}}]
[{"registro":{"registro_id":"3","estado":"1","preco":"R$ 3,99","usuario_id":"48","usuario_nome" :"maria"}}]

The problem is that I need to get these values in my javascript function and refresh the page fields, but different values are received for fields with distinct classes, so I tried:

    usuario_id   = $('.user-id-'+ registro_id);
    usuario_nome = $('.user-name-'+ registro_id);

The fields are with the proper classes, the variable registro_id is the same as the one received in the function in setinterval, but, this only works if only one item is sent to .php, if two are sent, nothing happens.

Summarized example:

DIVS

<div class="content_item" id="registro_1" title="registro_1">
        <div class="user-name-1" id="coupon-time"></div>
        <div class="user-id-1" id="coupon-price" style="text-align:center"></div>
</div>

<div class="content_item" id="registro_2" title="registro_2">
        <div class="user-name-2" id="coupon-time"></div>
        <div class="user-id-2" id="coupon-price" style="text-align:center"></div>
</div>

JavaScript Function

function atualizaregistro() {
    var registros = '';

    $.ajaxSetup({
        cache: false
    });
    $('.content_item').each(function() {
        var new_value = $(this).attr('title');
        if (registros != '') registros = registros + ',';
        registros = registros + new_value;
    });

    if (registros) {
        $.ajax({
            url: '_files/_update_information.php',
            dataType: 'json',
            type: 'POST',
            data: 'registro_id=' + registros,
            global: false,
            success: function(data) {


                $.each(data, function(j, item) {

                    var usuario_id = item.registro.usuario_id;
                    var usuario_nome = item.registro.usuario_nome;


                    field_user_id = $('.user-id-' + registro_id);
                    field_user_name = $('.user-name-' + registro_id);

                    field_user_id.text(usuario_id);
                    field_user_name.text(usuario_nome);


                });
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {

            }
        });
    }
}

PHP

$registros = explode(',',$_POST['registro_id']);
foreach($registros as $registro_id)
{
    ...Código Consulta BD

    $temp = '{"registro":{"registro_id":"'.$registro_id.'","estado":"1","preco":"'.$preco.'","usuario_id":"'.$usuario_id.'","usuario_nome":"'.$usuario_nome.'"}}';
}

echo "[".$temp."]";

Can anyone help?

    
asked by anonymous 12.08.2016 / 20:01

1 answer

2

I think it would be best to send a JSON, and return a JSON.

What you are doing now is to create a custom string, to make it "explode" (explode) in PHP and etc ... it is best not to reinvent the wheel.

Suggestion:

function atualizaregistro() {
    $.ajaxSetup({
        cache: false
    });
    var registos = $('.content_item').get().map(function(el) {
        return el.id;
    });

    if (registros) {
        $.ajax({
            url: '_files/_update_information.php',
            dataType: 'json',
            type: 'POST',
            data: {registro_id: JSON.stringify(registos)},

then in PHP:

$registros = json_decode($_POST['registro_id']);
$retorno = [];
foreach($registros as $registro_id){
    // etc
    $retorno[] = array(id, estado, preco, etc...)

and to return it returns the same, or at least just an array:

echo json_encode($retorno);

In this way you know in JavaScript that you have the same array order and you can do:

registos.forEach(function(id, i){
    $('#' + id).find('.coupon-time').html(data[i].preco);
    // etc...

});

That is:

  • creates an array with the elements
  • pass a JSON to, and from, PHP
  • iterates this array again and uses index to access data of ajax

Note: : You have duplicate IDs! You can only have an ID coupon-time per page. They have to be unique. In my example I changed to a class, so you group elements with the same functionality.

Anyway, it was a suggestion, I hope you can interpret and adapt it to your code.

    
12.08.2016 / 20:46