Showing posts with label JSON. Show all posts
Showing posts with label JSON. Show all posts

Tuesday 26 February 2019

Vanilla JavaScript Login form POST handler using XHR

I did a similar post to this called Vanilla JavaScript Login form POST handler using fetch. Fetch returns a JavaScript Promise, which can be a bit of a pain so I've also done a version using XHR, see below:

var postJSON = function(url, method, data, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open(method, url, true);
  xhr.responseType = 'json';
  xhr.onload = function() {
    var status = xhr.status;
    if (status === 200) {
      callback(null, xhr.response);
    } else {
      callback(status, xhr.response);
    }
  };
  xhr.send(data);
};

Here's how to call it:
const form = document.querySelector('form');
form.addEventListener('submit', function(ev) {
  ev.preventDefault();
  const url = this.getAttribute('action');
  const method = this.getAttribute('method');

  postJSON(url, method, new FormData(form), function(error, json) {
    if (error !== null) {
      console.log('parsing failed', error);
    } else {
      console.log('json.username', json.username);
      console.log('json.password', json.password);
    }
  });
});

Wednesday 6 February 2019

Vanilla JavaScript Login form POST handler using fetch

I've been updating my gists lately because I'm now in position to leave jQuery behind. See https://gist.github.com/guitarbeerchocolate
So, here's how to pass login form data to some middleware and accept JSON in return using fetch.

const form = document.querySelector('form');
form.addEventListener('submit', function(ev) {
  ev.preventDefault();
  const url = this.getAttribute('action');
  const method = this.getAttribute('method');

  fetch(url, {
    method: method,
    body: new FormData(form)
  }).then(function(response) {
    return response.json()
  }).then(function(json) {
    console.log('json.username', json.username)
    console.log('json.password', json.password)
  }).catch(function(error) {
    console.log('parsing failed', error)
  })
});

Monday 14 May 2018

Get blogspot content using JavaScript fetch

This example pulls in JSON data from a blog hosted on blogspot.com

First, I'll need to get fetch.
To add it to your project, change to your project directory:
cd myApp
Then use the following command:
npm install node-fetch --save

const fetch = require('node-fetch');
const url = 'http://some-website.blogspot.com/feeds/posts/default/-/blog?alt=json';
var myFetch = fetch(url);

myFetch.then(response => response.json()).then(function(data) {
  showMyData(data);
}).catch(function(err)
{
  console.log('Caught an error ',err);
});

function showMyData(md) {
  md.feed.entry.forEach((e) => {
    var title = (e.title.$t || '');
var url = (e.link || []).pop().href;
    var date = new Date(e.updated.$t || Date.now());
    var lessLines = e.content.$t.substr(0, 800);
    var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    var theMonth = months[date.getMonth()];
    var theYear = date.getFullYear();
  });
}

Friday 11 May 2018

The 2018 Web Developer : JavaScript JSON processing without jQuery

Enter 'fetch'. The JavaScript API which performs HTTP requests.
First, I'll need to get fetch.
To add it to your project, change to your project directory:
cd myApp
Then use the following command:
npm install node-fetch --save

In this example, I have a simple .json file which contains a set of URLs and their types.

const fetch = require('node-fetch');
const url = 'feeds.json';
var myFetch = fetch(url);

myFetch.then(response=>response.json()).then(function(data) {
    showMyData(data);
  });

function showMyData(md)
{
  md.forEach((value) => {
    console.log(value.URL, value.TYPE);
  });
}

Tuesday 24 April 2018

Live data to your page using EventSource

In the following example I deliver live data to a web page. It's possible to do this quite easily using node.js and socket.io. However most of the websites I create are delivered through a shared server and the providers won't let me install node.js, so here I provide an alternative.
In this instance I use a combination of HTML, JavaScript and PHP. It would also be possible to use jQuery instead of straight JavaScript and PHP with something like python or indeed any other language. I also use a JSON file which could be replaced by any other data source.

Let's begin with data source tester.json
[
{
"name": "Aragorn",
"race": "Human"
},
{
"name": "Gimli",
"race": "Dwarf"
}
]

