0% found this document useful (0 votes)
3 views13 pages

General Guidelines For JavaScript Usage

The document provides comprehensive guidelines for using JavaScript, covering essential topics such as syntax, variables, data types, functions, events, conditionals, loops, and objects. It also includes practical examples and explanations of jQuery and charting libraries like Chart.js and Plotly for data visualization with MySQL databases. Overall, it serves as a foundational resource for understanding and implementing JavaScript in web development.

Uploaded by

x1323971792
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views13 pages

General Guidelines For JavaScript Usage

The document provides comprehensive guidelines for using JavaScript, covering essential topics such as syntax, variables, data types, functions, events, conditionals, loops, and objects. It also includes practical examples and explanations of jQuery and charting libraries like Chart.js and Plotly for data visualization with MySQL databases. Overall, it serves as a foundational resource for understanding and implementing JavaScript in web development.

Uploaded by

x1323971792
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

General Guidelines for JavaScript

Usage

IE332: Computing in Industrial Engineering


Contents
1 Introduction to JavaScript 2

2 JavaScript Syntax 2

3 JavaScript Variables 2

4 JavaScript Data Types 2

5 JavaScript Functions 3

6 JavaScript Events 3

7 JavaScript Conditionals 4

8 JavaScript Loops 5

9 JavaScript Objects 6

10 JQuery 7
10.1 Setup jQuery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
10.2 Launching Code on Document Ready . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
10.3 Example: Handling Click Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
10.4 Adding and Removing HTML Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
10.5 Special Effects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
10.6 Callbacks and Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

11 Creating a Plot using Chart.js with MySQL Database 8


11.1 Setting up the MySQL Database Connection in PHP . . . . . . . . . . . . . . . . . . . . . . . 8
11.2 Fetching Data from MySQL Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
11.3 Preparing Data for Chart.js . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
11.4 Including Chart.js Library in HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
11.5 Rendering Chart using Chart.js . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

12 Creating a Plot using Plotly from a MySQL Database 10


12.1 Setup your Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
12.2 Fetch Data from MySQL Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
12.3 Process Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
12.4 Create the Plot using Plotly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
12.5 Display the Plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

1
1 Introduction to JavaScript
JavaScript is a scripting language used to create and control dynamic website content, interact with users,
and modify HTML and CSS.

2 JavaScript Syntax
JavaScript syntax is similar to Java and C. Statements are separated by semicolons (;), and JavaScript is
case-sensitive.
var x = 5 ; // D e f i n e v a r i a b l e x and a s s i g n i t t h e v a l u e 5
var y = 6 ; // D e f i n e v a r i a b l e y and a s s i g n i t t h e v a l u e 6
var z = x + y ; // D e f i n e v a r i a b l e z and a s s i g n i t t h e sum o f x and y
c o n s o l e . l o g ( z ) ; // Outputs : 11

3 JavaScript Variables
In JavaScript, variables are containers for storing data values. There are three main ways to declare variables:

• var: Used for declaring variables in JavaScript. Variables declared with var can be reassigned and
redeclared within their scope.
• let: let allows you to declare variables that are limited in scope to the block, statement, or expression
on which it is used. It is not possible to redeclare a variable using let.
• const: const is used to declare variables whose values should not be changed. It creates a constant
whose scope can be either global or local to the block in which it is declared.

var carName = ” Volvo ” ; // V a r i a b l e d e c l a r e d with var


l e t p r i c e = 5 0 0 0 0 ; // V a r i a b l e d e c l a r e d with l e t
c o n s t taxRate = 0 . 2 ; // Constant v a r i a b l e d e c l a r e d with c o n s t

4 JavaScript Data Types


JavaScript supports various data types, each serving different purposes:

• Numbers: Numeric data types, such as integers and floating-point numbers.

• Strings: Textual data enclosed within single (’ ’) or double (” ”) quotes.


• Booleans: Logical data types representing true or false values.
• Arrays: Ordered collections of data, which can contain multiple values of different types.

• Objects: Key-value pairs, where keys are strings and values can be of any data type.
• Undefined: Represents a variable that has been declared but not assigned a value.
• Null: Represents the intentional absence of any object value.

