JavaScript Notes

02/28/2024

This post is going to be like my PHP Notes page. I will be adding to it periodically. If you have any comments or suggestions, don't hesitate to email me.

Content

  1. New Page
  2. Ajax
  3. New Tab Links
  4. URL Parameters
  5. Checked Radio Input Value
  6. String Literals

New page

To send the browser to a different page

window.location.href = "http://example.com/";

Ajax

Sending a request

XMLHttpRequest

function completeAllListItems() {
  var xhttp = new XMLHttpRequest();

  xhttp.onreadystatechange = function() {
   if (this.readyState == 4 && this.status == 200) {
  	 var e = this.responseText;
  	 $("#todo-list-section").html(e);    // html section where the updated content is placed
   }
  };

  var listID = $("#todo-list-card").attr("data-listid");
  var link = 'complete-all-list-items.php?listID=' + listID;

  xhttp.open("GET", link, true);
  xhttp.send();
}

jQuery

$.ajax({
  type: "GET",
  url: 'get-data.php',
  data: {
    "id": 1,
    "name": "John"
  },
  success: function(response) {
    loadData(response);   // function
  }
});
.get() & .post()

The .get() and .post() functions have the same parameters: $.get(url, data, success(response)). Remember the data variable should be in JSON format.

var data = {
  id: 14,
  name: 'Ryan',
}

$.get('example-server.php', data, function(response) {
  console.log(JSON.parse(response));
});

Receiving the response

Once the php file receives the request from the file, it may sometimes return only data in a JSON format. If so, this is how you would parse the data returned by the php file:

var returnData = JSON.parse(response);

To make links open in a new tab using JavaScript, use the following code:

$("a").attr("target", "_blank");

URL Parameters

When using JavaScript, one can get the values of a URL by creating a URLSearchParams object. More info can be found here.

For example, suppose the url is the following: example.com?name=ryan&age=24. To get the values of name and age, do the following:

var queryString = window.location.search;
var urlParams = new URLSearchParams(queryString);
var name = urlParams.get('name');                   // name
var age = urlParams.get('age');                     // age

Checked Radio Input Value

To do this, we are going to use jQuery's :checked selector. The :checked selector only words for checkboxes, radio buttons, and options of select elements.

To get the value of a checked radio button with a name of radio-input you can do:

var radioInputValue = $('input[name="radio-input"]:checked').val();

String Literals

String literals are an easy way to generate an html element with JavaScript variables. You can read more about it from this article.

To use a string literal, you can do the following:

const some_html = `
  <div class="module">
    <h2>${data.title}</h2>
    <p>${data.content}</p>
  </div>`;

© 2024 by Ryan Rickgauer