Thursday, August 8, 2019

node.js + mongodb

NODE.JS + MONGODB 

Creating our Node project

Open your terminal and make a new folder.

mkdir mongotest

Run this command to make a recent Node project. It’s a good practice.

npm init --y

Let’s install the official MongoDB node module.

npm install --save mongodb

Connecting to MongoDB

Here is the code to connect to the MongoDB using Node.

const mongo = require('mongodb');
const url = "mongodb://localhost:27017";

mongo.connect(url, {useNewUrlParser: true}, (err, db) => {
        if(err) {
           console.log(err);
           process.exit(0);
        }
        console.log('database connected!');
        db.close();
});

Next, we need to select the database and create our collection in it.
Here is that the code to do the same.

const mongo = require('mongodb');
const url = "mongodb://localhost:27017";

mongo.connect(url, {useNewUrlParser: true}, (err, db) => {
        if(err) {
           console.log(err);
           process.exit(0);
        }
        console.log('database connected!');
        var dbo = db.db('codeforgeek');
        dbo.createCollection('users', (err, result) => {
            if(err) {
               console.log(err);
               process.exit(0);
            }
            console.log('collection created!');
            db.close();
        });
});

After a successful MongoDB connection, we choose the MongoDB database.

var dbo = db.db('codeforgeek');

Then, we try to create a collection naming users within the codeforgeek database.

Inserting data in the collection

Let’s add some entries in our collection. consider the code below.

const mongo = require('mongodb');
const url = "mongodb://localhost:27017";

mongo.connect(url, {useNewUrlParser: true}, (err, db) => {
    if(err) {
       console.log(err);
       process.exit(0);
    }
    let data = [{
       "id": 100,
        "name": "Shahid"
    },{
        "id": 101,
        "name": "Rahil"
    },{
        "id": 102,
        "name": "John"
    }];
    var dbo = db.db('codeforgeek');
    console.log('database connected!');
    var collection = dbo.collection('users');
    collection.insertMany(data, (err, result) => {
        if(err) {
            console.log(err);
            process.exit(0);
        }
        console.log(result);
        db.close();
    });
});

In the code shown on top of, we are using insertMany() function to add multiple entries at one go. However, you'll be able to conjointly use insertOne() function to add single entries if you wish.


Find the data in collection

We can use find() function to go looking for the records in MongoDB.
Here could be a code to indicate all the records present in the collection.

const mongo = require('mongodb');
const url = "mongodb://localhost:27017";

mongo.connect(url, {useNewUrlParser: true}, (err, db) => {
    if(err) {
       console.log(err);
       process.exit(0);
    }
    var dbo = db.db('codeforgeek');
    console.log('database connected!');
    var collection = dbo.collection('users');
    collection.find().toArray((err, results) => {
        if(err) {
            console.log(err);
            process.exit(0);
        }
        console.log(results);
        db.close();
    });
});

You can also add search parameters to help you find specific documents. simply change the query to this:

    collection.find({name: 'shahid'}).toArray((err, results) => {
        if(err) {
            console.log(err);
            process.exit(0);
        }
        console.log(results);
        db.close();
    });

Update the document in the collection

You can update the prevailing document using updateOne() operate. the first parameter is for looking out the document and the second is to a change it with new values. Here is the snipping.

collection.updateOne({name: 'Shahid'}, {'$set': {'name': 'Shahid Shaikh'}}, (err, results) => {
    if(err) {
        console.log(err);
        process.exit(0);
    }
    console.log(results);
    db.close();
});

Delete the document in the collection

You can delete the prevailing documents in the collection using deleteOne() function.

collection.deleteOne({name: 'Shahid'}, (err, results) => {
    if(err) {
        console.log(err);
        process.exit(0);
    }
    console.log(results);
    db.close();
});


Nodejs

INTRO:- 
Node.js is an open-source, cross-platform JavaScript run-time environment that executes JavaScript code outside of a browser.

