How to collect 'data-userid' from an Ajax-generated Button and use 'data-userid' in a post?

Asked

Viewed 122 times

0

I’m struggling in the following situation:

I have two pages: radioPage.php and radioPageBD.php.

In the radioPage.php the user will be able to select the RadioButton Company or the RadioButton client. The two make different queries in the database, one will bring the relationship of companies and the other of customers.

The distinction between consultations shall be made by ajax, when the user selects the Rb Client, the value 1 of a Javascript variable will be sent (var_query) for a php variable (idQuery).

If the value is 1, run the query to list companies. If the value is 2, run the query to list customers. When one of the Rb’s is selected, the content is sent to the div buttons_CE.

This Javascript variable passage for php is done on the radioPage.php

It brings these business/customer relationships recursively in Uttons. Follow the following print:

Empresa_Cliente

When the user clicks on any of these Button's, a post should be made for the page radioPageBD.php where it will return an html to the div #resultadofinal containing the information of the undertaking.

For all the Button's, there is a kind of id that is called data-userid. In that data-userid the company code is recorded so that the radioPageBD.php is able to consult company information by code (CDEMPRESA).

My question is: Why am I not managing to pass data-userid to the post and list company information?

Currently on radioPage.php I have a Post already ready. Follow the following fonts:

radioPage.php

<?php 

include('radioPageBD.php');

/* 
*  Se o idQuery possuir dados então o switchQuery recebe o idQuery. Se o switchQuery = 1 então ele faz uma consulta listando as empresas
*  Se o switchQuery = 2 então ele faz uma consulta listando os cliente.   
*/

if(isset($_GET['idQuery'])){

        $switchQuery = $_GET['idQuery'];
        if($switchQuery == 1){
                $sql = mysql_query("SELECT * FROM EMPRESA");

                 while($row = mysql_fetch_assoc($sql)) { ?>

                <button class="doQuery" data-userid="<?php echo($row['CDEMPRESA']); ?>"> <?php echo($row['DSNOMEFANTASIA']); ?></button><br>
<?php } 

        }
        else if($switchQuery == 2){ 
                $sql = mysql_query("SELECT * FROM CLIENTE");

                 while($row = mysql_fetch_assoc($sql)){ ?>

                <button class="doQuery" data-userid="<?php echo($row['CDEMPRESA']); ?>"><?php echo($row['DSCLIENTE']); ?></button><br>
<?php 
                }
        }
}
else {

?>

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
    </head>

    <body>
        <input type="radio" name="rd1" class="radio" id="rd1" nm-radio="1">Empresa</input>
        <input type="radio" name="rd1" class="radio" id="rd2" nm-radio="2">Cliente</input>

        <div id="buttons_CE"></div>
        <div id="resultadofinal"> </div>
    </body>
</html>

<script>

$(function(){   
    $.system = {};
    $.system.path = '/teste/'; // ou colocar a pasta raiz $.system.path = '/';

    /*Ao clicar nos botões "doQuery" ele atribui o valor do data-userid para o id_usuario e envia este valor para a radioPageBD.php*/

    jQuery(".doQuery").click(function(){

        var id_usuario = $(this).attr('data-userid');

        jQuery.post( $.system.path + 'radioPageBD.php' , { id_usuario:id_usuario,outraval:'valor_da_val' } , function(result,status){ 


            if( status == 'success' ){

                var json = jQuery.parseJSON(result);

                if( json.resultStatus == 'success' ){
                    jQuery("#resultadofinal").html(json.html);
                }
                else{
                    jQuery("#resultadofinal").html(json.resultMSG);

                }

            } 
            else{
                alert('Erro na requisicao jquery');
            }


        });
    });

    /*Se o radioButton rd1 estiver selecionado, ele envia o valor 1 para a variável idQuery nesta mesma página. Se o radioButton rd2 estiver selecionado, ele envia o valor 2 para a variável idQuery.*/

    $(".radio").change(function(){


                if(document.getElementById("rd1").checked){
                var var_query = 1;

                        $.ajax({
                        url: 'radioPage.php',
                        type: 'GET',
                        data: { idQuery: var_query },
                        success: function(data) {

                            $('#buttons_CE').html(data);
                         }

                        });

                 }
                else if (document.getElementById("rd2").checked){
                    var var_query = 2;

                        $.ajax({
                        url: 'radioPage.php',
                        type: 'GET',
                        data: { idQuery: var_query },
                        success: function(data) {

                            $('#buttons_CE').html(data);
                         }
                    });
            }       
    });

}); 
</script>
<?php } ?>

