2

I have a problem with updating the data I display from my db. Initially, when the page opens I display the date corresponding to the current date but then the user can change the date by entering it in a text box and when he clicks update all the data displayed should be deleted and the data corresponding to the new date should be displayed. Right now I have a javascript function which deleted all the data in the div when the button is clicked. The div holds the data I want to change. But I don't know how to add new data into the div. I tried to add php code to look up the database for the data in the javascript function but I don't know how to add it to the text box.

function changedate()
{
    document.getElementById("label1").innerText=document.getElementById("datepicker").valu e;
    document.getElementById("selecteddate").innerText=document.getElementById("datepicker"  ).value;
    document.getElementById("teammembers").innerHTML = "";//empties the div(teammembers)

    <?php
    $con=mysqli_connect("localhost","*****","*****","*****");
    $result = mysqli_query($con,"SELECT * FROM users");
    while($row = mysqli_fetch_array($result))
    {
        if(trim($user_data['email'])!=trim($row['email']))
        {
            $email_users = $row['email'];
            //I want to first show this email but I don't know how to add it to the div.
        }
    }
    ?>
}
avink
  • 55
  • 1
  • 5
  • 1
    You need to make an ajax call to a php script that returns your new data, then in the ajax success handler update your divs with the new data. – Nelson May 31 '13 at 16:16
  • 1
    You can't mix javascript code and php code that way, they are independent, javascript runs in the client (browser) while php runs on the server. – Nelson May 31 '13 at 16:17

3 Answers3

0

You can use a combination of jQuery and AJAX to do this. Much simpler than it sounds. To see that this is the right answer for you, just view this example.

In the below example, there are two .PHP files: test86a.php and test86b.php.

The first file, 86A, has a simple selection (dropdown) box and some jQuery code that watches for that selection box to change. To trigger the jQuery code, you could use the jQuery .blur() function to watch for the user to leave the date field, or you could use the jQueryUI API:

$('#date_start').datepicker({
    onSelect: function(dateText, instance) {

        // Split date_finish into 3 input fields                        
        var arrSplit = dateText.split("-");
        $('#date_start-y').val(arrSplit[0]);
        $('#date_start-m').val(arrSplit[1]);
        $('#date_start-d').val(arrSplit[2]);

        // Populate date_start field (adds 14 days and plunks result in date_finish field)
        var nextDayDate = $('#date_start').datepicker('getDate', '+14d');
        nextDayDate.setDate(nextDayDate.getDate() + 14);
        $('#date_finish').datepicker('setDate', nextDayDate);
        splitDateStart($("#date_finish").val());
    },
    onClose: function() {
        //$("#date_finish").datepicker("show");
    }
});

At any rate, when the jQuery is triggered, an AJAX request is sent to the second file, 86B. This file automatically looks stuff up from the database, gets the answers, creates some formatted HTML content, and echo's it back to the first file. This is all happening through Javascript, initiated on the browser - just like you want.

These two files are an independent, fully working example. Just replace the MYSQL logins and content with your own fieldnames, etc and watch the magic happen.

TEST86A.PHP

<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script type="text/javascript">
            $(function() {
//alert('Document is ready');

                $('#stSelect').change(function() {
                    var sel_stud = $(this).val();
//alert('You picked: ' + sel_stud);

                    $.ajax({
                        type: "POST",
                        url: "test86b.php", // "another_php_file.php",
                        data: 'theOption=' + sel_stud,
                        success: function(whatigot) {
//alert('Server-side response: ' + whatigot);
                            $('#LaDIV').html(whatigot);
                            $('#theButton').click(function() {
                                alert('You clicked the button');
                            });
                        } //END success fn
                    }); //END $.ajax
                }); //END dropdown change event
            }); //END document.ready
        </script>
    </head>
<body>

    <select name="students" id="stSelect">
        <option value="">Please Select</option>
        <option value="John">John Doe</option>
        <option value="Mike">Mike Williams</option>
        <option value="Chris">Chris Edwards</option>
    </select>
    <div id="LaDIV"></div>

</body>
</html>

TEST86B.PHP

<?php

//Login to database (usually this is stored in a separate php file and included in each file where required)
    $server = 'localhost'; //localhost is the usual name of the server if apache/Linux.
    $login = 'abcd1234';
    $pword = 'verySecret';
    $dbname = 'abcd1234_mydb';
    mysql_connect($server,$login,$pword) or die($connect_error); //or die(mysql_error());
    mysql_select_db($dbname) or die($connect_error);

//Get value posted in by ajax
    $selStudent = $_POST['theOption'];
    //die('You sent: ' . $selStudent);

//Run DB query
    $query = "SELECT `user_id`, `first_name`, `last_name` FROM `users` WHERE `first_name` = '$selStudent' AND `user_type` = 'staff'";
    $result = mysql_query($query) or die('Fn test86.php ERROR: ' . mysql_error());
    $num_rows_returned = mysql_num_rows($result);
    //die('Query returned ' . $num_rows_returned . ' rows.');

//Prepare response html markup
    $r = '  
            <h1>Found in Database:</h1>
            <ul style="list-style-type:disc;">
    ';

//Parse mysql results and create response string. Response can be an html table, a full page, or just a few characters
    if ($num_rows_returned > 0) {
        while ($row = mysql_fetch_assoc($result)) {
            $r = $r . '<li> ' . $row['first_name'] . ' ' . $row['last_name'] . ' -- UserID [' .$row['user_id']. ']</li>';
        }
    } else {
        $r = '<p>No student by that name on staff</p>';
    }

//Add this extra button for fun
    $r = $r . '</ul><button id="theButton">Click Me</button>';

//The response echoed below will be inserted into the 
    echo $r;

Here is a more simple AJAX example and yet another example for you to check out.

In all examples, note how the user supplies the HTML content (whether by typing something or selecting a new date value or choosing a dropdown selection). The user-supplied data is:

1) GRABBED via jQuery: var sel_stud = $('#stSelect').val();

2) then SENT via AJAX to the second script. (The $.ajax({}) stuff)

The second script uses the values it receives to look up the answer, then ECHOES that answer back to the first script: echo $r;

The first script RECEIVES the answer in the AJAX success function, and then (still inside the success function) INJECTS the answer onto the page: $('#LaDIV').html(whatigot);

Please experiment with these simple examples -- the first (simpler) linked example doesn't require a database lookup, so it should run with no changes.

Community
  • 1
  • 1
cssyphus
  • 37,875
  • 18
  • 96
  • 111
0

You want to output a literal JS statement with whatever you get back from php, basically:

document.getElementById("teammembers").innerHTML = // notice no erasing, we just
                                                   // overwrite it directly with the result

"<?php
  $con=mysqli_connect("localhost","*****","*****","*****");
  $result = mysqli_query($con,"SELECT * FROM users");
  while($row = mysqli_fetch_array($result))
  {
      if(trim($user_data['email'])!=trim($row['email']))
      {
          $email_users = $row['email'];
          //I want to first show this email but I don't know how to add it to the div.
          // so just show it!
          echo $email_users;     // think about this for a second though
                                 // what are you trying to achieve?
      }
  }
  ?>"
Blindy
  • 65,249
  • 10
  • 91
  • 131
-1

This is a vast question, not very specific. Checkout more about AJAX requests - basically from javascript you will have a call to the server that retrieves your data. This is a snippet from the javascript library jQuery :

   $.ajax({
  type: "POST",
  url: "emails.php",
  data: { user: "John" }
}).done(function( msg ) {
  $('teammembers').html(msg);
});

hope this will give you a starting point

Mihai Crăiță
  • 3,328
  • 3
  • 25
  • 37