Framework7 and Parse for User login

This is the second tutorial about building Framework7 HTML5 mobile web application. In the first tutorial part we have prepared the base by creating 3 mobile application views. One of them was the app user login view. In this tutorial part, we will make user registration and login functionality live by enabling login view communication with Parse -cloud-based backend service. The final third part is about wrapping Framework7 application into PgoneGap.

Creating Parse User Database

Nowadays you have many options once it comes to cloud-based storage options for mobile web apps. We did a good summary on HTMLCenter a few posts ago.

For todays tutorial, we are using Parse service. Parse at the time or writing supports 3 main functions – Core for data storage and user management, Push for push notifications and Analytics for logging different app events. They have free tier available for starting apps – it allows for up to 30 requests per second throughput and has 2TB data transfer limit per month. I’m sure we will not need this capacity in our tutorial!

Go ahead and create a free account on Parse. After you signup / login you can create new applications. I created one called framework7test dedicated for this tutorial. You can see it below.

Parse mobile applications backend service

What I specifically like about Parse – it has great user management functionality in built and available out of the box. Client applications can register new users and then log them in with only 2 API requests.
First we are going to register new user. Parse is asking client applications to send Application Id and API key in the HTTP headers. This information you can retrieve from Parse API reference documentation page. It should have your credential details pre filled in example requests.