2
var age = 2 5 ; // Number
var name = ” John Doe ” ; // S t r i n g
var i s M a l e = t r u e ; // Boolean
var f r u i t s = [ ” Apple ” , ”Banana ” , ” Orange ” ] ; // Array
var p e r s o n = { f i r s t N a m e : ” John ” , lastName : ”Doe ” , age : 3 0 } ; // Object
var s a l a r y ; // Undefined
var a d d r e s s = n u l l ; // N u l l

5 JavaScript Functions
Functions in JavaScript are essential building blocks for organizing and reusing code. Here are some key
points about JavaScript functions:

• Function Declaration: Functions are declared using the function keyword, followed by the function
name and parameters (if any).
• Function Invocation: Functions are invoked or called using their name followed by parentheses. You
can pass arguments to functions when invoking them.
• Return Values: Functions can return values using the return keyword. If a function doesn’t explicitly
return a value, it returns undefined by default.
• Anonymous Functions: Functions without a name are called anonymous functions. They are often
used as function expressions or as callbacks.
• Arrow Functions: Introduced in ES6, arrow functions provide a more concise syntax for writing
functions, especially for short, single-expression functions.

// Function D e c l a r a t i o n
f u n c t i o n g r e e t ( name ) {
r e t u r n ” H e l l o , ” + name + ” ! ” ;
}

// Function I n v o c a t i o n
var g r e e t i n g = g r e e t ( ” A l i c e ” ) ;
c o n s o l e . l o g ( g r e e t i n g ) ; // Outputs : H e l l o , A l i c e !

// Anonymous Function
var m u l t i p l y = f u n c t i o n ( x , y ) {
return x ∗ y ;
}
c o n s o l e . l o g ( m u l t i p l y ( 3 , 4 ) ) ; // Outputs : 12

// Arrow Function
c o n s t s q u a r e = (num) => num ∗ num ;
c o n s o l e . l o g ( s q u a r e ( 5 ) ) ; // Outputs : 25

6 JavaScript Events
JavaScript events allow you to respond to user actions and browser activities. Here are some key points
about JavaScript events:

3
• Event Handlers: JavaScript can react to various events triggered by the user or the browser, such
as mouse clicks, keyboard inputs, and page loading.
• Event Listeners: Event listeners are functions that wait for a specific event to occur and then execute
a block of code in response.
• Event Types: There are numerous types of events in JavaScript, including mouse events (click,
mouseover, mouseout), keyboard events (keydown, keyup), form events (submit, change), and docu-
ment/window events (load, resize, scroll).
• Inline Event Handlers: Events can be handled inline within HTML elements using attributes like
onclick, onmouseover, and onsubmit.

< !DOCTYPE html>


<html>
<head>
<t i t l e>Event Example</ t i t l e>
<s c r i p t>
f u n c t i o n d i s p l a y A l e r t ( ) { \\ D e f i n e s a J a v a S c r i p t f u n c t i o n
a l e r t ( ” Button c l i c k e d ! ” ) ; \\ D i s p l a y s an a l e r t with t h e message
}
</ s c r i p t>
</head>
<body>

<button onclick=” d i s p l a y A l e r t ( ) ”>C l i c k Me</button>

</body>
</html}

7 JavaScript Conditionals
JavaScript conditionals allow you to execute different blocks of code based on different conditions. Here are
some key points about JavaScript conditionals:

• if...else Statement: The if statement allows you to execute a block of code if a specified condition
is true. You can use the else statement to execute a block of code if the condition is false.
• else if Statement: In addition to if and else, JavaScript also supports the else if statement,
which allows you to specify a new condition if the first condition is false.
• Switch Statement: The switch statement evaluates an expression and executes the correspond-
ing case statement based on the expression’s value. It provides an alternative to long if...else
if...else chains.

var hour = 1 5 ;
i f ( hour < 1 2 ) {
c o n s o l e . l o g ( ” Good morning ! ” ) ;
} e l s e i f ( hour < 1 8 ) {
c o n s o l e . l o g ( ” Good a f t e r n o o n ! ” ) ;
} else {
c o n s o l e . l o g ( ” Good e v e n i n g ! ” ) ;

4
}

// Switch Statement
var day = ”Monday ” ;
s w i t c h ( day ) {
c a s e ”Monday ” :
c o n s o l e . l o g ( ” I t ’ s Monday ! ” ) ;
break ;
c a s e ” Tuesday ” :
c o n s o l e . l o g ( ” I t ’ s Tuesday ! ” ) ;
break ;
default :
c o n s o l e . l o g ( ” I t ’ s a n o t h e r day ! ” ) ;
}

