CSE 154

Lecture 14: GET and POST

GET and POST

  • GET requests are intended to retrieve information from the server and not change anything.
  • POST requests are intended to send information to the server, possibly changing information on the server.

Sending parameters in Ajax fetch

  • For GET requests, add them to the end of the url: '?param1=value1&param2=value2'
  • For POST requests, create a new FormData() and then use append(key, value) to add key, value pairs. Then include it in the fetch body.

Ajax GET Code Skeleton

//assume checkStatus() already included (https://courses.cs.washington.edu/courses/cse154/17au/lecture/AjaxCheckStatusHelper.js)

function callAjax(){
    let url = ..... // put url string here

    url += "?";
    url += "age=83";
    url += '&';
    url += "height=really tall";

    //fetch by default is a GET request
    fetch(url, {credentials: "include"}) // include credentials for cloud9
       .then(checkStatus)
       .then(function(responseText) {
            //success: do something with the responseText
        })
       .catch(function(error) {
           //error: do something with error
       });
}

Ajax POST Code Skeleton

//assume checkStatus() already included (https://courses.cs.washington.edu/courses/cse154/17au/lecture/AjaxCheckStatusHelper.js)

function callAjax(){
    let url = ..... // put url string here

    let data =  new FormData();
    data.append("age", 83);
    data.append("height", 'really tall');

    fetch(url, {method: "POST", body: data, credentials: "include"}) // include credentials for cloud9
       .then(checkStatus)
       .then(function(responseText) {
            //success: do something with the responseText
        })
       .catch(function(error) {
           //error: do something with error
       });
}

Query Parameters in PHP

  • PHP includes built in arrays to hold GET and POST parameters called $_GET and $_POST
  • To access the POST parameter age, reference it in PHP as $_POST["age"]

Example of GET in PHP

For a GET url with paramters passed, like:
url.com/path?username=kyle&id=53&meat=true

PHP Code:

$user_name = $_GET["username"];
$id_number = (int) $_GET["id"];
$eats_meat = FALSE;

if (isset($_GET["meat"])) { #check if the parameter is set (exists)
    $eats_meat = TRUE;
} 

Example of POST in PHP

For a POST to url with paramters passed, like:

let url = ..... // put url string here
let data =  new FormData();
data.append("username", 'Kyle');
data.append("password", 'very secret password!');

fetch(url, {method: "POST", body: data, credentials: "include"}) 
...

PHP Code:

$username = $_POST["username"];
$password = $_POST["password"];
$users_pw_hash = db_lookup_hashed_pw($username);

if (password_hash($password) == $users_pw_hash) {
    print("Successfully logged in!");
}