Connection with the Backend

Now we will learn, How to connect our cordova based application with the backend to work dynamically with data.

Backend Language → PHP

Database → MYSQL

Have you ever thought, when you feed your username and password in some login form, what happens? How does it verifies your credentials? So, let's try to understand and implement credentials verfication.

When you enter your username and password, the client (browser, in most cases or the app) sends your username, password and some header data to server (say PHP based server and MySQL based database). There Php receives your data and act accordingly. An SQL query is executed to fetch the data, which is then compared with the username and password submitted. And it send back the result through the same gateway, then client-side also responds as per the response received (like, server response is incorrect parameters, then client side will show you Username and password does not match. message).

Now in this tutorial, we will create an app which will communicate with the backend. For this we require XAMPP(https://www.apachefriends.org/index.html) application. Follow the link and download XAMPP and install it. XAMPP is a local server, which runs Apache, Php and MySQL for developing and testing websites and apps on your local machine. It replicates a LAMP web server locally on your laptop/computer.


  1. After installing, open XAMPP server and click on Start corresponding to Apache and MySQL.

    Connection with backened

    NOTE: Default port for the server is 80.

  2. Now write some code in Php and place it in the htdocs folder inside the XAMPP folder.

    index.php
    <?php
    echohello world!”;
    ?
    
  3. Open the browser and type in the address bar: http://localhost or http://127.0.0.1, it should show hello world! on the screen.

    Connection with backened

    This means our XAMPP server is running successfully. Now we are ready to develop a dynamic mobile app. Client-side script (HTML, CSS, Javascript and jQuery, just like in previous tutorials). Keep the jquery.js file with index.html (or both in same folder)

  4. Here is the index.html file.
    <html>
        <head>
            <script type=”text/javascript” src=”jquery.js”></script>
            <script type=”text/javascript”>
                $(document).ready(function(){
                    $(“#sub”).click(function(){
                    var firstname = $(“#firstname”).val();
                    var lastname = $(“#lastname”).val();
                    if($.trim(firstname).length >0 & $.trim(lastname).length >0) {
                    $.ajax({
                        type:”POST”,  //Request type
                        url: “http://localhost/firstname.php”,   
                        data:{firstname:firstname, lastname:lastname},
                        cache:false,
                        success:function(data) {
                            alert(data);
                        }
                    })
                    } 
                    else {
                        alert(‘Input fields are empty’);
                    }
                })
            })
            </script>
        </head>
        <body>
            <input type=”text” placeholder=”write your first name” id=”firstname”>
            <input type=”text” placeholder=”write your last name” id=”lastname”>
            <button id=”sub”>Submit result</button>
        </body>
    </html>
    

    and the firstname.php

    <?php
    $firstname = $_POST[‘firstname’];
    $lastname = $_POST[‘lastname’];
    echo $firstname.”  “.$lastname;
    ?>
        

    Now place this PHP file and the HTML file in the htdocs folder. And make sure your XAMPP server is running. Run the index.html in browser and feed input and check output.

    Connection with backened


Migrating the Code to Android App

Now we will run this code in mobile, so first connect your laptop and mobile (In which you will test your app) with the same hotspot. Then once connection is setup, open cmd in your laptop/computer, type ipconfig and press enter. It will show the IP addresses, if your computer is connected with WIFI router then copy the IP of wireless LAN adapter adapter wifi, else copy the LAN IP address. Replace the localhost (url attribute inside $.ajax function in index.html) with this IP address.

Connection with backened

We only need the index.html file in the App, firstname.php file will remain in the htdocs folder of XAMPP directory.

Now generate the apk. Copy it to your device and check whether it is working or not.

Connection with backened


In case it is not working, make sure your server is running or not? Whether both the devices are connected to same wifi hotspot network or not? If connected to same wifi network, check the IP address. Next, we will save user's input into our MySQL database.

For this, first we will have to create MySQL database.

  1. Open http://localhost/phpmyadmin in the browser.

  2. Click on SQL

    Connection with backened

  3. Type the following command in the textarea and click on Go.

    CREATE DATABASE mydb;

    Connection with backened

    This command will create database mydb if it does not exist already.

    Connection with backened

  4. Now open the mydb database, by clicking on it in the sidebar and once again click on SQL. Then create table using the following command.

    CREATE TABLE my_table (
        id int AUTO_INCREMENT,
        firstname varchar(200),
        lastname varchar(200)
    )
    

    Connection with backened

    It will create a table with name, my_table in mydb database.

    Connection with backened

  5. Client side code i.e. index.html file, will remain the same but the Php side code will change.

    firstname.php

    <?php
    /*
      localhost is the location where the server is located
      root is the global username of server
      ' ' this root has no password protection, hence empty
      my_db is db with which we want to connect
    */
    $con = mysqli_connect(‘localhost’,’root’,’’,’my_db) or die (‘unable to connect’);
    
    $firstname = $_POST[‘firstname’];
    $lastname = $_POST[‘lastname’];
    $sql = “INSERT INTO `my_table`(`firstname`,`lastname`) VALUES(‘$firstname’,’$lastname’);
    $result = mysqli_query($con,$sql);
    if($result) {
        echo $firstname.” “.$lastname;
    } 
    else {
        echo “unable to insert data”;
    }	
    ?>
    

    Now try it or refresh phpmyadmin page and check whether the data is inserted or not.