Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

The Client JavaScript

Here is a JavaScript example on the client-side, making an AJAX request to fetch the PHP file from the previous example:

Example

Use JSON.parse() to transform the result into a JavaScript object.

const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  const myObj = JSON.parse(this.responseText);
  document.getElementById(“demo”).innerHTML = myObj.name;
}
xmlhttp.open(“GET”“demo_file.php”);
xmlhttp.send();

PHP Array

When using the PHP function json_encode(), arrays in PHP are also converted into JSON.

PHP file

<?php
$myArr = array(“John”“Mary”“Peter”“Sally”);

$myJSON = json_encode($myArr);

echo $myJSON;
?>

The Client JavaScript

Here is a JavaScript example on the client-side, making an AJAX request to retrieve the PHP file from the array example mentioned above.

Example

Use JSON.parse() to convert the result into a JavaScript array.

var xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  const myObj = JSON.parse(this.responseText);
  document.getElementById(“demo”).innerHTML = myObj[2];
}
xmlhttp.open(“GET”“demo_file_array.php”true);
xmlhttp.send();