Now, the HTML file (index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Live data connectivity</title>
</head>
<body>
<table id="myTable">
  <thead>
    <tr>
      <th>Name</th>
      <th>Race</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>
<script src="updatetables.js"></script>
<script src="run.js"></script>
</body>
</html>

Basically we need to check if the HTML table has any data inside. if it doesn't we take data from the data source. If the HTML table does contain data, it will be updated with the contents of the data source. To achieve this we'll use a function inside updatetables.js.
function updateTable(jd, id)
{
  var tbody = document.getElementById(id).tBodies[0];
  for (var i = 0; i < jd.length; i++)
  {
    if(tbody.rows[i] == null)
    {
      /* No data in HTML table */
      var row = tbody.insertRow(i);
      var x = row.insertCell(0);
      x.innerHTML = jd[i].name;
      x = row.insertCell(1);
      x.innerHTML = jd[i].race;
    }
    else
    {
      /* Data in HTML table. Needs updating. */
      var row = tbody.rows[i];
      tbody.rows[i].cells[0].innerHTML = jd[i].name;
      tbody.rows[i].cells[1].innerHTML = jd[i].race;
    }
  }
}

Now that we have a means of updating the table, we need to get the data using stream.php
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$JSON = file_get_contents('tester.json');
echo 'data: '.json_encode($JSON).PHP_EOL.PHP_EOL;
flush();
?>

Finally we can use the JavaScript EventSource object to call stream.php and get our data. Once we have our data, we can pass it to updatetables.js. This is done through run.js
var source = new EventSource('stream.php');
var tableid = 'myTable';
source.onmessage = function(event)
{
  var jsonData = JSON.parse(event.data);
  jsonData = JSON.parse(jsonData);
  updateTable(jsonData, tableid);
};

If you have recreated these files, to test it all works, try changing the values of items in tester.json and see the updates on your page without refresh.




Wednesday 10 June 2015

Bootstrap formhandler calling class methods with JSON returned and processed

This entry offers a number of techniques through 4 files.

  • index.php contains a message alert which will only be displayed when there is a message to put in it. The forms use an action which contains the name of a class and method which will be used to process the results. There is also a call to custom.js
  • custom.js handles the form submissions and delivers the data returned to the page. It passes the form action and field content to formhandler.php. It receives JSON which then is either passed to a message alert or a data table.
  • formhandler.php receives the call from custom.js. This contains the form action and field content. It takes the form action and uses them to create calls to classes and methods named in the form action. For example and action of myclass/mymethod would be used to create calls similar to those below. The inclusion of the $_POST array allows the form field content to be passed to the class. The data returned is then passed back to custom.js for processing.
$myclass = new myclass($_POST);
$myclass->mymethod;

  • myclassname.class.php contains the example class and methods. The class receives the $_POST array and processes its content. There are 3 methods which demonstrate how to return a string, an array and an object.

This approach is a quick way of utilising many classes. It does not require a .htaccess file to simplify form actions and is flexible in its handling of returned data through JSON.
Have fun.

index.php

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Form handler for many PHP classes using jQuery</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <style>
    body
    {
      margin-top:2em;
    }
    #message, #data-table
    {
      display:none;
    }
    </style>
  </head>
  <body>
    <div class="row">
      <div class="container">
        <div class="col-md-12">
          <div id="message" class="alert alert-success" role="alert"></div>
          <!-- <form action="myclassname/myclassmethod_string" method="POST"> -->
          <!-- <form action="myclassname/myclassmethod_array" method="POST"> -->
          <form action="myclassname/myclassmethod_object" method="POST">
            <div class="form-group">
              <label for="name"></label>
              <input type="text" name="name" class="form-control" />
            </div>
            <button type="submit" class="btn btn-default">Submit</button>
          </form>
          <table id="data-table" class="table table-striped">
            <thead>
              <tr>
                <th>Name</th>
                <th>Age</th>
              </tr>
            </thead>
            <tbody>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
    <script src="custom.js"></script>
  </body>
</html>

custom.js

(function()
{
  $('form').on('submit', function(event)
  {
    $.post('formhandler.php?action='+$(this).attr('action'), $(this).serialize(), function(data)
    {
      var json_obj = JSON.parse(data);
      if(json_obj.hasOwnProperty('message'))
      {
        $('#message').text(json_obj.message);
        $('#message').show();
        $('#message').fadeOut(3000);
      }
      else
      {
        $.each(json_obj, function(name,age)
        {
          $('#data-table > tbody').appendRow(name,age);            
        });
        $('#data-table').show();
      }
    });
    event.preventDefault();
  });
})();

$.fn.appendRow = function()
{
  var s = '<tr>';
  for (var i = 0; i < arguments.length; i++)
  {
    s += '<td>'+arguments[i]+'</td>';
  }
  s += '</tr>';
  return $(this).append(s);
}

formhandler.php

<?php
if(isset($_GET['action']))
{
$arr = split('/', $_GET['action']);
$class = $arr[0];
$method = $arr[1];
require_once $class.'.class.php';
if(class_exists($class))
{
$evalStr = '$'.$class.' = new '.$class.'($_POST);';
eval($evalStr);
if(method_exists($class, $method))
{
$evalStr = '$returnValue = $'.$class.'->'.$method.'();';
eval($evalStr);
}
else
{
$returnValue = 'Method does not exist';
}
}
else
{
$returnValue = 'Class does not exist';
}
}
else
{
$returnValue = 'No action given';
}

if(is_object($returnValue) || is_array($returnValue))
{
echo json_encode($returnValue);
}
else
{
$returnArr = array('message'=>$returnValue);
echo json_encode($returnArr);
}
?>

myclassname.class.php

<?php
class myclassname
{
private $pa;
function __construct($postArray = array())
{
$this->pa = $postArray;
}

function myclassmethod_string()
{
return 'Your name is '.$this->pa['name'];
}

function myclassmethod_array()
{
$myArr = array('Peter'=>'35', 'Ben'=>'37', 'Joe'=>'43');
return $myArr;
}

function myclassmethod_object()
{
$myObj = (object) array('Peter'=>'35', 'Ben'=>'37', 'Joe'=>'43');
return $myObj;
}

function __destruct()
{

}
}
?>

Monday 6 October 2014

Using PHP to get YouTube Channel feed into Twitter Bootstrap thumbnails

I've been working on a Twitter Bootstrap site. The client created a YouTube channel and wanted the feed coming into the site. Some of the videos added are uploaded by the users, some come from subscriptions. There is a nice class called thumbnail in Twitter Bootstrap for such things, so I thought I'd use that. I'm happiest getting external data using PHP. Here's how it's done.
Replace the word 'Google' with the name of your channel.
<?php
$url = 'https://gdata.youtube.com/feeds/api/videos?q=Google&max-re%20sults=5&v=2&alt=jsonc&orderby=published';
$json = file_get_contents($url);
$data = json_decode($json);
$items = $data->data->items;
foreach($items as $child)
{
echo '<a href="'.$child->player->default.'" class="thumbnail">';
echo '<h4>'.$child->title.'</h4>';
echo '<img src="'.$child->thumbnail->sqDefault.'" alt="'.$child->title.'" />';
echo '<footer>'.date("jS F Y",strtotime($child->updated)).'</footer>';
echo '</a>';
}
?>

Monday 1 October 2012

Simple JSON retrieval through jQuery

This page explains how to retrieve some simple JSON data and append it to a page. First the JSON through a script called jsonout.php

{
  "one": "Singular sensation",
  "two": "Beady little eyes",
  "three": "Little birds pitch by my doorstep"
}


Now the HTML with jQuery to retrieve and display it within the page.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple JSON retrieval through jQuery</title>
<!--[if IE]>
 <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />
<style>
body
{
font:10px/15px Sans-serif;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1"); 
</script>
</head>
<body>
<script>
(function()
{
$.getJSON('jsonout.php', function(data)
{
  $.each(data, function(key, val)
  {
    $('body').append('<p>'+key+':'+val+'</p>');
  });
});
})();
</script>
</body>
</html>

Friday 22 July 2011

Lorem and Gibberish through PHP using the randomtext.me JSON API

Crikey! Is it so long since I did a post. OK. Here is yet another way of getting Lorem Ipsum or Gibberish to your page, while you test it out. There is a great generator at http://www.randomtext.me/ and they have helpfully supplied us with a JSON based API.

Below is an example ho grabbing 7 paragraphs of gibberish between 30 and 50 characters long. I then echo them to the page.


<?php
$data = json_decode(file_get_contents("http://www.randomtext.me/api/gibberish/p-7/30-50"));
echo $data->text_out;
?>

Tuesday 28 June 2011

PHP, JSON basic example using Topsy Otter

Topsy Otter

Otter API is a RESTful HTTP web service to Topsy. Topsy is a search engine that ranks links, photos and tweets by the number and quality of retweets they receive. The quality of retweets is determined by the influence of the Twitter users.

Below I have used PHP to display results of an Otter call which returns JSON. The results are for the most popular stories on wired.com today.

<?php
$data = json_decode(file_get_contents("http://otter.topsy.com/search.json?q=site:wired.com&window=d"));

foreach ($data as $name => $value)
{
 echo $value->total.'<br />';
 getAllItems($value->list);
}

function getAllItems($iarr)
{
foreach((array)$iarr as $itemName => $itemValue)
{
echo $itemValue->content.'<br />';
}
}
?>

PHP, JSON basic example using delicious

Here is an example of extracting and displaying JSON results through PHP. In this instance, I am using my delicious feed.
Having received the data and decoded it into an array, I like to see the structure of the data. This is where the <pre> tags come in handy. Once you have seen the structure, you know how to traverse and pick out the values you need. Given that the code below is so small, I have commented it.



<?php
/* Get the data and put it into an array */
$data = json_decode(file_get_contents("http://feeds.delicious.com/v2/json/guitarbeerchocolate"));

/* Display the structure of the data so that we know what to extract */
/* Comment out once understood */
echo '<pre>';
print_r($data);
echo '</pre>';

/* Traverse the array, picking out the values you need */
foreach ($data as $name => $value)
{
echo $value->u.'<br />';
echo $value->d.'<br />';
getAllItems($value->t);
echo $value->dt.'<br />';
echo $value->n.'<br />';
echo $value->a.'<br />';
}

/* Some values in this case, tags are themselves arrays so traverse those too */
function getAllItems($iarr)
{
foreach($iarr as $item)
{
echo $item.', ';
}
echo '<br />';
}
?>