"Hello World"

Ok, let's simply jump within the cold water and write our initial Node.js application: "Hello World".

Open your favorite editor and make a file known as helloworld.js. we wish it to write down "Hello World" to STDOUT, and here is that the code required to try to that:


console.log("Hello World"); 

Save the file, and execute it through Node.js:

node helloworld.js


This should output Hello World on your terminal.

Ok, these things are boring, right? Let's write some real thing.


 A full-blown web application with Node.js

The use cases

Let's keep it easy, however realistic:

➤  The user ought to be able to use our application with an online browser
➤  The user ought to see a welcome page once requesting http://domain/start that displays a file transfer kind
➤  By selecting a picture file to transfer and submitting the shape, this image ought to then be uploaded to http://domain/upload, wherever it's displayed once the transfer is finished

Fair enough. Now, you'll reach this goal by googling and hacking along one thing. however, that is not what we would like to try to here.

Furthermore, we do not wish to put in writing solely the foremost basic code to attain the goal, but elegant and proper this code may be. we'll designedly add a lot of abstraction than necessary so as to urge a sense for building a lot of advanced Node.js applications.

The application stack

Let's dissect our application. those elements got to be enforced so as to satisfy the utilization cases?

➤  We want to serve websites, so we'd like an associate HTTP server
➤  Our server can be got to answer otherwise to requests, betting on that URL the request was inquiring for, so we'd like some reasonable router so as to map requests to request handlers
➤  To fulfill the requests that came across the server and are routed using the router, we'd like actual request handlers
➤  The router most likely ought to additionally treat any incoming POST information and provides it to the request handlers in a very convenient type, so we'd like request information handling
➤  We not only need to handle requests for URLs, we have a tendency to additionally need to show content once these URLs square measure requested, which suggests we'd like some reasonably read logic the request handlers will use so as to send content to the user's browser
➤  Last however not least, the user are able to transfer pictures, therefore we have a tendency to square measure getting to want some reasonably transfer handling that takes care of the main points

Let's suppose a flash concerning however we'd build this stack with PHP. it isn't specifically a secret that the everyday setup would be associate Apache HTTP server with mod_php put in. 
This successively implies that the total "we got to be able to serve websites and receive HTTP requests" stuff does not happen inside PHP itself.

Well, with node, things square measure a touch completely different. as a result of Node.js, we have a tendency to not solely implement our application, we have a tendency to conjointly implement the total HTTP server. In fact, our net application and its net server square measure essentially identical.

This may sound sort of a heap of labor, however, we are going to see in a very moment that with Node.js, it's not.

Let's simply begin at the start and implement the primary a part of our stack, the HTTP server.

Building the application stack

A basic HTTP server

When I got hold of the purpose wherever I wished to begin with my initial "real" Node.js application, I wondered not only the way to truly code it, however additionally the way to organize my code. 
Would I like to own everything in one file? Most tutorials on the net that teach you ways to write a basic HTTP server in Node.js have all the logic in one place. What if I need to create positive that my code stays readable the additional stuff I implement?

Turns out, it's relatively simple to stay the various considerations of your code separated, by swinging them in modules.

This allows you to own a clean computer file, that you execute with Node.js and clean modules which will be employed by the most file and among one another.

So, let's create the main file that we have a tendency to use to begin our application, and a module file wherever our HTTP server code lives.

My impression is that it's additional or less a regular to call your main file index.js. It makes sense to put our server module into a file named server.js.

Let's begin with the server module. create the digital computer.js within the root directory of your project, and fill it with the subsequent code:

var http = require("http");

http.createServer(function(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}).listen(8888);

That's it! you only wrote a working HTTP server. Let's prove it by running and testing it. First, execute your script with Node.js:

node server.js

Now, open your browser and point it at http://localhost:8888/. This should display a web page that says "Hello World".

That's quite interesting, isn't it? however about talking about what is going on here and leaving the question of the way to organize our project for later? I promise we'll go back to it.

