0

I am trying to populate the data in a modal via AJAX, but i am unsure how to do so.

The link right now is <a href="viewmessage.php?id='.$row['ID']'">View</a> Since there is only 1 Message in the Database, the number is 70.

I have seen multiple things online but I am not sure how to implement it.

the modal I want to use will have the ID = "messageModal" and I want to use 1 modal to populate every value. I can create a php page of viewmessage.php that will run the query and return the response.

viewmessage.php:

    $query = "SELECT * FROM `tb_cform` WHERE `ID`='$id'";

     $result = mysqli_query($link, $query);

     while ($row = mysqli_fetch_assoc($result)){

     $message = $row['subj'];
     $message .= '<hr><br>';
     $message .= $row['message'];
    }

    print $message
2
Contributors
13
Replies
81
Views
4 Months
Discussion Span
Last Post by patk570
Featured Replies
  • I got it to work, i had to modify what you put and changed a few values. The code is working like it should now. jquery: $(function(){ $('.get-msg').click(function(e){ var id = $(this).attr('data-id'); e.preventDefault(); $.ajax({ type : 'GET', url : 'viewmessage.php', data : 'dataID='+ id, success : function(r){ $('#messageModal').modal('show'); $('#messageBody').show().html(r); } … Read More

0
<!-- Modal -->
<div class="modal fade" id="messageModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div id="messageBody" class="modal-body">
        Info Should Populate Here.
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

      </div>
    </div>
  </div>
</div>

Sorry about that. I forgot one of the main parts!

0

Your php can return raw html as you've shown or json:

echo json_encode(["msg"=>$message]);

Your Ajax (using html or json as returned data)
e.g. If json:

$ajax(...)
.done(function(data){
    $('#messageBody').html( data.msg );
});

e.g. if html:

$ajax(...)
.done(function(data){
    $('#messageBody').html( data );
});
0

Hey @Diafol, So, for the AJAX Function, does that go something like this:

$('#myModal').on('show.bs.modal', function(){
$.ajax
({
   type: "POST",
   url: "viewmessage.php",
   data: data-id='+ id',
   cache: false,
   success: function(r)
   {
      $("#messageBody").html(r);
   } 
});
});

then the viewmessage.php is this:

 <?php
 $id = $_GET['id'];
$query = "SELECT * FROM `tb_cform` WHERE `ID`='$id'";

 $result = mysqli_query($link, $query);

 while ($row = mysqli_fetch_assoc($result)){

 $message = $row['subj'];
 $message .= '<hr><br>';
 $message .= $row['message'];

}

 print $message;

?>

and to call the data model:

<a href="" type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-id='.$row['ID']' data-target="#myModal">View</a>

Am i close?

0

So here is what is happening,

1) When i click on Test 1 Message, it shows the message for test 1 like it should.
2) When I click on Test 2 Message, it still shows 'test 1' Message.

I have an example username and password if you want to see.

https://tekcomsolutions.com/secure/

UName: testuser
PWord: testuser

0

So i changed it, but i am getting all sorts of errors. Here is my updated code:

$('#messageModal').on('shown.bs.modal', function() {
$.ajax({
type: "GET",
url: "https://www.tekcomsolutions.com/secure/viewmessage.php",
datatype: "html",
data:{ dataId : $(a[data-target="#messageModal"]).data('id')},
success: function(r) {
  $('#messageBody').html(r);
}
});
});

here is my link:

<a href="#" type="button" class="btn btn-primary btn-xs" id="launchModal" data-toggle="modal" data-id="'.$values['ID'].'" data-target="#messageModal">View</a>

And my viewmessage.php:

if(isset($_GET['data-id']) || is_numeric($_GET['data-id'])){
$id = mysqli_real_escape_string($link,$_GET['data-id'] );
$query = "SELECT * FROM `tb_cform` WHERE `ID`='$id'";

 $result = mysqli_query($link, $query);
 $message = "";
 while ($row = mysqli_fetch_assoc($result)){

 $message .= '<div><h4>Subject: </h4><h5>'.$row['subj'].'<h5></div>';
 $message .= '<hr><br>';
 $message .= '<div><b>Message:<br>'.$row['message'].'</b></div>';

}
 echo $message;
}
0

Your ajax...

$('#messageModal').on('shown.bs.modal', function() {
    var id = $(a[data-target="#messageModal"]).data('id'); //I have no idea if this is right
    console.log(id); //check the data you're sending with this in the console pane
    $.ajax({
        type: "GET",
        url: "https://www.tekcomsolutions.com/secure/viewmessage.php",
        dataType: "html",
        data:{ dataId : id },
        success: function(r) {
          $('#messageBody').html(r);
        }
    });
});

Your PHP...

You are sending parameter dataId, but you're checking for $_GET['data-id'] ! Use $_GET['dataId']
Assuming you have $link set to a connection
You are only retrieving ONE result so no need for while loop and you can use LIMIT clause to prevent searching rest of table after you find the first match.

if(isset($_GET['dataId']) && is_numeric($_GET['dataId'])){
     $id = mysqli_real_escape_string($link, $_GET['dataId'] );
     $query = "SELECT `subj`, `message` FROM `tb_cform` WHERE `ID`='$id' LIMIT 1";
     $result = mysqli_query($link, $query);
     $message = "";
     if($result){
         $row = mysqli_fetch_assoc($result);
         $message .= '<div><h4>Subject: </h4><h5>'.$row['subj'].'<h5></div>';
         $message .= '<hr><br>';
         $message .= '<div><b>Message:<br>'.$row['message'].'</b></div>';
         echo $message;
     }else{
         echo "No such data"; 
     }
}
0

This is the error i am getting, line 38 is $('#messageModal').on('shown.bs.modal', function() {

error:

Uncaught ReferenceError: $ is not defined
    at index.php:38
0

So i figured out the issue, it is now displaying the results, however, $(a[data-target="#messageModal"]).data('id'); will not pass the value, i had to use: var id = $("#messageID").attr("data-id");. This is working, but becuase there are multiple instances of #messageID listed, it is only showing the first result becuase you cannot have duplicate ID tags with the same information.

My question is how can i assign or get a value added after #messageID like an array using[ ] to assign a value and have it look for that then get the data-id value to pass?

0

$(a[data-target="#messageModal"]).data('id'); will not pass the value

As I suspected:

var id = $(a[data-target="#messageModal"]).data('id'); //I have no idea if this is right

This is the problem when you don't supply relevant info. We don't know the structure of the html/attributes/properties of the links you're using.

My question is how can i assign or get a value added after #messageID like an array using[ ] to assign a value and have it look for that then get the data-id value to pass?

Why are you using ids in the first place? If you must, use a classname (or more awkwardly a data attribute).

Example of links - which probably could be created by PHP in a loop (presuming):

<a href="#" class="get-msg" data-id="3">Get data 3</a>

For example:

<div id="links">
<?php foreach($idList as $id){ ?>
    <a href="#" class="get-msg" data-id="<?=$id?>">Get data <?=$id?></a>
<?php } ?>
</div>

Js handler:

$('#links').on('click', '.get-msg', function(e){
    e.preventDefault(); //prevent click doing anything silly
    var jx = $.ajax({
        //as you have it
    })
    .done(function(data){
        $('#messageBody').html(data);
        $('#messageModal').modal('show');
    })
});    

I'm assuming you only have the ONE modal in your page - you do not need one for each link, as data is loaded dynamically.

Caveat: code not tested - off top of my head.

Edited by diafol

2

I got it to work, i had to modify what you put and changed a few values. The code is working like it should now.

jquery:

     $(function(){

$('.get-msg').click(function(e){
  var id = $(this).attr('data-id');
  e.preventDefault();
   $.ajax({
      type : 'GET',
       url : 'viewmessage.php',
      data :  'dataID='+ id,
      success : function(r){
      $('#messageModal').modal('show');
      $('#messageBody').show().html(r);
    }
});

});

});

Link:

<a href="#" class="get-msg btn btn-xs btn-primary" data-id="'.$values['ID'].'">View</a>

PHP:

if(isset($_GET['dataID']) && is_numeric($_GET['dataID'])){
 $id = mysqli_real_escape_string($link, $_GET['dataID'] );
 $query = "SELECT `subj`, `message` FROM `tb_cform` WHERE `ID`='$id' LIMIT 1";
 $result = mysqli_query($link, $query);
 $message = "";
 if($result){
     $row = mysqli_fetch_assoc($result);
     $message .= '<div><h4>Subject: </h4><h5>'.$row['subj'].'<h5></div>';
     $message .= '<hr><br>';
     $message .= '<div><b>Message:<br>'.$row['message'].'</b></div>';
     echo $message;
 }else{
     echo "No such data"; 
 }
}

This code is perfect for populating a modal with information. I am posting the answer in hopes that it will help someone else out.

Basically, I had to get the var id set by using the class reconignation .get-msg then when you have that link clicked, it finds that attribute set in this case data-id and displays the results based off the link. The next is just strait AJAX call, by using GET and setting the PHP to get the dataID that is passed by AJAX, it will populate the results into the modal body on success. There are a few other properties that validates that the variable is numeric first before passing it on. With this, you just need one Modal to use and it will find any value that is assigned to the data-id attribute.

@diafol, thanks for your help on this and helping me see the err of my ways! I now have a much better understanding for ajax calls and more.

Votes + Comments
Glad it helped :)
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.