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

0

I'm having trouble with the following situation:

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

In radioPage.php the user can select the RadioButton Company or RadioButton client. The two make different queries in the database, one will bring the business relationship and the other one of clients.

The query distinction is made by ajax , when the user selects rb Client, the value 1 of a JavaScript variable ( var_query ) will be sent to a variable in php ( idQuery ).

If the value is 1, execute the query to list the companies. If the value is 2, execute the query to list the clients. When one of the rb's is selected, the content is sent to div buttons_CE .

This variable from Javascript to php is done in radioPage.php itself

It brings these business / customer relationships recursively into buttons. Follow the print below:

WhentheuserclicksonanyoftheseButton's,apostshouldbemadetotheradioPageBD.phppagewhereitwillreturnanhtmltodiv#resultadofinalcontainingtheinformation.

ForallButton's,thereisakindofidcalleddata-userid.Inthisdata-userid,thecompanycodeissaved,sothatradioPageBD.phpcanquerythecompanyinformationbythecode(CDEMPRESA).

Myquestionis:WhyamInotbeingabletopassthedate-useridtothepostandlistthecompanyinformation?

CurrentlyinradioPage.phpIhaveaPostalreadyready.Followthesourcesbelow:

radioPage.php

<?phpinclude('radioPageBD.php');/**SeoidQuerypossuirdadosentãooswitchQueryrecebeoidQuery.SeoswitchQuery=1entãoelefazumaconsultalistandoasempresas*SeoswitchQuery=2entãoelefazumaconsultalistandooscliente.*/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><scriptsrc="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 pointing out that for both the company and customer buttons, the   clicking on one of them will list the company information. In the table   of clients there is an FK where the company is referenced for the   client. So, if I query by customer and click on some, it will be   made by FK CDEMPRESA for this customer.

I'm counting on your help, thank you!

    
asked by anonymous 02.08.2015 / 19:23

1 answer

0

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

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: loop that creates <button> is before <html> , the correct one is to be placed inside <body> .

Recommended reading: Why should not we use functions of type mysql_ *?

    
06.08.2015 / 18:40