Analyzing our HTTP server

Well, then, let's analyze what is truly occurring here.

The first line needs the http module that ships with Node.js and makes it accessible through the variable http.

We then call one in every of the functions the http module offers: createServer. This function returns an object, and this object has a method named listen, and takes a numeric price that indicates the port range our http server goes to listen on.

Please ignore for a second the perform definition that follows the opening bracket of http.createServer.

We could have written the code that starts our server and makes it listen at port 8888 like this:

var http = require("http");

var server = http.createServer();
server.listen(8888);

That would begin an http server listening at port 8888 and doing nothing else (not even answering any incoming requests).

The very interesting (and, if your background could be a a lot of conservative language like PHP, odd looking) part is that the function definition right there wherever you'd expect the first parameter of the createServer() call.

Turns out, this function definition is that the 1st (and only) parameter we are giving to the createServer() call. because in JavaScript, functions can be passed around like any alternative value.

Passing functions around

You can, for example, do something like this:

function say(word) {
  console.log(word);
}
function execute(someFunction, value) {
  someFunction(value);
}
execute(say, "Hello");

Read this carefully! we pass the function say as the 1st parameter to the execute function. Not the return value of say, however, say itself!

Thus, say becomes the local variable someFunction within execute, and execute will call the function in this variable by provision someFunction() (adding brackets).

Of course, because say takes one parameter, execute will pass such a parameter when calling someFunction.

We can, as we simply did, pass a function as a parameter to a different function by its name. however we do not got to take this indirection of 1st defining, then passing it - we will define and pass a function as a parameter to a different function in-place:

function execute(someFunction, value) {
  someFunction(value);
}
execute(function(word){ console.log(word) }, "Hello");


We define the function we wish to pass to execute right there at the place wherever execute expects its 1st parameter.

This way, we do not even need to provide the function a name, which is why this can be called an anonymous function.

This is a first glimpse at what i prefer to call "advanced" JavaScript, however let's take it step by step. For now, let's simply accept that in JavaScript, we can pass a function as a parameter when calling another function. we can try this by assigning our function to a variable, which we then pass, or by defining the function to pass in-place.

How function passing makes our HTTP server work

With this information, let's revisit to our minimalistic http server:

var http = require("http");

http.createServer(function(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}).listen(8888);

By currently it ought to be clear what we are actually doing here: we pass the createServer function an anonymous function.

We might come through the same by refactoring our code to:

var http = require("http");

function onRequest(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}

http.createServer(onRequest).listen(8888);

Maybe now could be an honest moment to ask: Why are we doing it that way?

Event-driven asynchronous callbacks

To understand why Node.js applications need to be written this manner, we want to understand however Node.js executes our code. Node's approach is not unique, however, the underlying execution model is different from runtime environments like Python, Ruby, PHP or Java.




Tuesday, July 16, 2019

ER-Diagram

                               ER-Diagram


What is Associate in Entity Entity Relationship Diagram (ER Diagram)?

An ER diagram shows the connection among entity sets. Associate in Entity entity set may be a cluster of comparable entities and these entities will have attributes. In terms of DBMS, Associate in Entity entity may be a table or attribute of a table in info, therefore by showing the relationship among tables and their attributes, the ER diagram shows the entire logical structure of info. Lets have a glance at an easy ER diagram to know this idea.

A simple ER Diagram:

In the following diagram we've 2 entities Student and faculty and their relationship. the connection between Student and faculty is several to 1 as a university will have several students but a student cannot study in multiple faculties at the identical time. The student entity has attributes like Stu_Id, Stu_Name & Stu_Addr and faculty entity has attributes like Col_ID & Col_Name.





Rectangle: Represents Entity sets.
Ellipses: Attributes
Diamonds: Relationship Set
Lines: They link attributes to Entity Sets and Entity sets to Relationship Set
Double Ellipses: Multivalued Attributes
Dashed Ellipses: Derived Attributes
Double Rectangles: Weak Entity Sets
Double Lines: Total participation of Associate in Entity entity during a relationship set

