0

I have a column of buttons in a table, declared like this: (file index.php) echo ''; Then this script reads the data in the row of the button clicked and posts it to another php file:

<!-- scripts that gets the lecturer chosen to SHOW functionality-->
    <script>
        $(document).ready(function(){
             $(".show-button").click(function() {
             var $row = $(this).closest("tr");    // Find the row
             var names = $row.find(".name").text(); // Find the name
             var surname = $row.find(".surname").text(); // Find the surname 
                 $.ajax({  type: "POST",  url: "show_lecturer.php", data: { x: names, y: surname}   }) 
            });
        });
</script>

That file (show_lecturer.php) stores the data read in a table (keep_track) in the database: (file show_lecturer.php)

<?php
ob_start(); //eliminates buffer collisions

    require_once('connect_db.php'); 
    $name = $_POST['x']; 
    $surname = $_POST['y'];         
    $result = pg_query(connect(), "INSERT INTO keep_track VALUES ('$name', '$surname')");   

?>

Then I create an empty dialogbox with jquery, to populate it with the data taken from the database: (file index.php)

<!-- The following script generates the empty dialog box -->
<script src="/js/jquery.min.js"></script>
<link rel="stylesheet" href="/css/jquery-ui.css">
<script src="/js/jquery-ui.min.js"></script>
<script>
    $(function() {
        //show lecturer dialog
        $("#show_dialog").dialog({autoOpen: false});
        $(".show-button").on("click", function() {$("#show_dialog").dialog("open");});
    });
</script>

Then these data are taken from the table keep_track and echoed in the above dialog: (file index.php)

        $name; $surname;
        require_once('connect_db.php'); 

                $firstname = pg_query(connect(), "SELECT name FROM keep_track");
                while($row = pg_fetch_array($firstname)){ $name = $row['path']." ".$row['name'];    }
                $lastname = pg_query(connect(), "SELECT surname FROM keep_track");
                while($row = pg_fetch_array($lastname)){ $surname = $row['path']." ".$row['name'];  }       
                echo '<div id="show_dialog" class="ui-dialog-content ui-widget-content">';      
                echo $name."".$surname; 
                echo '</div>';

?>

So when I click the button of row x, a dialogbox opens with the data from the row x.

The only thing that is not working correctly is this: The moment I click button x, it opens a dialog but displays a value, but not that of row x. However, when i see the database, the row x is stored there. The value in the checkbox is that of the button clicked before the latest refresh on the page. Its as if there is some mistake in my chain of calls or something (that I cant figure out, thats why Im asking).

To illustrate the data I get: (Initially the table keep_track is empty)

Press button 1 -> row 1 stored, dialogbox has no content
Press button 2 -> row 2 stored, dialogbox has no content
Press button 3 -> row 3 stored, dialogbox has no content
  Refresh page manually
Press button 4 -> row 4 stored, dialogbox has content from row 3
Press button 5 -> row 5 stored, dialogbox has content from row 3
  Refresh page manually
Press button 6 -> row 6 stored, dialogbox has content from row 6
Press button 7 -> row 7 stored, dialogbox has content from row 3
Lazarus Rising
  • 2,597
  • 7
  • 33
  • 58

2 Answers2

1

I suggest you return your data from the POST via JSON. And please be aware that an AJAX Call is asynchronous. So you won't know when the reply is coming. So you need to process your results using the ajax Success callback function.

</script>
$(document).ready(function(){
         $(".show-button").click(function() {
         var $row = $(this).closest("tr");    // Find the row
         var names = $row.find(".name").text(); // Find the name
         var surname = $row.find(".surname").text(); // Find the surname 
         do_post_and_show_info(names, surname);
        });
    });

function do_post_and_show_info(names, surname){
  request= $.ajax({
    type:      "post",
    cache:     false, 
    url:       "show_lecturer.php", 
    data: { x: names, y: surname}  ,
    dataType: "json",
    });

    request.done(function(json){
        if (json.status =="ok"){
            // DO YOUR THING!   
            Alert(json.data.names + " " + json.data.surnames);
        }
        else {
            alert("Error! " + json.error + " : " + json.remarks);
        }
    });


    request.fail(function(jqXHR, textStatus) {
        alert( "Request failed: " + textStatus  + ":" + jqXHR.responseJSON); 
    });  
}//do_post_and_show_info
</script>

I usually return a datastructure like this in PHP (so in your show_lecturer.php)

<?
  // get your data before this in the variable $data
  // put your status "OK" or "ERROR" in $status
  // put some error info in $extraInfo
// of course some processing is involved, but here's a simple example

require_once('connect_db.php'); 

