Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
153 changes: 153 additions & 0 deletions 3 JavaScript/docs/13 - Vue Basics.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
# Vue

Vue is a JavaScript framework for building user interfaces. Vue is a MVVM framework (Model View View-model). This is a fancy
way of saying that you give Vue a JavaScript object that represents the state (or data, or model) of your application and a
template (or view) of the visual representation of your data. Vue provides a view-model that binds your data to your template
and syncs them to each other instantly as both update. This means that as the user updates the values of elements on the page
they are instantly reflected in the data object, and as you update the data object with event listeners or other methods the
webpage template is instantly re-rendered with the new data. This removes the need to do manual DOM manipluation, making it
easy to write more complicated user interfaces and interactive web pages.

For more information about JavaScript frameworks and why to use them, go [here](https://www.academind.com/learn/javascript/jquery-future-angular-react-vue/).

More detailed explanations and code examples can be found in the Vue guide [here](https://vuejs.org/v2/guide/).

A YouTube series on Vue basics can be found [here](https://www.youtube.com/watch?v=5LYrN_cAJoA&list=PL4cUxeGkcC9gQcYgjhBoeQH7wiAyZNrYa) and the solution repo [here](https://github.com/iamshaunjp/vuejs-playlist/tree/lesson-1).

## Installing

Vue can be run from a CLI tool and it's own project like Django, but in class we will be running Vue from a CDN, loaded
in with a `script` tag. This means we can add Vue to an existing HTML page and add Vue functionality and features
at our own page, on top of our existing front-end knowledge.

`<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>`

Also highly recommended:
* [Vuetur syntax highlighting and snippits for VS Code](https://marketplace.visualstudio.com/items?itemName=octref.vetur)
* [Vue devtools for Chrome/Firefox/etc](https://github.com/vuejs/vue-devtools)

## Declarative Rendering

```
<div id="app">
{{ message }}
</div>
```

```
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
}
})
```

Looks a lot like Django, doesn't it? We instantiate a `new` Vue instance, and pass it a configuration object. `el` represents
the CSS selector of the element to create our Vue app inside. `data` is our model or state, kind of like the context in Django.
When the value of `message` changes, our page will automatically change to match.

We can also use a *directive* called `v-bind` to bind attribute values to Vue's data model.

```
<div id="app-2">
<span v-bind:title="message">
Hover your mouse over me for a few seconds
to see my dynamically bound title!
</span>
</div>
```

```
var app2 = new Vue({
el: '#app-2',
data: {
message: 'You loaded this page on ' + new Date().toLocaleString()
}
})
```

## Loops and Conditionals

```
<div id="app-3">
<span v-if="seen">Now you see me</span>
</div>
```

```
var app3 = new Vue({
el: '#app-3',
data: {
seen: true
}
})
```

```
<div id="app-4">
<ol>
<li v-for="todo in todos">
{{ todo.text }}
</li>
</ol>
</div>
```

```
var app4 = new Vue({
el: '#app-4',
data: {
todos: [
{ text: 'Learn JavaScript' },
{ text: 'Learn Vue' },
{ text: 'Build something awesome' }
]
}
})
```

Again, this should feel familiar. Instead of using template tags, we're using *directives* that look like HTML attributes.
Note that unlike with templte tags, the directives go directly on the HTML elements.

## Events and Input

```
<div id="app-5">
<p>{{ message }}</p>
<button v-on:click="reverseMessage">Reverse Message</button>
</div>
```

```
var app5 = new Vue({
el: '#app-5',
data: {
message: 'Hello Vue.js!'
},
methods: {
reverseMessage: function () {
this.message = this.message.split('').reverse().join('')
}
}
})
```

We can also give Vue as many *methods* as we want, which we can call in our template with the `v-on:<event_name>` directive.
Finally, we can use the `v-model` directive to bind the value of an input element to our data model.

```
<div id="app-6">
<p>{{ message }}</p>
<input v-model="message">
</div>
```

```
var app6 = new Vue({
el: '#app-6',
data: {
message: 'Hello Vue!'
}
})
```
180 changes: 180 additions & 0 deletions 3 JavaScript/docs/14 - Ajax.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@

# AJAX

AJAX stands for "asynchronous javascript and XML", and allows you to execute HTTP requests from JavaScript. You can read more about AJAX [here](https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started), [here](https://developer.mozilla.org/en-US/docs/AJAX) and [here](https://www.w3schools.com/xml/ajax_intro.asp).


- [AJAX in Axios](#ajax-in-axios)
- [Setting Query Parameters](#setting-query-parameters)
- [Setting Custom Request Headers](#setting-custom-request-headers)
- [Sending Data](#sending-data)
- [AJAX in Vanilla JavaScript](#ajax-in-vanilla-javascript)
- [AJAX in jQuery](#ajax-in-jquery)
- [CORS](#cors)
- [JSONP](#jsonp)



## AJAX in Axios

[Axios](https://github.com/axios/axios) is a JavaScript library which handles AJAX more succinctly. Ultimately it's built upon vanilla JavaScript, so it doesn't offer anything you can't otherwise do with vanilla JS.

```es6
axios({
method: 'get',
url: 'https://favqs.com/api/qotd'
}).then((response) => {
console.log(response.data)
})
```

### Setting Query Parameters

You can set query parameters using string concatenation or by setting the `params` property. Just remember that if you use string concatenation, you may have to use `encodeURIComponent` if the value has special characters in it. If you use `params` with Axios, it will automatically encode your parameters for you.

```javascript
let business_name = 'Schmitt & Associates'
let url1 = "http://example.com/?business=" + business_name
let url2 = "http://example.com/?business=" + encodeURIComponent(business_name)
console.log(url1) // INVALID: http://example.com/?business=Schmitt & Associates
console.log(url2) // VALID: http://example.com/?business=Schmitt%20%26%20Associates
```

The code below sends the request to `https://opentdb.com/api.php?amount=10&category=18&difficulty=easy`

```javascript
axios({
method: 'get',
url: 'https://opentdb.com/api.php',
params: {
amount: 10,
category: 18,
difficulty: 'easy'
}
}).then((response) => {
this.questions = response.data.results
})
```

### Setting Custom Request Headers

Depending on the API specification, you may need to put an API key inside the headers of the request.

```javascript
axios({
method: 'get',
url: 'https://favqs.com/api/qotd',
headers: {
'x-api-key': 'api_key'
}
}).then((response) => {
console.log(response.data)
})
```

### Sending Data

```javascript
axios({
method: 'post',
url: 'https://favqs.com/api/qotd',
data: {
name: 'joe',
age: '34'
}
}).then((response) => {
console.log(response.data)
})
```

## AJAX in Vanilla JavaScript

Here's how to execute an AJAX request in native JavaScript. You can read more about XMLHttpRequest [here](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest). If you have many query parameters, consider using a function to [convert an object](https://stackoverflow.com/questions/111529/how-to-create-query-parameters-in-javascript). Remember status 200 means 'success'.

```javascript
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
console.log(this.responseText);
}
};
xhttp.open("GET", 'https://api.iify.org/?format=json');
xhttp.send();
```

The possible values for `readyState` are shown below, you can find more info [here](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState)
- 0 UNSENT: the request has not yet been sent
- 1 OPENED: the connection has been opened
- 2 HEADERS_RECEIVED: the response headers have been received
- 3 LOADING: the response body is loading
- 4 DONE: the request has been completed


Adding a key-value pair to the request header is done by invoking `setRequestHeader` when the connection is open.

```javascript
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 1) {
xhttp.setRequestHeader('Authorization', 'Token token="a1b2c3"')
} else if (this.readyState === 4 && this.status === 200) {
let data = JSON.parse(xhttp.responseText);
// do something with data
} else if (this.readyState === 4 && this.status === 404) {
// handle 404
}
};
xhttp.open("GET", url);
xhttp.send();
```


It's possible to hide the messiness inside a function by passing a callback function.

```javascript
function http_get(url, success) {
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
let data = JSON.parse(xhttp.responseText);
success(data);
}
};
xhttp.open("GET", url);
xhttp.send();
}

http_get("https://api.ipify.org/?format=json", function(data) {
console.log(data);
});
```


## AJAX in jQuery

```javascript
$.ajax({
method: "GET", // specify the HTTP Verb
url: 'https://api.iify.org/?format=json' // specify the URL
}).done(function(data) {
console.log(data); // log the data we get in response
}).fail(function() {
alert("error"); // indicate that an error has occurred
});
```





## CORS

CORS stands for 'cross-origin resources sharing', and represents a relaxation of the [same origin policy](https://en.wikipedia.org/wiki/Same-origin_policy). You can read more about CORS on the [MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS).

If you receive the response "No 'Access-Control-Allow-Origin' header is present on the requested resource", it's because the remote server you're sending to the request from has security controls in place that prevent access from a client. You can read more about CORS [here](https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe) and [here](https://security.stackexchange.com/questions/108835/how-does-cors-prevent-xss).


## JSONP

JSONP (short for "JSON with Padding") is an additional security feature some APIs offer or require. You can read more about JSONP [here](https://stackoverflow.com/questions/3839966/can-anyone-explain-what-jsonp-is-in-layman-terms) and [here](https://stackoverflow.com/questions/16097763/jsonp-callback-function).

Loading