Components of a ER Diagram





As shown within the higher than diagram, Associate in Entity ER diagram has 3 main components:
1. Entity
2. Attribute
3. Relationship

1. Entity




An entity is Associate in Entity object or element of knowledge. Associate in Entity entity is diagrammatical as parallelogram in Associate in Entity ER diagram.
For example: within the following ER diagram we've got 2 entities Student and faculty and these 2 entities have several to at least one relationship as several students study in a very single faculty. we'll browse additional regarding relationships later, for currently specialize in entities.


Weak Entity:
An entity that can't be unambiguously known by its own attributes and depends on the link with alternative entity is termed weak entity. The weak entity is pictured by a double parallelogram. as an example – a checking account can't be unambiguously known while not knowing the bank to that the account belongs, therefore checking account may be a weak entity




2. Attribute

An attribute describes the property of Associate in Entity entity. Associate in Entity attribute is pictured as Oval in Associate in Entity ER diagram. There square measure four forms of attributes:

1. Key attribute
2. Composite attribute
3. Multivalued attribute
4. Derived attribute

1. Key attribute:

A key attribute will unambiguously establish Associate in Entity entity from Associate in Entity entity set. as an example, student roll range will unambiguously establish a student from a group of scholars. Key attribute is pictured by oval same as alternative attributes but the text of key attribute is underlined.



2. Composite attribute:

An attribute that's a mix of different attributes is understood as composite attribute. for instance, In student entity, the scholar address may be a composite attribute as associate address consists of different attributes like pin code, state, country.




3. Multivalued attribute:

An attribute that may hold multiple values is understood as multivalued attribute. it's described with double ovals in associate ER Diagram. for instance – an individual will have over one variety|telephone number|number|signal|signaling|sign}s therefore the phone number attribute is multivalued.

4. Derived attribute:

A derived attribute is one whose price is dynamic and derived from another attribute. it's described by dotted oval in associate ER Diagram. for instance – Person age may be a derived attribute because it changes over time and may be derived from another attribute (Date of birth).



3. Relationship

A relationship is described by diamond form in ER diagram, it shows the connection among entities. There ar four varieties of relationships:
1. One to One
2. One to Many
3. Many to One
4. Many to Many

1. One to One

When one instance of associate entity is related to one instance of another entity then it's known as one to at least one relationship. for instance, an individual has just one passport and a passport is given to at least one person.



2. One to Many

When one instance of associate entity is related to quite one instances of another entity then it's referred to as one to several relationship. as an example – a client will place several orders however a order can not be placed by many purchasers.



3. Many to Many
When quite one instances of associate entity is related to one instance of another entity then it's referred to as several to at least one relationship. as an example – several students will study during a single faculty however a student cannot study in several faculties at identical time.



4. 

When quite one instances of associate entity is related to quite one instances of another entity then it's referred to as several to several relationship. as an example, a may be allotted to several comes and a project may be allotted to several students.




Total Participation of associate Entity set

A Total participation of associate entity set represents that every entity in entity set should have a minimum of one relationship during a relationship set. For example: within the below diagram every faculty should have at-least one associated Student.



Sunday, July 7, 2019

mongo db



Image result for mongo db


INTRO:- 
MongoDB is an open-source document database and leading NoSQL database.


 Paste Article Duplication Processing Re-Write Suggestion Done (Unique Article)
1. to make a data
Use the command — use data name>




2. To list the Databases within the Mongolian monetary unit dB system.
Use the command — show dbs
This command can show the default DB’s and also the one’s created by the consumer. but If there aren't any collections within the dB created then it won’t be shown within the list. conjointly to ascertain that data is presently elect then use the command- dB. The below image shows the data that
currently being operated on.




