3

If I click on the button "Send", a message will be placed inside a client sql database and a notification is shown.

However, this only works if I refresh the page first!

How do I make the function to start working immediately? I've already tried to place the function "addMessage" inside the $(document).ready(function() but then the function stops working entirely. See the code below:

<script>
        var db;

        $(document).ready(function()    {
            //Opens the database
            try
            {
              if (!window.openDatabase) {
                    alert('Not supported -> Please use a webkit browser');
              } else {
                  var shortName = 'Rvpk';
                  var version = '1.0';
                  var displayName = 'The Rvpk databse';
                  var maxSize = 3072*1024; //  = 3MB in bytes 65536
                  db = openDatabase(shortName, version, displayName, maxSize);      
                  }  
            }
            catch(e)
            {
              if (e == 2) {
                  alert("Invalid database version.");
              } else {
                  alert("Unknown error "+e+".");
              }return;
            }

            //If needed creates the messagetable
            db.transaction(function (tx) {
                 tx.executeSql('CREATE TABLE IF NOT EXISTS message (id INTEGER PRIMARY KEY, name)')                    
            });
        });

        //The function addMessage takes the entered message from the message inputfield and places it inside the messagetable
        function addMessage(){
        var message = $('input:text[name=message]').val();

            db.transaction(function (tx) {
                     tx.executeSql("INSERT INTO message (id, name) VALUES (NULL, ?)", [message]);
            });
            console.log("Message "+ message +" added to database");

            //Shows a notification that sending the message was a success
            alert('The message has been sent');

            //Update the messages
            updateMessages();            
        }    
    </script>
    </head>

    <body>
    <?php include("includes/header2.php"); ?>

                <div data-role="content">
                    <form>
                        <fieldset>
                            <label id="messagelabel" for="message">Message:</label>
                            <input id="message" type="text" name="message" value="This can't go on like this">
                            <button onClick="addMessage()" data-theme="g">Send</button>
                        </fieldset>
                    </form>
                </div> 
t0byman
  • 31
  • 1
  • 5

4 Answers4

1

Please try this:

document.ready is run only on page load. Instead use it in a separate function and call that function whenever you want. copy and paste following script.

<script>
        var db;

        function runThis()
        {
            //Opens the database
            try
            {
              if (!window.openDatabase) {
                    alert('Not supported -> Please use a webkit browser');
              } else {
                  var shortName = 'Rvpk';
                  var version = '1.0';
                  var displayName = 'The Rvpk databse';
                  var maxSize = 3072*1024; //  = 3MB in bytes 65536
                  db = openDatabase(shortName, version, displayName, maxSize);      
                  }  
            }
            catch(e)
            {
              if (e == 2) {
                  alert("Invalid database version.");
              } else {
                  alert("Unknown error "+e+".");
              }return;
            }

            //If needed creates the messagetable
            db.transaction(function (tx) {
                 tx.executeSql('CREATE TABLE IF NOT EXISTS message (id INTEGER PRIMARY KEY, name)')                    
            });
        }

        //The function addMessage takes the entered message from the message inputfield and places it inside the messagetable
        function addMessage(){

        //call db access function.
        runThis();

        var message = $('input:text[name=message]').val();

            db.transaction(function (tx) {
                     tx.executeSql("INSERT INTO message (id, name) VALUES (NULL, ?)", [message]);
            });
            console.log("Message "+ message +" added to database");

            //Shows a notification that sending the message was a success
            alert('The message has been sent');

            //Update the messages
            updateMessages();            
        }    
    </script>
suresh gopal
  • 3,138
  • 6
  • 27
  • 58
  • I was wrong, I still need to refresh when I delete the database, I can't have this because new users should not have to refresh the page. Check the complete code somewhere on this page. Can somebody fix the complete code, so that when you delete the database (pretend your are a new user) you don't have to refresh the page? – t0byman Nov 03 '12 at 13:11
  • add this in body onload .. like – suresh gopal Nov 03 '12 at 13:27
  • I added "" but when I delete the database (pretend your are a new user) I still need to refresh the page first. – t0byman Nov 03 '12 at 13:36
0

I pasted your code in test file and tried to find where is the exact problem. I don't know what the exact problem but I found that blow portion has some issue and that's why alert is not coming in first time:

db.transaction(function (tx) { tx.executeSql("INSERT INTO message (id, name) VALUES (NULL, ?)", [message]); });

Try with commenting above portion the alert will work come without refreshing the page. I think you should check that if you've made mistake in above portion.

Dhaval
  • 901
  • 3
  • 8
  • 26
  • Indeed it seems that this portion is the problem. However, it needs to be there to create the table. What needs to change in this portion so that the table is created, the alert will show and I don't need to refresh? What is the mistake that I made? – t0byman Nov 03 '12 at 11:57
  • In which browser you're testing? As the method of accessing db is only supported on Chrome & Safari. I've tested it in Chrome and the alert message is coming successfully in first time. I not needed to refresh the page. – Dhaval Nov 03 '12 at 12:37
0

This code if copy pasted in a file works fine when opened in chrome, It throws an alert message "The Message has been sent" on button click without the need to refresh