$name    = $_POST['x']; 
$surname = $_POST['y'];         
$result  = pg_query(connect(), "INSERT INTO keep_track VALUES ('$name', '$surname')");   
// obviously you need to do some error checking, but here's the happy flow
$status = "OK";
$error  = "";

$data['names']    = $name;
$data['surnames'] = $surname;


echo json_encode(array(
    "status" => $status,
    "error"  => $error,
    "remark" => $extraInfo,
    "data"   => $data
  ));

?>

Please be aware this is an example that I have created here in the editor and not in a real working setup. SO please try to understand it instead of copy-pasting it and giving it a run.

Pianoman
  • 327
  • 2
  • 10
  • 1
    Have your looked in the Network monitor of Google Chrome or Internet Explorer to have a look at the actual answer from the ajax post? This could show there is more than just JSON in your reply from show_lecturer.php. Problem is that you cannot send an AJAX query and wait for the answer. Your javascript code will always continue. So when do you build the Dialog box? Maybe I don't understand how all the code fits in your source files. – Pianoman Feb 06 '15 at 13:37
  • Extended my answer to include some more of your code in order make it more clear. I do not understand how the third and fourth code block fit in your source code files. Could you elaborate? – Pianoman Feb 06 '15 at 13:52
  • 1
    Trying to beat async ajax is like beating an elephant to death using breadcrumbs: it can't be done. You need to adapt your way of working. Opening the network monitor can be done using the function key F12. A new section will open up below. Search for the Network Tab. Usually you must start the logging using a button. Then refresh your page and start working. You'll see the requests passing by. Select one and view headers and response messages. Usually this will help a LOT. – Pianoman Feb 06 '15 at 13:53
  • what about delaying part of the jquery and php code until ajax returns some confirmation that it did its thing? That would help a lot. Also, the ajax calls are executed normally (I can see their results in the database entries). However, php select query is unable to read anything inserted after the last refresh of the page. – Lazarus Rising Feb 06 '15 at 14:03
  • Waiting is not an option. You need to install some handler that is called when the ajax call returns an answer. I know it's hard, I was in denial for a long time about this ajax way of working. Could you elaborate why you need two PHP scripts? Normal AJAX scripts (your .php file) do two things: handle and process and then return some status or new data (usually in JSON). SO why separate these two? – Pianoman Feb 06 '15 at 14:11
  • Because, I need to display the data in a certain format (the famous dialog box) that I was unable to write with anything else but php. In fact, I dont really intend to display the same data that I post with ajax. I will write a php query to get rows from another table that match the row where Im pressing the button. – Lazarus Rising Feb 06 '15 at 14:14
  • I've seen you've asked this question before and got some pretty good answers. Maybe you're completely on the wrong track. Why do you need to generate HTML for the dialog box using a PHP file ? Why not use JQuery for that too?`var someDiv=$("
    "); $(someDiv).html("

    hello " + surname + "

    "); $("#show_dialog").append(someDiv);`
    – Pianoman Feb 06 '15 at 14:18
  • Because it doesnt work. The content of that box will be php - generated (i will get lots of data from the database and write them on it). And I cannot write php inside jquery. – Lazarus Rising Feb 06 '15 at 14:23
  • Oke, fair enough. Then there are two other options: call AJAX and instruct it to return HTML instead of JSON. Then add the received data using jquery. Other option is to just return the new data using JSON and create the HTML in JQuery as instructed in my previous comment. This is the recommended way. Calling a PHP file just to setup some HTML is not a common solution. I could adapt the answer to reflect this. I know you cannot write PHP in jquery, but learning to build HTML in JQuery isn't very different from PHP. – Pianoman Feb 06 '15 at 14:25
  • You have a very good point there. However, the data I need to display are php - generated (results of a postgresql query). That's why I'm stuck – Lazarus Rising Apr 21 '15 at 09:26
0

I wrote the content of the dialog (div) in another file and used

$("#div").load("content.php", {x:parameter_1, y:parameter_2, ......});

instead of

$.ajax({  type: "POST",  url: "show_lecturer.php", data: { x: names, y: surname}   }) 

This did the trick.

Now the div is initially invisible and empty, but once the button is clicked, it requests the content.php page to load. Since I'm passing the search parameters when I request the content, I get the data that I wanted.

The problem from before was that when the page loaded, the div was created with the data (even though I hadn't clicked any button). Therefore, when I 'd click a button, it would show me the div with the content from the last page load (last refresh).

There were also other minor changes I had to do to make it work, but this is the main idea.

Lazarus Rising
  • 2,597
  • 7
  • 33
  • 58