3. Drop data
Use the command — dB.dropDatabase(). Follow the below commands wherever the databases ar shown before and once dropping the chosen data. we have a tendency to cannot specify a particular data name. The data that is presently elect are mechanically deleted. conjointly we've got inserted some knowledge into sampledb that is why it's showing within the list. If no knowledge was there in sampledb then wouldn't have appeared once writing the command — show dbs.




4. produce assortment
The below method shows show to make a set in an exceedingly data. within the assortment lies the document. Use the command — dB.collectionname.insert(). The below image shows just one document created within the assortment ‘Country’. we are able to produce multiple documents within the same assortment. This assortment refers to the Table for HBase or either a relation DBMS.




The below example shows a set having multiple documents. Notice the quantity of fields in each the documents. the first document doesn't have the suburban area field which implies we've got to insert solely those data that is obtainable with United States of America.




5. to search out the documents within the assortment
Use the command- dB.collectionname.find(). the item ID’s would be appended to the every document on it’s own. this may build every document distinctive.




We can conjointly use AND and OR operator to search out specific documents at intervals the gathering. for example to search out the document that has the town city use the below command:
db.country.find();

6. Update the Document at intervals the gathering
To update a selected field use the command-
db.collectionname.update(,})
Before Update




After Update




7. Delete a Document
To delete a document use the below command-
db.collectioname.remove()




We can conjointly use the command dB.collectionname.remove() to truncate the whole assortment and has been supplemental within the Version two.6. Earlier the command dB.collectionname.remove() accustomed work. this is often resembling the truncate command in SQL.

8. Projection of rows
To select the desired fields we are able to use the below given command. we want to append either ‘1’ or ‘0’ to the sector within the command. If we have a tendency to provides a ‘1’ then all the rows for that field can seem and ‘0’ can provide the other way around results. If the sector name isn't laid out in the command then it default takes a ‘1’ for the item ID field, this case doesn't applied for all the opposite field s within the list. The fields here correspond to the columns in RDBMS.
db.collectionname.find(,field:1})




9. Limiting the rows
This is the advanced version of projected the rows. In Projection technique all the rows would seem leading to United States of America obtaining unwanted knowledge. Here we are able to limit the columns additionally as skip few of the rows. Use the command -db.collectionname.find(,zero,field:1 or 0…}).limit(1).skip(1). This methodology can retrieve just one row. the quantity of skips determines the quantity of rows which will be aloof from the result.




10. Sorting the rows
In this methodology we are able to type the rows within the ascending or downward-sloping manner. choose the fields that ar required so append a one or -1 to the type command. Default is one, thence in such a case the type command needn't be specific. The ascending or downward-sloping are supported the column elect within the type command.
Command: dB.country.find(,).sort()




These ar the few ways to control with Mongolian monetary unit dB. The syntax ar user friendly and easy to know. Associate in Nursing another advantage of this data is, we want not embody all the fields all told the documents at intervals an equivalent assortment. for example, If one document contains a field named town and also the alternative document doesn't would like it then we want not embody it. This helps in saving plenty of area. talk to the below example







jQuery


Image result for jquery
INTRO:-  
jQuery is a JavaScript library designed to simplify HTML DOM tree traversal and manipulation, as well as event handling, CSS animation, and Ajax


Query — New Wave JavaScript

  ➤ In the spirit of open supply software system development, jQuery continuously encourages community code contribution. to assist you start and before you jump into writing code, make certain to browse these vital contribution tips thoroughly:

   1.Getting concerned
   2.Core vogue Guide
   3.Writing Code for jQuery Foundation comes

Environments during which to use jQuery

  ➤ Browser support
  ➤ jQuery conjointly supports Node, browser extensions, and                alternative non-browser environments.

What you wish to make your own jQuery

  ➤ To build jQuery, you wish to possess the most recent Node.js/npm and lowlife one.7 or later. Earlier versions would possibly work, however aren't supported.

  ➤ For Windows, you've got to transfer and install lowlife and Node.js.

  ➤ OS X users ought to install alcoholic beverage. Once alcoholic beverage is put in, run brew install lowlife to put in lowlife, and brew install node to put in Node.js.

  ➤ Linux/BSD users ought to use their applicable package managers to put in lowlife and Node.js, or build from supply if you swing that approach. Easy-peasy.

