Category Archives: JavaScript / Ajax

upload file in JQuery

function imageManager(){
	var fd = new FormData(); 
	var files = $('#file')[0].files[0]; 
	fd.append('file', files); 

	$.ajax({
	  type:"POST",
	  url:"http://127.0.0.1/ajax/do-item.ajax.php",
	  data: fd, 
		contentType: false, 
		processData: false, 
	  beforeSend:function(){
		$("#ajax-file").html("Loading...");
	  },
	  success:function(data){
		$("#ajax-file").html(decodeURI(data));
	  }
	});
}

<?php
   var_dump($_FILES);
?>

Get store information in Google Map

<!DOCTYPE html>
<html>
  <head>
    <title>Place Searches</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
    <script>
      var map;
      var infowindow;

      function initMap() {
        var pyrmont = {lat: -33.867, lng: 151.195};

        map = new google.maps.Map(document.getElementById('map'), {
          center: pyrmont,
          zoom: 15
        });

        infowindow = new google.maps.InfoWindow();
        var service = new google.maps.places.PlacesService(map);
        service.nearbySearch({
          location: pyrmont,
          radius: 500,
          type: ['store']
        }, callback);
      }

      function callback(results, status) {
        if (status === google.maps.places.PlacesServiceStatus.OK) {
          for (var i = 0; i < results.length; i++) {
            createMarker(results[i]);
          }
        }
      }

      function createMarker(place) {
        var placeLoc = place.geometry.location;
        var marker = new google.maps.Marker({
          map: map,
          position: place.geometry.location
        });

        google.maps.event.addListener(marker, 'click', function() {
          infowindow.setContent(place.name);
          infowindow.open(map, this);
        });
      }
    </script>
  </head>
  <body>
    <div id="map"></div>
    <script src="https://maps.googleapis.com/maps/api/js?key=Key&libraries=places&callback=initMap" ></script>
  </body>
</html>

Output :
get-store-information-in-google-map

node.js + mqtt (Docker)

Directory Path : /app

Dockerfile

FROM node:latest
# 
WORKDIR specifies the directory our
# application's code will live within
WORKDIR /app
# We copy our package.json file to our
# app directory

RUN npm install -g nodemon

COPY package.json /app/package.json
# We then run npm install to install
# express for our application
RUN npm install && npm ls
RUN mv /app/node_modules /node_modules

# We then copy the rest of our application
# to the app direcoty
COPY . /app
# We start our application by calling
# npm start.
CMD ["npm", "start"]

mqtt-server.js

var mqtt = require('mqtt');
var fs = require('fs');
var path = require('path');

var clientID = "HKOSub"+Math.random().toString(36).substring(7);

var TRUSTED_CA_LIST = fs.readFileSync(path.join(__dirname, './key.pem'));

var address = '127.0.0.1';
var PORT = 1883;

const options = {
    host: address,
    port: PORT,
    keepalive: 60,
    clientId: clientID,
    // username: "testing_user",
    // password: "password",
    // protocol: 'mqtts',
    // rejectUnauthorized: true,
    // ca: TRUSTED_CA_LIST
};

var client = mqtt.connect(options);
var topic="name/#"
client.subscribe(topic, {  //subscribe to /[SI]/[DI]/raw/json
    qos: 1
});

client.on('message', function (topic, message) {
    console.log("[Received] topic: " + topic.toString());  //Print topic name
    console.log("[Received] message: " + message.toString()); //Print payload
})

function publishdata() {
  client.publish('LEUNG/test/time', 'Current time is: ' + new Date());
}

//setInterval(publishdata, 5000); //publish data every 10 seconds

package.json

{
    "name": "mqtt",
    "version": "1.0.0",
    "main": "mqtt-server.js",
    "dependencies": {
      "express" : "^4.16.3",
      "mqtt" : ""
    },
    "scripts": {
      "start": "node mqtt-server.js"
    }
  }

Docker

Docker build -t mqtt-server .

docker run -it -p 9001:3000 -v $(pwd):/app mqtt-server

Automatically Picking up Changes in node.js (Docker)

Location Dir Path : /app

app.js

const express = require("express");
const app = express();

app.get("/", (req, res) => res.send(`Hello World!`));

app.listen(3000, () => {
  console.log(`Example app listening on port 3000!`);
});

Dockerfile

FROM node:latest
# 
WORKDIR specifies the directory our
# application's code will live within
WORKDIR /app
# We copy our package.json file to our
# app directory
RUN npm install -g nodemon
COPY package.json /app/package.json
# We then run npm install to install
# express for our application
RUN npm install && npm ls
RUN mv /app/node_modules /node_modules
# We then copy the rest of our application
# to the app direcoty
COPY . /app
# We start our application by calling
# npm start.
CMD ["npm", "start"]

package.json

{
    "name": "hello-world",
    "version": "1.0.0",
    "main": "app.js",
    "dependencies": {
      "express" : "^4.16.3"
    },
    "scripts": {
      "start": "node app.js"
    }
}

Docker:

docker build -t node-docker-tutorial .

docker run -it -p 9001:3000 -v $(pwd):/app node-docker-tutorial

Output :
http://127.0.0.1:9001 Hello World

automatically-picking-up-changes-in-node-js-docker

Docker + node.js

Location Dir Path : /app

app.js

const express = require("express");
const app = express();

app.get("/", (req, res) => res.send(`Hello World!`));

app.listen(3000, () => {
  console.log(`Example app listening on port 3000!`);
});

Dockerfile

FROM node:latest
# Create app directory
WORKDIR /app
# Copy package.json and package-lock.json using a wildcard
COPY package*.json ./
# Install app dependencies
RUN npm install
# Bundle app source
COPY . ./app
EXPOSE 8080
CMD ["npm", "start"]

package.json

{
    "name": "simple-rest-api",
    "version": "1.0.0",
    "main": "app.js",
    "dependencies": {
      "express": "^4.16.3"
    },
    "scripts": {
      "start": "node app.js"
    }
}

Building our Docker Image

docker build -t node-docker .

docker run -d -p 9000:3000 node-docker

Output :
127.0.0.1:9000 Hello World!

Docker + node.js