views:

445

answers:

6

I'm trying to make a simple MySQL Admin thing with php and jQuery. I've never used jQuery so my code is probably quite lol-worthy. The problem I'm having with the code is that when I click the button, nothing happens. I know the even fires because if I open the html file in firefox (not going to the url, using the file:/// thing) and click it, it shows my php code in the box I want the returned content to go into. The first thing i'm trying to do is connect to the database specified and return a list of the tables. Heres my code

index.html

<html>
    <head>
     <script type='text/javascript' src='jquery.js'></script>

     <script type='text/javascript'>
      var Server = 'None';
      var Username = 'None';
      var Password = 'None';
      var Database = 'None';

      $("#connect").click(function() {
       Server = $('#server').val();
       Username = $('#username').val();
       Password = $('#password').val();
       Database = $('#database').val();
       loadTables();
      });

      function loadTables() {
       $.get("display.php", { server: Server, username: Username, password: Password, database: Database, content: "tables" },
        function(data){
         html = "<ul>";
         $(data).find("table").each(function() {
          html = html + "<li>" + $(this).text() + "</li>";
          });
                                            html = html + "</ul>";
         $('#content').html(html);
        }
       );
      }
     </script>
    </head>
    <body>
     <center>
      <div class='connection'>
       <form name='connectForm'>
        Server: <input type='text' size='30' id='server' />&nbsp;
        Username: <input type='text' id='username' />&nbsp;
        Password: <input type='password' id='password' />&nbsp;
        Database: <input type='text' id='database' />&nbsp;
        <input type='button' id='connect' value='Connect' />
       </form>
      </div>
      <div id='content'>

      </div>
     </center>
    </body>
</html>

display.php

<?
mysql_connect($_GET['server'], $_GET['username'], $_GET['password'])
    or die("Error: Could not connect to database!<br />" . mysql_error());
mysql_select_db($_GET['database']);

$content = $_GET['content'];

if ($content == "tables") {
    $result = mysql_query("show tables");
    $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    $xml .= "<tables>";
    while ($row = mysql_fetch_assoc($result)) {
     $xml .= "<table>" . $row['Tables_in_blog'] . "</table>";
    }
    $xml .= "</tables>";
    header('Content-type: text/xml');
    echo $xml;
}
?>

EDIT: I have updated the code according to a mix of a few answers, but I'm still having the same problem.

A: 

I'm not sure exactly what the question is. But you don't need the $(function() {}) inside your $.get callback - passing a function to $() actually binds an event handler to the "ready" event which only gets called when your page is first loading. You just provide a function that takes your XML as a parameter (here you have it as "data" but reference it as "xml"?) and use it. I'd start by reading http://docs.jquery.com/Ajax/jQuery.get#urldatacallbacktype, and http://docs.jquery.com/Events/ready#fn. Also, install Firebug and check out the error console to see where your JavaScript is having problems - you can go to the "Script" tab and set breakpoints to see how your code is executing to get a feeling for where things are going wrong.

BRH
+1  A: 

Hi there. I hope this helps. I noticed three things about your code:

1) display.php doesn't close the tag.

2) You refer to the 'content' div using $(#content), which throws a Javascript error. Make sure to encapsulate this selector in quotes, like $('#content').

3) I'm not sure about "$("table", xml).text()". Instead, used the very cool find('tag').each() syntax to walk through the XML response. This worked for me as a replacement for your function(data) statement:

function(data) { 
 htmlTable = '<ul>';
 $(data).find('table').each(function(){ 
  htmlTable = htmlTable + '<li>' + $(this).text() + '</li>'; });
 htmlTable = htmlTable + '</ul>'
 $('#content').html(htmlTable);
});
Jeff
Firebug is a great tool, I definitely used it while reviewing this code.
Jeff
+8  A: 

Ok, firstly don't do that and by "that" I mean:

  • Don't put DB connection details in Javascript; and
  • Don't use input from the user without sanitizing it. You're just asking to be hacked.

