Drupal JSON Services Examples with PhoneGap and JQuery Mobile for Android

Category:

UPDATE: Please read this article for a much more detailed explanation on how to get PhoneGap up and running to communicate with Drupal Services.

This info assumes you have Drupal 6.x, Services 3.x and PhoneGap/Eclipse/Android up and running. If you are new to Drupal Services, head over to the Drupal Services Examples article to get started. This page is a work in progress and I will continue to add more examples when days are 48 hours long.

System Connect, User Login, User Logout

assets/www/index.html

<!DOCTYPE html> 
<html>

  <head> 
    <title>Drupal JSON Services with PhoneGap and JQuery Mobile for Android</title> 
    <script type="text/javascript" charset="utf-8" src="phonegap-1.1.0.js"></script>
    <link rel="stylesheet" href="jquery.mobile-1.0a1.min.css" /> 
    <script src="jquery-1.4.3.min.js"></script>
    <script src="jquery.mobile-1.0a1.min.js"></script>
  </head>

<body>

<div data-role="page" id="tf_page_dashboard">
  <script type="text/javascript" charset="utf-8" src="scripts/dashboard.js"></script>

  <div data-role="header">
    <h1>Dashboard</h1>
  </div><!-- /header -->

  <div data-role="content">
    <p><a href="#tf_page_login" data-role="button" id="tf_login_button">Login</a></p>
    <p><a href="#" data-role="button" id="tf_logout_button">Logout</a></p>
  </div><!-- /content -->

</div><!-- /page -->

<div data-role="page" id="tf_page_login">
  <script type="text/javascript" charset="utf-8" src="scripts/login.js"></script>

  <div data-role="header">
    <h1>Login</h1>
  </div><!-- /header -->

  <div data-role="content" class='content'>
    <div>
      <label for="tf_page_login_name">Username</label>
      <input type="text" id="tf_page_login_name" />
    </div>
    <div>
      <label for="tf_page_login_pass">Password</label>
      <input type="password" id="tf_page_login_pass" />
    </div>
    <fieldset>
      <div><button type="button" data-theme="b" id="tf_page_login_submit">Login</button></div>
    </fieldset>
  </div><!-- /content -->

</div><!-- /page -->

</body>

</html>

assets/www/scripts/dashboard.js

$('#tf_page_dashboard').live('pageshow',function(){
  try {
    // BEGIN: drupal services system connect (warning: don't use https if you don't have ssl setup)
    $.ajax({
      url: "https://www.tylerfrankenstein.com/my_services_path/system/connect.json",
        type: 'post',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          alert('tf_page_login_submit - failed to login');
          console.log(JSON.stringify(XMLHttpRequest));
          console.log(JSON.stringify(textStatus));
          console.log(JSON.stringify(errorThrown));
        },
        success: function (data) {
          var tf_user = data.user;
          if (tf_user.uid == 0) { // user is not logged in, show the login button, hide the logout button
            $('#tf_login_button').show();
            $('#tf_logout_button').hide();
          }
          else { // user is logged in, hide the login button, show the logout button
            $('#tf_login_button').hide();
            $('#tf_logout_button').show();
          }
       }
    });
    // END: drupal services system connect
  }
  catch (error) { alert("tf_page_dashboard - " + error); }
});

$('#tf_logout_button').live("click",function(){
try {
  // BEGIN: drupal services user logout (warning: don't use https if you don't have ssl setup)
  $.ajax({
      url: "https://www.tylerfrankenstein.com/my_services_path/user/logout.json",
      type: 'post',
      dataType: 'json',
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert('tf_logout_button - failed to logout');
        console.log(JSON.stringify(XMLHttpRequest));
        console.log(JSON.stringify(textStatus));
        console.log(JSON.stringify(errorThrown));
      },
      success: function (data) {
        alert("You have been logged out.");
        document.location.href = "../index.html#tf_page_dashboard";
      }
  });
  // END: drupal services system connect
}
catch (error) { alert("tf_logout_button - " + error); }
return false;
});

assets/www/scripts/login.js

$('#tf_page_login').live('pageshow',function(){
  try {
    // do some stuff when the page is ready, if you want...
  }
  catch (error) { alert("tf_page_login - " + error); }
});

$('#tf_page_login_submit').live('click',function(){
  
  var name = $('#tf_page_login_name').val();
  if (!name) { alert('Please enter your user name.'); return false; }
  
  var pass = $('#tf_page_login_pass').val();
  if (!pass) { alert('Please enter your password.'); return false; }
  
  // BEGIN: drupal services user login (warning: don't use https if you don't have ssl setup)
  $.ajax({
      url: "https://www.tylerfrankenstein.com/my_services_path/user/login.json",
      type: 'post',
      data: 'username=' + name + '&password=' + pass,
      dataType: 'json',
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert('tf_page_login_submit - failed to login');
        console.log(JSON.stringify(XMLHttpRequest));
        console.log(JSON.stringify(textStatus));
        console.log(JSON.stringify(errorThrown));
      },
      success: function (data) {
        document.location.href="../index.html#tf_page_dashboard";
      }
  });
  // END: drupal services user login
  return false;
});

Comments

Thank you for this tutorial! I was wondering if you could help me understand a few steps past this.

How could you store the returned json (sessionid, etc) to make authenticated posts with something like localstorage? I am sure I am missing something very obvious but I am just not seeing it. Any insight would be really appreciated, thanks!

Thank you, I am glad it helped.

For example, in the System->Connect resource success call back function, you can do this:

success: function (data) {
  // This will show you what the json return object looks like as a string.
  // You can take the print out of this from eclipse and paste it into something 
  // like JSONLint to see a pretty print of this object
  console.log(JSON.stringify(data)); 

  // this saves it into local storage
  window.localStorage.setItem("my_system_connect_data_key",JSON.stringify(data));

  // this retrieves it from local storage
  var local_storage_data_retrieval = JSON.parse(window.localStorage.getItem("my_system_connect_data_key"));
}

Wow, what a quick reply! You sir are a gentleman and a scholar. I had gotten that far. What I don't understand is how to take elements out of that string for an authenticated request, such as creating a node. Unless I am misunderstanding how JSON.stringify works I have to get only the values for the keys I need.

So if I did something like:
$.ajax({
type: "POST",
url: 'URL/services/rest/node', //my endpoint
data: JSON.stringify(obj), //this is coming from a form....
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('');
console.log(JSON.stringify(XMLHttpRequest));
console.log(JSON.stringify(textStatus));
console.log(JSON.stringify(errorThrown));
},
success: function(data){
}
});

where would I include the data from localstorage?

I really am not trying to force you to write my code for me. I'm just a sys admin literally being forced to write a mobile app (long story) and I've been running into walls all weekend. I sincerely appreciate any insight, thanks!

Thanks Tyler!Could you help me please?i want to send image from phonegap app to node of drupal how do i do that?sorry about my english

Thanks a lot. Was struggling with phonegap. But you help a lot.
Waiting for Druaplgap to become a downloadable module from Drupal.org

Perrrrfect!! Thanks
:)

Add new comment