The Web Blinders logo

Programming

CORDOVA AJAX POST JSON DATA EXAMPLE

You can do it the same way how you normally do for browsers.
For example..

APP DESCRIPTION : Let's make an App that takes an URL as input and sends json data using POST request method and displays the response from backend script.

Inside your CORDOVA www directory, add following html code to index.html

    <div>
        <h1>Ajax test</h1>
        <input type="text" id="url" placeholder="TYPE URL HERE" />
        <button id="btn-url">CHECK</button>
        <div id="ajaxResult">
        </div>
    </div> 

Now Add following JavaScript to index.js

class RequestTest {
  constructor() {
      this.url = document.getElementById("url");              // input element
      this.urlBtn = document.getElementById("btn-url");       // button element
      this.urlResult = document.getElementById("ajaxResult"); // we will display response in this div
  }
  init() {
      document.addEventListener("deviceready", this.startEvents, false);
  }
  startEvents() {
      this.urlBtn.onclick = () => {
          this.ajaxRequest();
      }
  }

  // This is it 
  ajaxRequest() {
          // JavaScript Object
          var data = {
              reqTime: new Date(),
              user: 'YOYO'
          };
          // JSON Data
          data = JSON.stringify(data);
          var xhttp = new XMLHttpRequest();
          var that = this;
          xhttp.onreadystatechange = function() {
              if (this.readyState == 4 && this.status == 200) {
                  // we will display response from server
                  that.urlResult.innerHTML = this.responseText;
              }
          }
          xhttp.open("POST", this.url.value, true);
          xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
          xhttp.send(`data=${data}`);
  }
}
var reqTest = new RequestTest();
reqTest.init();

Let's say you are using PHP in the backend.

<?php
echo $_POST['data'];
?>

Output which looks something like this will be displayed on your index.html

{"reqTime":"2019-07-13T06:56:53.638Z","user":"YOYO"}

ALTERNATE TITLES

Cordova post request

cordova php example

Cordova ajax json example

Cordova xmlhttp request

cordova crud app
cordova load url example

Need developers ?

if so, send a message.

thewebblinders@gmail.com

More Programming from our blog

SEARCH FOR ARTICLES