radioPageBD.php

<?php 

    $con   = mysql_connect('localhost','root','');
    $db    = mysql_select_db('telefones',$con);

    /* Aqui ele captura o data-userid da radioPage.php e faz uma consulta no banco de dados filtrando por esse código. */
    if( isset($_POST['id_usuario'])){

        // input    
        $id    = $_POST['id_usuario'];


        $html  = array();

        //Query a ser executada
        $sql = mysql_query("SELECT *  FROM EMPRESA E WHERE E.CDEMPRESA = '{$id}'",$con);

        if(mysql_error()){
            $html['resultStatus'] = 'error';    
            $html['resultMSG']    = mysql_error();
        } 
        else{

            if( mysql_num_rows($sql) >= 1 ){

                $html['resultStatus'] = 'success';      

                /*Quando a consulta retorna algum resultado, é enviado o HTML abaixo contendo as informações da empresa para a div resultadofinal na radioPage.php; */


                while( $row = mysql_fetch_assoc($sql) ){
                    //HTML responsável por exibir cada as informações da empresa ou do cliente. Ele passa esse HTML para a div resultadofinal.

                    $html['html'] = "

                    <label for='razaoSocial'>Razão Social:</label> 
                    <input type='text' id='razaoSocial' style='width: 300px;' value='{$row['DSRAZAOSOCIAL']}' readonly='readonly'></input>
                        <label for='nmtelefone' style='margin-left: 127px;'>Telefone:</label> 
                        <input type='text' id='nmtelefone' value='{$row['NMTELEFONE']}' readonly='readonly'></input>
                            <label for='UF' style='margin-left: 130px;'>UF: </label>
                            <input type='text' id='UF' style='width: 30px;' value='{$row['DSUF']}' readonly='readonly'></input>
                                    <br><br>
                                    <p><label for='dsusuario'>Usuário</label> 
                                    <input type='text' id='dsusuario' value='{$row['DSUSUARIO']}' readonly='readonly'></input>
                                <label for='dssenha'>Senha:</senha>
                                <input type='text' id='dssenha' value='{$row['DSSENHA']}' readonly='readonly'></input>

                            <label for='dsgestumlic'>Gestum:</label> 
                            <input type='text' id='dsgestumlic' style='width: 100px;' value='{$row['DSGESTUMLIC']}' readonly='readonly'></input>
                       <label for='nmlic'>Nº Licenças:</label>
                       <input type='text' id='nmlic' style='margin-left: width: 30px;' value='{$row['NMLIC']}' readonly='readonly'></input></p>
                        <br><br><br>
                <label for='dsobs'>OBS:</label>
                <p><textarea id='dsobs' style='max-width:955px; width: 955px; resize: vertical; ' readonly='readonly'>{$row['DSOBS']}</textarea></p>

                    ";
                }
            }
            else{
                $html['resultStatus'] = 'error';        
                $html['resultMSG'] = 'Nenhum resultado';                    
            }
        }
        // output
        echo json_encode($html);
    }

?>

Just noting that both for the company and customer Buttons, to click on one of them will be listed the company information. In the table of customers there is a FK where the company is referenced to the customer. So if I consult per customer and click on any, it will be made the consultation by FK CDEMPRESA of that client.

I count on your help, thank you!

  • Forehead jQuery(document).on('click', ".doQuery", function(){ in time of jQuery(".doQuery").click(function(){. That solves the problem?

  • take a look at $(document).delegate('.doQuery', 'click', function(){ ... });

1 answer

0

jQuery provides the function .data() to fetch attributes data-*.

In your code change

var id_usuario = $(this).attr('data-userid');

To

var id_usuario = $(this).data('userid');

another error that may be affecting the expected result: the loop that creates the <button> is before the <html>, the correct is to be placed inside the <body>.


Recommended reading: Why should we not use mysql type functions_*?

Browser other questions tagged

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