Username has to be unique in the User database and Parse has inbuilt validation for this (try to create another user with the same name and you will get “username already taken” error.

curl -X POST \
 -H "X-Parse-Application-Id: xxx" \
 -H "X-Parse-REST-API-Key: yyy" \
 -H "Content-Type: application/json" \
 -d '{"username":"htmlcenter","password":"superpassword","moreinfo":"its a great blog"}' https://api.parse.com/1/users

After our new user is successfully created some time latter our mobile application can make another request with user login data in order to login. Parse will handle username / password validation steps and will issue session token with user details if login was successful. In case login data is incorrect your application will receive appropriate response from Parse service.

curl -X GET \
 -H "X-Parse-Application-Id: xxx" \
 -H "X-Parse-REST-API-Key: yyy" \
 -G \
 --data-urlencode 'username=htmlcenter' \
 --data-urlencode 'password=superpassword' https://api.parse.com/1/login

As you can see all user management functionality is already provided for our mobile application by Parse without us doing much work. We do not have to store any user related data in mobile web app (not recommended for security reasons). Our client application will only have registration and login forms for app user to submit data. Here is how registered user data looks in Parse cloud service – via web UI.

HTMLCenter user data in Parse
Next step is to enable login and registration views.

Framework7 Http Requests

Framework7 doesn’t use any external 3rd party libraries. In their applications developers can use jQuery like syntax for accessing DOM and jQuery Ajax syntax to send / receive requests via HTTP.

In this tutorial part we continue using source code from where we left it the previous tutorial part. I have added another page called register by simply copying login page HTML code and renaming data-page attribute. This page has 3 fields we are going to be sending to Parse: username, password and email. In order to login, user will need only username and password but our application could retrieve users email anytime by requesting information from Parse.

We first have to create the method for Send button that once its clicked by application user our app sends HTTP request with registration data to Parse service. This is done in my-app.js JavaScript file:

// Function to handle Submit button on Register page
$$('#submmit-register').on('click', function () {
 
 var username = $$('#register-username').val();
 var email = $$('#register-email').val();
 var password = $$('#register-password').val();
 
 if (!username || !password || !email){
  myApp.alert('Please fill in all Registration form fields');
  return;
 }

 ...

});

This above peace of code captures values from registration form and assigns them to variables to be used in the HTTP request. Code also checks for these fields not to be empty and displays simple alert message if any one of them is missing data. Note the myApp.alert in the code –  it will display nice iOS7 like popup message.

Framework7 registration form

Next block of code uses the username, email and password values we have captured and sends HTTP POST request to Parse backend in order to create new user. Request format is the same as curl one we have discussed before just has to be adjusted to jQuery Ajax like syntax

var query = 'https://api.parse.com/1/users';
var postdata = {};

postdata.username = username;
postdata.password = password;
postdata.email = email;
myApp.showIndicator();
$$.ajax({
 url: query,
 headers: {"X-Parse-Application-Id":applicationId,"X-Parse-REST-API-Key":restApiKey},
 type: "POST",
 contentType: "application/json",
 data: JSON.stringify(postdata),
 statusCode: {
  201: success201,
  400: notsuccess,
  500: notsuccess
 }
});

As you can see, we are setting query url, JSON object to be posted to Parse and initialising Framework7 spinner before making Ajax request.

I have externalised the deader values in the beginning of my-app.js JavaScript file so they can be used across multiple Ajax requests. We set HTTP request type to POST and add handle methods for HTTP response status codes. In our case HTTP 201 means successfully created user and any other HTTP code means request did not succeed.

Whats left is to add the methods to handle success and failed Parse responses:

var success201 = function(data, textStatus, jqXHR) {
 // We have received response and can hide activity indicator
 myApp.hideIndicator();
 // Will pass context with retrieved user name
 // to welcome page. Redirect to welcome page
 mainView.router.load({
 template: Template7.templates.welcomeTemplate,
  context: {
   name: username
  }
 });
};

var notsuccess = function(data, textStatus, jqXHR) {
 // We have received response and can hide activity indicator
 myApp.hideIndicator();
 myApp.alert('Login was unsuccessful, please try again');
};

In both cases we are dismissing spinner. In case user registration was successful we are loading up welcome page from Framework7 template. If registration for some reason was not successful, we are going display already familiar Framework7 popup message about unsuccessful registration.

Worth to mention that it would be possible to verify more details about why the registration request has failed as Parse actually sends informative response message. But we are going to do it in 3rd tutorial part.

Framework7 login application

The same approach I did for login page functionality. Only difference is the request is GET and we have no request body to send. As we are expecting HTTP 200 response as success response instead of using status codes to handle responses we can just use success / error:

$$.ajax({
   url: query,
   headers: {"X-Parse-Application-Id":applicationId,"X-Parse-REST-API-Key":restApiKey},
   type: "GET",
   // if successful response received (http 2xx)
   success: function(data, textStatus ){
 
     // We have received response and can hide activity indicator
     myApp.hideIndicator();
 
     data = JSON.parse(data);
     if (!data.username) {return}

     var username = data.username; 
 
    // Will pass context with retrieved user name 
    // to welcome page. Redirect to welcome page
    mainView.router.load({
     template: Template7.templates.welcomeTemplate,
     context: {
      name: username
     }
   });
  },
  error: function(xhr, textStatus, errorThrown){ 
    // We have received response and can hide activity indicator
    myApp.hideIndicator(); 
    myApp.alert('Login was unsuccessful, please verify username and password and try again');

    $$('#login-email').val('');
    $$('#login-password').val('');
  }
});

Conclusion

Adding HTTP communication to Framework7 is not hard if you are familiar with jQuery type Ajax request syntax and JavaScript async nature of coding (all the callback fun). In this tutorial we have added such communication with Parse backend service for registering / user login. You can find all the related project source code on GitHub.

In the final 3rd part of the tutorial we are going to wrap up this application to PhoneGap framework which will make it a native mobile app. Stay tuned for the last tutorial part.

21 Responses

  • jnuc093

    it is so userful!

    • u r welcome

      • neeraj

        Hi, this tutorial is good for when we submit data using form to another page. But, we have to do it when we get xml result from url and I want to attribute value after I get success result using ajax in framework7.io. Can any body help me ? I use this code for get xml result.

        $$.ajax({
          timeout : 20000,
          url: URL,
          dataType: 'text',
          success: function(data){
        
            myApp.alert(data);
        
            //*here i get xml result what how i get the attribute value. Suppose i want to get value of result and message using this result how i get ?? */
            /*i use below code for get result text value but not get any thing how i get result can any body help me out ? i really appreciate them ? */
            // var res = $$(data).find('result').text();
        },
        
        error: function(xhr, textStatus, errorThrown){
        
          myApp.alert('Login was unsuccessful, please verify username and password and try again');
          $$('input[name="emp_code"]').val('');
          $$('input[name="password"]').val('');
        }
        });
        
        • hi, I have responded to your first comment on top of the list. hope it helps

        • bokungai

          I have created a php registration and login form need to integrate in backend using Framework7.
          I dont know can anyone help me please.

  • blizzerdz

    I love the tut, however, I am struggling to get it to work with classes like blog in parse. I want to display posts from my class “blog”.

    • So you have class in Parse called ‘blog’ and struggling to get data out? any specific errors?

  • Manmeet Kaur

    Great post and tutorial with simple examples.

  • neeraj

    Can I use code to get xml results?

    
    $$.ajax({
      timeout : 20000,
      url: URL,
      dataType: 'text',
      success: function(data){
        myApp.alert(data);
        //*here i get xml result what how i get the attribute value. Suppose i want to get value of result and message using this result how i get ?? */
    
        /*i use below code for get result text value  but not get any thing how i get result can any body help me out ? i really appreciate them ? */
    
        // var res =  $$(data).find('result').text();
       },
          error: function(xhr, textStatus, errorThrown){
            myApp.alert('Login was unsuccessful, please verify username and password and try again');
            $$('input[name="emp_code"]').val('');
            $$('input[name="password"]').val('');
          }
        });
  • Ashok Kumar

    Hi, Is there any option to use Angular like services in Framework7. I want to create a Mediaplayer app which will be available across all pages.

  • TDAdvocate

    How does one properly view the work that they have created? I have no web host or anything that I can use to upload these files to for testing.

  • Brian

    I have created a php registration and login form need to integrate in backend using Framework7.
    I dont know can anyone help me please.

    • Omar Salah

      Please advise if you got it sorted out, as I’ve been stuck for over a week now.
      Thanks in advance.

      • What exactly you are stuck with?

        • Omar Salah

          I’m trying to create a login & registeration page using framework 7, and need some guidance on how to create a php api that could be used in ajax in framework7,,,I’m able to achieve this using php only but not ajax,,,please advise how to accomplish this with framework 7.

  • bokungai

    I have created a php registration and login form need to integrate in backend using Framework7 as the frontend.
    I dont know how i can do it, can anyone help me please?.
    I need it for a school project.

Post Your Comment

Your email address will not be published.