That being said, your main problem seems to be that $(#content) should be $("#content"). Also putting an onclick on the button isn't really the jQuery way. Try:

<body>
<div class='connection'>
  <form name='connectForm'>
    Server: <input type='text' id="server" size='30' name='server' />
    Username: <input type='text' id="username" name='username' />
    Password: <input type='password' id="password" name='password' />
    Database: <input type='text' id="database" name='database' />
    <input type='button' id="connect" value='Connect' />
  </form>
</div>
<div id='content'></div>
<script type="text/javascript" src="/jquery-1.3.1.js"></script>
<script type="text/javascript">
$(function() {
  $("#connect").click(function() {
    $.get(
      "display.php",
      {
        server: $("#server").val(),
        username: $("#username").val(),
        password: $("#password").val(),
        database: $("#database").val(),
        content: "tables"
      },
      function(data) {
        $("#content").html("<ul></ul>");
        $(data).find("table").each(function() {
          $("#content ul").append("<li>" + $(this).text() + "</li>");
        });
      }
    );
  });
});
</script>
</body>

Edit: minor corrections to the above and tested with this script:

<?
header('Content-Type: text/xml');
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<root>
<?
$tables = array('one', 'two', 'three', 'four');
foreach ($tables as $table) {
    echo "  <table>$table</table>\n";
}
?>
</root>
cletus
I made updates to my code according to you're answer, but I'm still having the same problem. The new code is in the question now.
The.Anti.9
You're adding a close </ul> in every loop. Seriously install Firefox, get Firebug and look at your errors console.
cletus
Ok I fixed that, tried firefox with firebug, and looked at my errors console, and there were no errors, but alas, it still does not work.
The.Anti.9
Does going directly to display.php correctly bring up an XML document? Do you have a single root element?
cletus
Also you don't appear to have an <?xml ... ?> header at the top of your tables document.
cletus
yea i realized that a while ago and just forgot to add it to this code. it's there, and yes it brings up the xml document
The.Anti.9
problem was that the javascript had to be after the html code. fixed. I'll accept your answer because i used more of it than anyone elses
The.Anti.9
Oh I see your $("#connect").click() wasn't wrapped in $(document).ready() or $() for short. That's important.
cletus
A: 

$(#content) << This is definately a problem. Selectors must be strings, so $("#content") would be correct.

flitzwald
A: 

You should use the jQuery.forms.js plugin. http://malsup.com/jquery/form/

superUntitled
+1  A: 

Here is a working piece of code:

<script type='text/javascript'>
  function connect() {
          $.ajax({
                url:'display.php',
                type: 'POST',
                dataType:'xml',
                success: { 
                    server: $('#server').val()||'None', 
                    username: $('#username').val()||'None', 
                    password: $('#password').val()||'None', 
                    database: $('#database').val()||'None', 
                    content: "tables" 
                  },
                  function(data){
                      $('#content').html('<ul></ul>');
                      var contentUL = $('#content>ul');
                      $(data).find('table').each(function(){
                        $('<li></li>').html($(this).html()).appendTo(contentUL);
                      });                                        
                  },
                  'xml'
                });
  }
</script>
</head>
<body>
  <center>
      <div class='connection'>
          <form id="connectForm" name='connectForm'>
                  Server: <input id="server" type='text' size='30' name='server' /> 
                  Username: <input id="username" type='text' name='username' /> 
                  Password: <input id="password" type='password' name='password' /> 
                  Database: <input id="database" type='text' name='database' /> 
                  <input type='button' onclick='connect();' value='Connect' />
          </form>
      </div>
      <div id='content'>          
      </div>
  </center>
</body>

But in my opinion it's better and easier to use JSON instead of xml, it's more easier to work with it (last lines of get function):

              function(data){
                  $('#content').html('<ul></ul>');
                  var contentUL = $('#content>ul');
                  $.each(data.tables, function(){
                    $('<li></li>').html(this).appendTo(contentUL);
                  });                                        
              },
              'json');

Also you can use jquery.form plugin to submit a form. It also can update specified elements using response, example:

$(document).ready(function() {
    $('#connectForm').ajaxForm({
        target: '#content'
    });
});
zihotki