Easy Code Share > Cordova > 3 Steps to Make Cordova AJAX Not Failed

3 Steps to Make Cordova AJAX Not Failed


Cordova should make jQuery AJAX work successfully in built Android APPs. You can test distinct AJAX methods here, and learn how to fix cross-domain blocking issue. Moreover, we review for you the Cordova building process that have been mentioned in our previous post.

All codes here are not complicated, so you can easily understand even though you are still students in school. To benefit your learning, we will provide you download link to a zip file thus you can get all source codes for future usage.

Estimated reading time: 6 minutes

 

 

BONUS
Source Code Download

We have released it under the MIT license, so feel free to use it in your own project or your school homework.

 

Download Guideline

  • Prepare HTTP server such as XAMPP or WAMP in your windows environment.
  • Download and unzip into a folder that http server can access.
 DOWNLOAD SOURCE

 

STEP 1
Cordova AJAX

Sometimes developers reflect Cordova AJAX is not working. Let’s demonstrate different jQuery AJAX methods in the section, and reveal the cause of failure.

 

Communicating with Hosts

If Cordova would like to build APPs capable of linking to HTTP hosts, Ajax is surely a candidate. Here listed 4 alternatives for testing on Ajax POST and GET.

You have to locate index.js in www/js folder under Cordova project. If not familiar with file structure of Cordova project, you can refer to steps for Cordova building.

index.js
var url_test = "http://www.example.com/ajax-server.php";
function ajax_test_0(v) {
    $.ajax({
        url: url_test,
        type: "POST",
        data: { msg: v },
        success: function(msg) {
            $("#response p").html(msg);
        },
    });
}
function ajax_test_1(v) {
    $.post(
        url_test,
        { msg: v },
        function(msg) {
            $("#response p").html(msg);
        },
    );
}
function ajax_test_2(v) {
    $.get(
        url_test,
        { msg: v },
        function(msg) {
            $("#response p").html(msg);
        },
    );
}
function ajax_test_3(v) {
    $.ajax({
        url: url_test,
        type: "GET",
        data: { msg: v },
    }).done( function(msg) {
        $("#response p").html(msg);
    });
}

 

AJAX Testing APP

There are 4 ways of $.ajax(), $.post(), $.get(), and $.ajax().done() to perform AJAX. Clicking buttons on the website or built APP, you can test POST and GET protocols, respectively.

 

AJAX Testing APP Created by Cordova

Our example server site just replies with the message coming from clients to indicate success. Response messages are shown in footer part on APPs. In ajax-server.php, you might wonder what the definition Access-Control-Allow-Origin:* means. Subsequently, that will be explained in the next section.

ajax-server.php
<?php
header("Access-Control-Allow-Origin:*");
if (isset($_GET["msg"])) echo $_GET["msg"];
if (isset($_POST["msg"])) echo $_POST["msg"];
?>

 

STEP 2
Access-Control-Allow-Origin

To avoid hackers, cross-domain HTTP requests are under control by using header definition upon requested resources. However, it influence our developing process in Cordova. You will learn the solution here.

 

Blocked by CORS Policy

If no Access-Control-Allow-Origin header is present on the server site, cross-domain clients will fail to access services because the CORS policy blocks requests. Usually, that is a common mistake developers make.

Cordova Ajax Blocked by CORS Policy

Whereas, you can define header to be Access-Control-Allow-Origin: http://localhost in order to release blocking for a single domain.

 

Cross-Origin Resource Sharing (CORS)

What is cross-origin resource sharing (CORS)? CORS Policy is a browser mechanism controlling access between websites or domains in order to prevent websites from cross-domain hacking-data attacks. It is implemented by Access-Control-Allow-Origin header which could be * for all domains or protected-website.com for a specified website.

 

STEP 3
Cordova Building Process

We have a post about building cordova projects before. Now, according to this example, let’s briefly show steps for creating an ajax-test APP on Android platform.

 

Quick Start

$ cordova create ajaxtest com.easycodeshare.ajaxtest AjaxTest

The command line can create a Cordova project with specified PATH, ID, and NAME. Now, ajaxtest directory is generated. Replace all files in ajaxtest/www folder with your project files.

 

Convert ajax-test.php To Be index.html

Cordova is capable of building APPs from websites, while websites might consist of server-site scripts PHP that Cordova can’t understand. Therefore, before building APPs, you have to interpreted PHP as a index.html file, which is the APP entry point and should be put into ajaxtest/www folder.

ajax-test.php
<?php
$bText = ["$.ajax()", "$.post()", "$.get()", "$.ajax().done()"];
function setButton($id) {
    global $bText;
    echo "<input type='button' value='$bText[$id]'>";
} ?>
<!DOCTYPE html>
<html>
<head>
<title>3 Major Steps Cordova Ajax Make APPs Not Failed</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="css/1.4.5/jquery.mobile.min.css">
<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/1.4.5/jquery.mobile.min.js"></script>
<script src="cordova.js"></script>
<script src="js/index.js"></script>
</head>
<style>
    .btns { margin-left:10%; margin-bottom:3%; width:80%; }
    #response { color: lightgreen; background: gray; }
</style>
<body>
<div data-role="page">
    <div data-role="header">
        <h1>AJAX TEST</h1>
    </div>
    <div data-role="content">
        <?php for($i=0; $i<4; $i++) setButton($i); ?>
        <p style="text-align:center;">(Click to make a request)</p>
    </div>
    <div id="response" data-role="footer" data-position="fixed">
        <p style="text-align:center;">Show Response Here</p>
    </div>
</div>
</body>
</html>

After that, it is safe to build an APP by command line $ cordova build android. More details for building cordova projects are in our previous post.

 

Moving ajax-server.php To Server

Apart from the files APPs require, we need a AJAX server implemented by an additional file ajax-server.php. So move it to a host, and make sure that url_test in ajaxtest/www/js/index.js directs to correct URL such as http://www.example.com/ajax-server.php.

 

FINAL
Conclusion

Potential issues you may encounter about Cordova AJAX have been discussed here. Thank you for reading, and we have suggested more helpful articles here. If you want to share anything, please feel free to comment below. Good luck and happy coding!

 

Learning Tips

Let us suggest a excellent way to learn HTML scripts here. Using Google Chrome F12 Inspect or Inspect Element will help you study the codes.

In Google Chrome, there are two ways to inspect a web page using the browser built-in Chrome DevTools:

  • Right-click an element on the page or in a blank area, then select Inspect.
  • Go to the Chrome menu, then select More Tools > Developer Tools.

 

Suggested Reading

 

TRY IT
Quick Experience

That is all for this project, and here is the link that let you experience the program. Please kindly leave your comments for our enhancement.

 

Try It Yourself

Click here to execute the source code, thus before studying the downloaded codes, you can check whether it is worthy.

Leave a Comment