Treat Post return in Javascript

Asked

Viewed 1,203 times

2

Opa,

I have a page that runs a Setinterval of seconds in javascript, this page captures the data of Divs and sends via post, and this data sent is not fixed, sometimes, can be sent 1 or more of a.

When sending, I treat this amount of sent integers and separate it by commas, ie the file . php receives in the format registro_id = 1, 3, 4, 5.

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

The json response format 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 receive these values in my javascript function and update the page fields, but, are received different values for fields with different classes, I tried so:

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

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

Summary 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?

  • When you send two items to PHP, how do you distinguish them in Javascript and HTML? Each one has its key as user-name or each item has user-name and user-id?

  • In html each div has the fields with user-name-ID and user-id-ID, this ID is the value sent to javascript, and the same query in php

  • So the best thing would be to create a JSON in javascript with these Ids... how are you getting these values in Javascript? You can display an HTML example with two items?

  • Yes, I’ll make an example, please, just a moment

  • @Sergio I added the short example of the code, directly in the question

1 answer

2


I think you’d better send a JSON, and return a JSON.

What you’re doing now is creating a custom string, making it "explode" (explode) in PHP and so on... it’s 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)},

later in PHP:

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

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

echo json_encode($retorno);

This way you know in Javascript that you have the same array order and can do:

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

});

That is to say:

  • creates an array of elements
  • passes a JSON to, and, PHP
  • iterates this array again and uses the index to access the dataajax

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

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

  • I fully agree, I have no words to thank your suggestion, I am already adapting it to my code, but, I came across a problem, php is not recognizing the variable sent in the post Undefined index: registro_id in The variables in javascript are correct and with value, can give me a strength

  • @sNniffer I think I changed the syntax, see the data ajax again and then in PHP.

  • Show ball, Sergio not wanting to push too hard, but, takes away a quick doubt. I am sending the json and receiving from php successfully, but if sending to php only one value, the data is returned successfully, if more than one value is sent back the data referring only to the last value. There in php by foreach I saw that the ID are received correctly. Ex.: When sending ID 1 and 3, foreach is executed and sends the data only for 3.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.