<html>
<head>
<script src="jquery.min.js" type="text/javascript"></script>
<script>
          var db;

          $(document).ready(function()    {
              //Opens the database
              try
              {
                if (!window.openDatabase) {
                      alert('Not supported -> Please use a webkit browser');
                } else {
                    var shortName = 'Rvpk';
                    var version = '1.0';
                    var displayName = 'The Rvpk databse';
                    var maxSize = 3072*1024; //  = 3MB in bytes 65536
                    db = openDatabase(shortName, version, displayName, maxSize);      
                    }  
              }
              catch(e)
              {
                if (e == 2) {
                    alert("Invalid database version.");
                } else {
                    alert("Unknown error "+e+".");
                }return;
              }

              //If needed creates the messagetable
              db.transaction(function (tx) {
                   tx.executeSql('CREATE TABLE IF NOT EXISTS message (id INTEGER PRIMARY KEY, name)')                    
              });
          });

          //The function addMessage takes the entered message from the message inputfield and places it inside the messagetable
          function addMessage(){
          var message = $('input:text[name=message]').val();

              db.transaction(function (tx) {
                       tx.executeSql("INSERT INTO message (id, name) VALUES (NULL, ?)", [message]);
              });
              console.log("Message "+ message +" added to database");

              //Shows a notification that sending the message was a success
              alert('The message has been sent');

              //Update the messages
              updateMessages();            
          }    
      </script>
      </head>

      <body>
      <?php include("includes/header2.php"); ?>

                  <div data-role="content">
                      <form>
                          <fieldset>
                              <label id="messagelabel" for="message">Message:</label>
                              <input id="message" type="text" name="message" value="This can't go on like this">
                              <button onClick="addMessage()" data-theme="g">Send</button>
                          </fieldset>
                      </form>
                  </div> 
</body>
</html>

and Ofcourse make sure to have the jquery.min.js in same directory

Mudassir Ali
  • 7,913
  • 4
  • 32
  • 60
0

I'm using Google Chrome as well. I still need to refresh first using this code.

<!DOCTYPE html>
<html lang="nl">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
    <link rel="stylesheet" href="jquery.mobile-1.2.0/jquery.mobile-1.2.0.css" />
    <script src="jquery.mobile-1.2.0/jquery-1.8.2.min.js"></script>
    <script src="jquery.mobile-1.2.0/jquery.mobile-1.2.0.min.js"></script>

    <link href="css/layout.css" rel="stylesheet" type="text/css" />
    <link rel="shortcut icon" href="afbeeldingen/favicon.ico" type="image/x-icon" />
    <meta name="Author" content="Tobias Boekwijt" />    <title>This can't go on like this</title>

<script>
var db;

        function runThis()
        {
            //Opens the database
            try
            {
              if (!window.openDatabase) {
                    alert('Not supported -> Please use a webkit browser');
              } else {
                  var shortName = 'Rvpk';
                  var version = '1.0';
                  var displayName = 'The Rvpk databse';
                  var maxSize = 3072*1024; //  = 3MB in bytes 65536
                  db = openDatabase(shortName, version, displayName, maxSize);      
                  }  
            }
            catch(e)
            {
              if (e == 2) {
                  alert("Invalid database version.");
              } else {
                  alert("Unknown error "+e+".");
              }return;
            }

            //If needed creates the messagetable
            db.transaction(function (tx) {
                 tx.executeSql('CREATE TABLE IF NOT EXISTS message (id INTEGER PRIMARY KEY, name)')                    
            });
        }

        //The function addMessage takes the entered message from the message inputfield and places it inside the messagetable
        function addMessage(){

        //call db access function.
        runThis();

        var message = $('input:text[name=message]').val();

            db.transaction(function (tx) {
                     tx.executeSql("INSERT INTO message (id, name) VALUES (NULL, ?)", [message]);
            });
            console.log("Message "+ message +" added to database");

            //Shows a notification that sending the message was a success
            alert('The message has been sent');        
        }    
</script>
</head>
<body>
    <div id="wrapper">
        <div data-role="page" id="page1">
            <div data-role="header" data-position="fixed" data-theme="a">                
                <h3>Test</h3>

                <a href="#popupInfo" data-rel="popup" data-position-to="window" data-role="button" data-icon="grid" data-iconpos="notext" class="ui-btn-right" data-theme="a" data-transition="pop"></a>
                    <div data-role="popup" id="popupInfo" class="ui-content" data-theme="e">
                    <a href="#" data-rel="back" data-role="button" data-theme="bl" data-icon="delete" data-iconpos="notext" class="ui-btn-right">Close</a>
                      <div data-role="content" data-theme="d" class="ui-corner-bottom ui-content">
                            <a data-role="button" href="messages.php" data-theme="b">My messages</a>
                            <a data-role="button" href="logout.php" data-theme="r">Log out</a>
                      </div>
                    </div>

                <a data-role="button" href="for_who.php" data-icon="home" data-iconpos="notext" class="ui-btn-left" data-theme="a"></a>
            </div> 

            <div data-role="content">
                <form>
                    <fieldset>
                        <label id="messagelabel" for="message">Message:</label>
                        <input id="message" type="text" name="message" value="This can't go on like this">
                        <button onClick="addMessage()" data-theme="g">Send</button>
                    </fieldset>
                </form>
            </div> 
        </div>    
    </div>
</body>
</html>
t0byman
  • 31
  • 1
  • 5
  • Where are you loading the main jQuery library ?? if you don't want to use jQuery then add window.onload = runThis() as last line inside script tag... – Mudassir Ali Nov 05 '12 at 10:45