How to fill php variable via jquery/ajax?

Asked

Viewed 224 times

0

I am developing a system of messages in php + mysql and in the "inbox" I am displaying the messages in table formatted, using the plugin datatables.

I happen to want to open the message in a modal when the user clicks on the subject. But I still could not find a way to "grab" the ID of the clicked message, query that message in the database and then open the data in modal.

Input box and "link" code part for the modal in the subject:

while($row = mysqli_fetch_array($result1)){
    $phpdate = strtotime( $row['criada'] );
    $mysqldate = date( 'H:i d-m-Y', $phpdate );
    echo "<tr>";
    echo "<td>" . $row['denome'] . "</td>";
    echo '<td><a data-toggle="modal" data-target="#modal-leremail" style="cursor: pointer;">' . $row['assunto'] . '</a></td>';
    echo '<td>' . $row['mensagem'] . '</td>';
    echo "<td>" . $mysqldate . "</td>";
    echo '<td></td>';
    echo "</tr>";
} ?>

I have researched several ways but still can not understand very well how to do it with jquery, ajax, etc, because I know the basics.

Theoretically, if I could get a simple way to "get" the message ID, it would only be to query the database and load the data in the modal, no?

1 answer

0

Add a div in the place where you want to display the information inside the modal:

<div id='iddeumadivvaziadentrodomodal'></div

Add onclick by calling a js function passing as parameter id:

echo "<td><a onclick(carregardados(". $row['id'] .")) data-toggle='modal' data-target='#modal-leremail' style='cursor: pointer;'>" . $row['assunto'] . "</a></td>";

After You create this function by sending the id via ajax to php, passing the id and a code as parameter.

function carregardados(id){
var result = "",cod = 2;

    $.ajax({
        type: "POST",
        dataType: "json",
        url: 'buscardados.php',
        data: {id,cod},
        error: function(jqXHR, textStatus, errorThrown) {
            alert("Falha":textStatus);
        },
        success: function(data, textStatus, jqXHR){
            result += "<div>"+data['assunto']+"</div>";


            $('#iddeumadivvaziadentrodomodal').html(result);
        }
    }); };

last time you create the php file

if($cod == 2){
    $id = $_POST['id'];
       $db = conn();
       $sql = "SELECT * FROM tuatabela WHERE id = $id";
       $result = mysqli_query($db,$sql);
       $arr  = mysqli_fetch_assoc($result);

       return $arr;
}

ready all the information Voce quizer insert vc puts in ajaz Success with the html you want.

  • It didn’t work... I used the same code and nothing happens... :(

  • check where the fault is, debug the code, find where the error is not working I use in several projects and works very well, see if the path is correct, see if it is returning something, check from js to php.

Browser other questions tagged

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