8 JavaScript Loops
Loops in JavaScript are used to execute a block of code repeatedly. They allow you to automate repetitive
tasks and iterate over data structures like arrays and objects. Here are some key points about JavaScript
loops:

• for Loop: The for loop is used when you know how many times you want to execute the code. It
consists of an initialization, a condition, and an iteration statement.
• while Loop: The while loop is used when you don’t know in advance how many times the loop will
run. It repeats a block of code as long as a specified condition is true.

• do...while Loop: Similar to the while loop, the do...while loop executes the code block once before
checking the condition.

// f o r Loop
f o r ( var i = 0 ; i < 5 ; i ++) {
// P r i n t t h e v a l u e o f i
c o n s o l e . l o g ( ” The number i s ” + i ) ;
}

// w h i l e Loop
var count = 0 ;
w h i l e ( count < 5 ) {
// P r i n t t h e v a l u e o f count
c o n s o l e . l o g ( ” Count : ” + count ) ;
// Increment count by 1
count++;
}

// do . . . w h i l e Loop
var x = 0 ;
do {
// P r i n t t h e v a l u e o f x
c ons ol e . log (” x i s : ” + x ) ;
// Increment x by 1

5
x++;
} while (x < 5 ) ;

9 JavaScript Objects
Objects in JavaScript are key components for organizing and manipulating data. Here are some key points
about JavaScript objects:

• Object Literal: Objects can be created using object literals, which consist of key-value pairs enclosed
in curly braces {}.
• Properties: Properties are key-value pairs within an object. Keys are strings that act as property
names, and values can be of any data type.
• Methods: Methods are functions defined within objects. They allow objects to perform actions or
manipulate their own properties.
• Accessing Properties: Properties and methods of an object can be accessed using dot notation
(objectName.propertyName) or bracket notation (objectName[’propertyName’]).
• Nested Objects: Objects can contain other objects as property values, creating nested structures.
• Object Constructors: Objects can also be created using constructor functions or object constructors.

// Object L i t e r a l
var p e r s o n = {
f i r s t N a m e : ” John ” ,
lastName : ”Doe ” ,
age : 3 0 ,
fullName : f u n c t i o n ( ) {
r e t u r n t h i s . f i r s t N a m e + ” ” + t h i s . lastName ;
}
};

c o n s o l e . l o g ( p e r s o n . fullName ( ) ) ; // Outputs : John Doe

// A c c e s s i n g P r o p e r t i e s
c o n s o l e . l o g ( p e r s o n . f i r s t N a m e ) ; // Outputs : John
c o n s o l e . l o g ( p e r s o n [ ’ lastName ’ ] ) ; // Outputs : Doe

// Nested O b j e c t s
var c a r = {
make : ” Toyota ” ,
model : ” C o r o l l a ” ,
year : 2022 ,
owner : {
firstName : ” Alice ” ,
lastName : ” Smith ”
}
};

c o n s o l e . l o g ( c a r . owner . f i r s t N a m e ) ; // Outputs : A l i c e

6
10 JQuery
jQuery is a popular JavaScript library. It simplifies HTML DOM manipulation, event handling, animations,
and AJAX interactions, making web development more efficient and cross-browser compatible.

10.1 Setup jQuery


To use jQuery, include the jQuery library in your HTML file using a <script> tag with the src attribute
pointing to the jQuery file. Ensure that jQuery is included before any scripts that utilize it.
< ! doctype html>
<html>
<head>
<meta charset=” u t f −8”>
<t i t l e>Demo</ t i t l e>
</head>
<body>
<a href=” h t t p : / / j q u e r y . com/ ”>jQuery</a>
<s c r i p t src=” j q u e r y . j s ”> </ s c r i p t>
<s c r i p t>
// Your jQuery code g o e s h e r e .
</ s c r i p t>
</body>
</html>

10.2 Launching Code on Document Ready


Use $(document).ready() to ensure code runs when the document is ready to be manipulated. This is
preferred over window.onload as it doesn’t wait for images to load.
$ ( document ) . ready ( f u n c t i o n ( ) {
// Your code h e r e .
});

10.3 Example: Handling Click Events


Attach event handlers to elements using jQuery selectors. Use methods like click () to define actions on
events.
$ ( document ) . ready ( f u n c t i o n ( ) {
$ (” a ” ) . c l i c k ( func tion ( event ) {
a l e r t ( ” Thanks f o r v i s i t i n g ! ” ) ;
event . preventDefault ( ) ;
});
});