How to build your own jQuery

  ➤ Clone a replica of the most jQuery lowlife repo by running:

git clone lowlife://github.com/jquery/jquery.git

Enter the jquery directory and run the build script:

cd jquery && npm run build


  ➤ The designed version of jQuery are going to be place within the dist/ directory, in conjunction with the minified copy and associated map file.

  ➤ If you would like to make custom build or facilitate with jQuery development, it'd be higher to put in grunt instruction interface as a world package:

npm install -g grunt-cli

  ➤ Make sure you've got grunt put in by testing:

grunt -V

  ➤ Now by running the grunt command, within the jquery directory, you'll build a full version of jQuery, a bit like with Associate in Nursing npm run build command:

grunt


  ➤ There square measure several alternative tasks offered for     jQuery Core:

grunt -help

Modules

   ➤Special builds are often created that exclude subsets of jQuery practicality. this permits for smaller custom builds once the builder is definite that those components of jQuery aren't getting used. as an example, Associate in the Nursing app that solely used JSONP for $.ajax() and didn't have to be compelled to calculate offsets or positions of components might exclude the offset and ajax/xhr modules.

   Any module is also excluded apart from core, and selector. To exclude a module, pass its path relative to the src folder (without the .js extension).

JSON



Image result for json
INTRO:- 
(JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write.


What Is JSON?

  ➤ JSON is brief for JavaScript Object Notation, store datas in an organized, easy-to-access manner. during a shell, it provides us with a human-readable assortment of data that we are able to access during an extremely logical manner.

Storing JSON data

  ➤ As a straightforward example, data concerning Pine Tree State may well be written in JSON as follows:

 var Jason = {

"age" : "24",
"hometown" : "Missoula, MT",
"gender" : "male"

 };


  ➤ This creates AN object that we have a tendency to access victimization the variable mythical being. By envelopment the variable’s worth in permed braces, we’re indicating that the worth is AN object. within the item, we are able to declare any variety of properties employing a "name": "value" pairing, separated by commas. To access the data keep in mythical being, we are able to merely discuss with the name of the property we want. as an example, to access data concerning Pine Tree State, we have a tendency to may use the subsequent snippets:

1. document.write('Jason is ' mythical being.age); // Output: mythical being is twenty four

2. document.write('Jason could be a ' mythical being.gender); // Output: mythical being could be a male



Storing JSON data in Arrays

  ➤ A slightly additional sophisticated example involves storing 2 folks in one variable. To do this, we have a tendency to enclose multiple objects in sq. brackets, that signifies AN array. as an example, if I required to incorporate data concerning myself and my brother in one variable, I would use the following:

var family = [ 
{
"age" : "24",
 "gender" : "male"
 "},
{
"age" : "21",
"gender" : "male"
}

];

  ➤ To access this data, we want to access the array index of the person we have a tendency to want to access. as an example, we might use the subsequent snip to access data keep in the family:

NOTE: this can be helpful if it'll be necessary to loop through keep data because it lends itself to a for loop with AN mechanically incrementing worth.



Nesting JSON data

  ➤ Another way to store multiple folks in our variable would be to nest objects. To do this, we might produce one thing like the following:

var family = "name" : "Jason Lengstorf",
"age" : "24",
"gender" : "male"
">,
"kyle" : "age" : "21",
"gender" : "male"
">
}

  ➤ Accessing data in nested objects could be very little easier to understand; to access data within the object, we might use the subsequent snippet:

1. document.write(family.jason.name); // Output: mythical being Lengstorf

2. document.write(family.kyle.age); // Output: twenty one

3. document.write(family.jason.gender); // Output: male
 
 ➤ Nested JSON and arrays will be combined pro re nata to store the maximum amount data as necessary.



Why will JSON Matter?

  ➤ With the increase of AJAX-powered sites, it’s changing into additional and additional vital for sites to be able to load data quickly and asynchronously, or within the background while not delaying page rendering. shift up the contents of a definite part among our layouts while not requiring a page refresh adds a “wow” issue to our applications, to not mention the extra convenience for our users. as a result of the recognition and simple social media, several sites think about the content provided by sites like Twitter, Flickr, and others. These sites offer RSS feeds, that ar simple to import and use on the server-side, however if we have a tendency to attempt to load them with mythical being, we have a tendency to run into a wall: we are able to solely load AN RSS feed if we’re requesting it from constant domain it’s hosted on. a shot to load my Flickr account’s RSS feed via jQuery’s $.ajax() technique leads to the subsequent JavaScript error:

[Exception... "Access to restricted URI denied" code: "1012"
nsresult: "0x805303f4 (NS_ERROR_DOM_BAD_URI)"
location: "http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js Line: 19"]

  ➤ JSON permits us to beat the cross-domain issue as a result of we are able to use a way known as JSONP that uses a recall perform to send the JSON data back to our domain. It’s this capability that produces JSON therefore improbably helpful because it discloses loads of doors that were antecedently tough to figure around.



How can we Load JSON into a Project?

  ➤ One of the best ways that to load JSON data into our net applications is to use the $.ajax() technique offered within the jQuery library. the convenience of retrieving data can vary supported the location providing the data, however a straightforward example would possibly appear as if this:

$.ajax(
type:'GET',
url:"http://example.com/users/feeds/",
data:"format=json&id=123",
success:function(feed) ,
dataType:'jsonp'
);

  ➤ This example would request the newest feed things in JSON format and output them to the browser. Obviously, we have a tendency to wouldn’t wish to output raw JSON data to the browser, however, this instance shows the fundamentals of loading JSON from AN external supply.




A sensible Example: Loading Flickr Streams with JSON and jQuery

[demolink]See the Demo | transfer the Source[/demolink]

  ➤ To show however JSON works during a real-world example, let’s load photographs from Flickr victimization jQuery and therefore the JSON version of Flickr’s “Latest” photo feed.

Step 1: produce the mythical being Request
Flickr’s photostream feeds ar comparatively simple to access. All users have a novel ID variety, that we'll send as a part of the request to the present computer address.

http://api.flickr.com/services/feeds/photos_public.gne
  
 ➤ The request we want to send asks for the newest photos from the user in question, alongside flags soliciting for a JSON-formatted response. The request we want to send can appear as if this:

 id=XXXXXXXX@NXX&lang=en-us&format=json&jsoncallback=?

  ➤ In the on top of example, XXXXXXXX@NXX has to get replaced with the user’s ID. We’ll be writing a perform, therefore the user’s ID is going to be passed as AN argument known as flickrID. Our perform are going to be known as loadFlickr(). Let’s produce the perform which will load our JSON response:

function loadFlickr(flickrid)
{

$('#feed').html('');
$.ajax({
type:'GET',
url:"http://api.flickr.com/services/feeds/photos_public.gne",
data:"id="+flickrid+"&lang=en-us&format=json&jsoncallback=?",
success:function(feed) {
// Do one thing with the response
},
dataType:'jsonp'
});

}

  ➤ The came JSON data can look one thing like this (note that I’ve removed well-nigh one among the came photos for the sake of brevity):

({
"title": "Uploads from ennuidesign",
"link": "http://www.flickr.com/photos/ennuidesign/",
"description": "",
"modified": "2009-03-17T03:53:36Z",
"generator": "http://www.flickr.com/",
"items": [
{
"title": "This Is however You Get folks to speak concerning You",
"link": "http://www.flickr.com/photos/ennuidesign/3361269251/",
"media": ,
"date_taken": "2009-03-16T21:53:36-08:00",
"description": "
ennuidesign announce a photo:" descripton",
"published": "2009-03-17T03:53:36Z",
"author": "nobody@flickr.com
/* <![CDATA[ */
(function()s=document.createTextNode(s);l.replaceChild(s,l);}}catch(e)})();
/* ]]> */
(ennuidesign)",
"author_id": "29080075@N02",
"tags": "gift ennuidesign trevorgnauck bluedragoncustomlaserengraving"
}
// the remainder of the photograph entries go here...

]
})



