JQuery Mobile and Cordova Page Templates

I was tasked with creating a mobile app for our medium school board to promote our schools. Initially it seemed pretty straightforward - I grabbed Cordova and Eclipse, ditched the jQuery Mobile library, and created some pages for my first school (I think only 5). Copy / paste / edit content links / update for another 17.

Then my boss said, "Make the pages in the colors of each school." Again, frivolous. A few CSS classes later, and all a hundred or so were pretty and school-appropriate.

Then a bomb appeared. All the data so far has been local - .htm files that were installed alongside the application and just loaded by the application when the user clicked on it: no data connection required. I was asked this morning if we can change information on the fly without updating the app. I, stupidly but truthfully, said "No" - and you can guess what the next request was.

So, I need a way to do this. My thought process now is to start a backend that gets an id of some type (appdata.schoolbord.web / 123) and it will return a JSON object that has data in it - probably title, name (so I can wrap my 93 pages just a few), some CSS (just to stop the next request) and then data to insert into the template.

Is there an easy way to do this with Cordova and jQuery Mobile? Pointers in any direction would be great. Thank.

+3


source to share


1 answer


Here's a simple example. I have created a jQM login page, you need to enter your username and password. This data will be used to check if the username exists in the database, if true, false otherwise is returned. I would suggest you create better db reading logic, this is a simple SQL injection prone solution, but it will work well for your purpose.

index.php:

<!DOCTYPE html>
<html>
<head>
    <title>jQM Complex Demo</title>
    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/>
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
    <style>
        #login-button {
            margin-top: 30px;
        }        
    </style>
    <script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js"></script>    
    <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
    <script src="js/custom.js"></script>
</head>
<body>
    <div data-role="page" id="login">
        <div data-theme="a" data-role="header">
            <h3>Login Page</h3>
        </div>

        <div data-role="content">
            <label for="username">Enter your username:</label>
            <input type="text" value="" name="username" id="username"/>
            <label for="password">Enter your password:</label>
            <input type="password" value="" name="password" id="password"/>  
            <a data-role="button" id="login-button" data-theme="b">Login</a>
        </div>

        <div data-theme="a" data-role="footer" data-position="fixed">

        </div>
    </div>
    <div data-role="page" id="index">
        <div data-theme="a" data-role="header">
            <h3></h3>
        </div>

        <div data-role="content">
            Here goes content
        </div>

        <div data-theme="a" data-role="footer" data-position="fixed">
            <h3>Page footer</h3>
        </div>
    </div>    
</body>
</html>

      

json.php:



<?php
    $var1 = $_REQUEST['action']; // We dont need action for this tutorial, but in a complex code you need a way to determine ajax action nature
    $jsonObject = json_decode($_REQUEST['outputJSON']); // Decode JSON object into readable PHP object

    $username = $jsonObject->{'username'}; // Get username from object
    $password = $jsonObject->{'password'}; // Get password from object

    mysql_connect("localhost","root","");  // Conect to mysql, first parameter is location, second is mysql username and a third one is a mysql password
    @mysql_select_db("test") or die( "Unable to select database"); // Connect to database called test

    $query = "SELECT * FROM users WHERE user_name = '".$username."' and user_pass = '".$password."'";
    $result=mysql_query($query);
    $num = mysql_numrows($result);

    if($num != 0) {
        echo "true";
    } else {
        echo "false";        
    }
?>

      

custom.js:

$(document).on('pagebeforeshow', '#login', function(){ 
    $('#login-button').on('click', function(){
        if($('#username').val().length > 0 && $('#password').val().length > 0){
            userObject.username = $('#username').val(); // Put username into the object
            userObject.password = $('#password').val(); // Put password into the object
            // Convert an userObject to a JSON string representation
            var outputJSON = JSON.stringify(userObject);
            // Send data to server through ajax call
            // action is functionality we want to call and outputJSON is our data
            ajax.sendRequest({action : 'login', outputJSON : outputJSON});
        } else {
            alert('Please fill all nececery fields');
        }
    });    
});

$(document).on('pagebeforeshow', '#index', function(){ 
    if(userObject.username.length == 0){ // If username is not set (lets say after force page refresh) get us back to the login page
        $.mobile.changePage( "#login", { transition: "slide"} ); // In case result is true change page to Index  
    }
    $(this).find('[data-role="header"] h3').append('Wellcome ' + userObject.username); // Change header with wellcome msg
    //$("#index").trigger('pagecreate');
});

// This will be an ajax function set
var ajax = {
    sendRequest:function(save_data){
        $.ajax({url: 'http://localhost/JSONP_Tutorial/json.php',
            data: save_data,
            async: true,
            beforeSend: function() {
                // This callback function will trigger before data is sent
                $.mobile.showPageLoadingMsg(true); // This will show ajax spinner
            },
            complete: function() {
                // This callback function will trigger on data sent/received complete
                $.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
            },
            success: function (result) {
                if(result == "true") {
                    $.mobile.changePage( "#index", { transition: "slide"} ); // In case result is true change page to Index
                } else {
                    alert('Login unsuccessful, please try again!'); // In case result is false throw an error
                }
                // This callback function will trigger on successful action
            },
            error: function (request,error) {
                // This callback function will trigger on unsuccessful action                
                alert('Network error has occurred please try again!');
            }
        });
    }
}

// We will use this object to store username and password before we serialize it and send to server. This part can be done in numerous ways but I like this approach because it is simple
var userObject = {
    username : "",
    password : ""
}

      

If you want, contact me by email (you can find it in ma profile) and I will send you a project with source code and using sql script.

+1


source







All Articles