10.4 Adding and Removing HTML Classes


Manipulate classes of HTML elements using addClass() and removeClass() methods.
$ ( document ) . ready ( f u n c t i o n ( ) {
$ ( ” a ” ) . a d d C l a s s ( ” t e s t ” ) ; // Adds c l a s s ’ t e s t ’
$ ( ” a ” ) . removeClass ( ” t e s t ” ) ; // Removes c l a s s ’ t e s t ’
});

7
10.5 Special Effects
jQuery provides effects like hide() to create visual transitions on elements.
$ ( document ) . ready ( f u n c t i o n ( ) {
$ (” a ” ) . c l i c k ( func tion ( event ) {
event . preventDefault ( ) ;
$ ( t h i s ) . h i d e ( ” s l o w ” ) ; // Hides t h e c l i c k e d e l e m e n t s l o w l y
});
});

10.6 Callbacks and Functions


jQuery allows passing functions (callbacks) as arguments to other functions. Use anonymous functions as
wrappers to defer execution of callbacks with arguments.
$ . g e t ( ” myhtmlpage . html ” , f u n c t i o n ( ) {
myCallBack ( param1 , param2 ) ;
});

11 Creating a Plot using Chart.js with MySQL Database


Chart.js is a user-friendly JavaScript library for creating visually appealing charts and graphs on web pages,
utilizing HTML5 canvas for rendering. With built-in interactivity features and support for multiple chart
types, it caters to various data visualization needs. While lightweight and actively maintained, Chart.js
may lack advanced features and customization options found in other libraries, and performance may be a
concern for extremely large datasets or complex charts.

11.1 Setting up the MySQL Database Connection in PHP

<?php
$servername = ” l o c a l h o s t ” ;
$username = ” your username ” ;
$password = ” y o u r p a s s w o r d ” ;
$dbname = ” y o u r d a t a b a s e n a m e ” ;

// Cr e a t e c o n n e c t i o n
$conn = new m y s q l i ( $servername , $username , $password , $dbname ) ;

// Check c o n n e c t i o n
i f ( $conn−>c o n n e c t e r r o r ) {
die ( ” Connection f a i l e d : ” . $conn−>c o n n e c t e r r o r ) ;
}
?>

11.2 Fetching Data from MySQL Database

<?php
$ s q l = ”SELECT ∗ FROM y o u r t a b l e ” ;
$ r e s u l t = $conn−>query ( $ s q l ) ;

8
$data = array ( ) ;
while ( $row = $ r e s u l t −>f e t c h a s s o c ( ) ) {
$data [ ] = $row [ ’ your column ’ ] ;
}
?>

11.3 Preparing Data for Chart.js

<?php
$ d a t a j s o n = j s o n e n c o d e ( $data ) ;
?>

11.4 Including Chart.js Library in HTML

< !DOCTYPE html>


<html>
<head>
<t i t l e>Chart . j s Example</ t i t l e>
<s c r i p t src=” h t t p s : / / cdn . j s d e l i v r . n e t /npm/ c h a r t . j s ”></ s c r i p t>
</head>
<body>
<canvas id=”myChart”></ canvas>
</body>
</html>

11.5 Rendering Chart using Chart.js

<s c r i p t >
// R e t r i e v e JSON data from a PHP v a r i a b l e and a s s i g n i t t o t h e
J a v a S c r i p t v a r i a b l e ’ data ’ .
var data = <?php echo $ d a t a j s o n ; ? >;

// Get t h e 2D r e n d e r i n g c o n t e x t o f t h e canvas e l e m e n t with ID ’ myChart ’ .


var c t x = document . getElementById ( ’ myChart ’ ) . g e t C o n t e x t ( ’ 2 d ’ ) ;

// C r e a t e a new Chart i n s t a n c e with t h e 2D r e n d e r i n g c o n t e x t .