Step 2: method the JSON data

  ➤ What we’re reaching to do is show the thumbnails of the newest sixteen photos, which is able to link to the medium-sized show of the image. The Flickr JSON could be a very little confusing, and it doesn’t offer an immediate link to the fingernail version of our photos, therefore we’ll ought to use some trickery on our finish to induce to that, that we’ll cowl in only an instant. every photograph entry is keep in AN array known as things, that we have a tendency to access in our mythical being decision victimization feed.items. to induce to the data concerning every entry, we’ll loop through the things till we’ve either hit the last offered photograph or sixteen total photos; whichever comes initial. Let’s modify our perform and got wind of the loop:

function loadFlickr(flickrid)
{

// show a loading icon in our show part
$('#feed').html('');
// Request the JSON and method it
$.ajax({
type:'GET',
url:"http://api.flickr.com/services/feeds/photos_public.gne",
data:"id="+flickrid+"&lang=en-us&format=json&jsoncallback=?",
success:function(feed) {
// produce AN empty array to store pictures
volt-ampere thumbs = [];
// Loop through the things
for(var i=0, l=feed.items.length; i < l && i < 16; i)
{
// method every image
}
// show the thumbnails on the page
},
dataType:'jsonp'
});

}

  ➤ The part we’re curious about is that the “m” part keep among the “media” part. this could be accessed among our loop victimization feed.items[i].media.m. We’re reaching to run an everyday expression on this worth to induce each the medium and fingernail image ways, that we’ll assemble into a coupled fingernail image. Then, we have a tendency to’ll push the recently assembled markup language into the array of thumbs we created. when we’ve finished the loop, we’ll mix all the pictures into one string of markup language and replace the contents of our show part with the loaded thumbnails. Let’s add this practicality to our script:
function loadFlickr(flickrid)
{
// show a loading icon in our show part
$('#feed').html('');
// Request the JSON and method it
$.ajax({
type:'GET',
url:"http://api.flickr.com/services/feeds/photos_public.gne",
data:"id="+flickrid+"&lang=en-us&format=json&jsoncallback=?",
success:function(feed) {
// produce AN empty array to store pictures
volt-ampere thumbs = [];
// Loop through the things
for(var i=0, l=feed.items.length; i < l && i < 16; i)
{
// Manipulate the image to induce thumb and medium sizes
volt-ampere img = feed.items[i].media.m.replace(
/^(.*?)_m.jpg$/,
''
);
// Add the new part to the array
thumbs.push(img);
}
// show the thumbnails on the page
$('#feed').html(thumbs.join(''));
// A perform to feature a lightbox result
addLB();
},
dataType:'jsonp'
});
}

Note that I’ve additionally extra a perform known as addLB() to the tip of this function; this adds the lightbox result to our thumbnails, that is only for aesthetics.


Step 3: decision Our perform

  ➤ At this time, we’re able to decision our perform. To load my Flickr stream, we might ought to decision our perform as follows:
loadFlickr("29080075@N02");

  ➤ The example announce can pull multiple users’ photostreams into the containing box while not inflicting a page refresh. explore the ASCII text file on the demo to visualize however it had been done. NOTE: detain mind that this demo was to indicate a way to load JSON data, and not on a way to implement the code to decision the perform. The JavaScript calls ar inline, that shouldn't be employed in a production script.

[demolink]See the Demo | transfer the Source[/demolink]








Search This Blog