var myChart = new Chart ( ctx , {
// S e t t h e type o f c h a r t t o ’ l i n e ’ .
type : ’ l i n e ’ ,
// D e f i n e t h e data f o r t h e c h a r t .
data : {
// C r e a t e l a b e l s f o r t h e x−a x i s u s i n g t h e l e n g t h o f t h e
’ data ’ a r r a y .
l a b e l s : [ . . . Array ( data . l e n g t h ) . k e y s ( ) ] ,
// D e f i n e t h e d a t a s e t f o r t h e c h a r t .
datasets : [{
// S e t t h e l a b e l f o r t h e d a t a s e t .
l a b e l : ’ Your Data ’ ,

9
// P r o v i d e t h e a c t u a l data p o i n t s f o r t h e c h a r t .
data : data ,
// S e t t h e background c o l o r f o r t h e a r e a under t h e l i n e .
backgroundColor : ’ rgba ( 2 5 5 , 9 9 , 1 3 2 , 0 . 2 ) ’ ,
// S e t t h e c o l o r o f t h e l i n e .
b o r d e r C o l o r : ’ rgba ( 2 5 5 , 9 9 , 1 3 2 , 1 ) ’ ,
// S e t t h e width o f t h e l i n e .
borderWidth : 1
}]
},
// D e f i n e o p t i o n s f o r t h e c h a r t .
options : {
// C o n f i g u r e s c a l e s f o r t h e c h a r t .
scales : {
// C o n f i g u r e t h e y−a x i s .
yAxes : [ {
// C o n f i g u r e t i c k s on t h e y−a x i s .
ticks : {
// S t a r t t h e y−a x i s s c a l e from z e r o .
beginAtZero : t r u e
}
}]
}
}
});
</ s c r i p t >

12 Creating a Plot using Plotly from a MySQL Database


12.1 Setup your Environment

<s c r i p t src=” h t t p s : / / cdn . p l o t . l y / p l o t l y −l a t e s t . min . j s ”></ s c r i p t>

12.2 Fetch Data from MySQL Database

f e t c h ( ’ y o u r p h p f i l e . php ’ )
. then ( r e s p o n s e => r e s p o n s e . j s o n ( ) )
. then ( data => {
// P r o c e s s data h e r e
})
. c a t c h ( e r r o r => c o n s o l e . e r r o r ( ’ E r r o r f e t c h i n g data : ’ , e r r o r ) ) ;

12.3 Process Data


To create a plot using Plotly, you need to process the data retrieved from the MySQL database.
// Assuming data i s an a r r a y o f o b j e c t s f e t c h e d from t h e d a t a b a s e
// Example : [ { c a t e g o r y : ’ Category 1 ’ , v a l u e : 2 0 } ,
{ c a t e g o r y : ’ Category 2 ’ , v a l u e : 1 4 } , . . . ]
var xData = data . map( e n t r y => e n t r y . c a t e g o r y ) ;

10
var yData = data . map( e n t r y => e n t r y . v a l u e ) ;
Below are some examples of how you can process the data:

• Basic Transformation: If your data consists of categories and corresponding values, you might need
to separate them into arrays for x-axis (categories) and y-axis (values).

var xData = data.map(entry => entry.category);


var yData = data.map(entry => entry.value);

• Aggregating Data: You might need to aggregate data if it’s grouped by certain criteria. For instance,
if you have sales data grouped by month, you may want to calculate the total sales for each month.

var monthlySales = {};

data.forEach(entry => {
if (!monthlySales[entry.month]) {
monthlySales[entry.month] = 0;
}
monthlySales[entry.month] += entry.sales;
});

var xData = Object.keys(monthlySales);


var yData = Object.values(monthlySales);

• Data Transformation for Different Chart Types: Depending on the chart type you’re creating,
you might need to process data differently. For instance, for a scatter plot, you may need x and y
coordinates.

var xData = data.map(entry => entry.x);


var yData = data.map(entry => entry.y);

• Data Formatting: Sometimes, data might need formatting before plotting. For instance, if you have
date-time data, you might need to convert it to a suitable format.

var xData = data.map(entry => new Date(entry.date));


var yData = data.map(entry => entry.value);

12.4 Create the Plot using Plotly

var t r a c e = {
x : xData ,
y : yData ,
type : ’ bar ’
};

var l a y o u t = {
t i t l e : ’ Your P l o t T i t l e ’ ,

11
x a x i s : { t i t l e : ’X−a x i s Label ’ } ,
y a x i s : { t i t l e : ’Y−a x i s Label ’ }
};

P l o t l y . newPlot ( ’ y o u r d i v i d ’ , [ t r a c e ] , l a y o u t ) ;

12.5 Display the Plot

<div id=” y o u r d i v i d ”></ div>

12

You might also like