Back

Sending and retrieving files

I can use AJAX when:

This makes it very difficult to use AJAX if I'm running the files locally, as I tend to do when I work on projects. File urls won't be regarded as living on the same server and so accessing local files this way won't be possible in most modern browsers.

The first solution to this is to run a simple local server.

An alternative is to use JSONP, but I think I should avoid it.

Generally, it makes sense to use AJAX to access another page in response to something the user does. In the case of excel.php, nothing the user does will impact the content that is loaded, so it is better to use PHP to load all the data before the page is returned to the client.

However, in such a case where I want to produce an animation based on live data, like the realtime position of satellites, AJAX is the way to go.

Accessing data from a file

bare minimum for an ajax http request

let xhr = new XMLHttpRequest();
xhr.open('GET', URL, true);
xhr.send();

You can check the network tab in the developper tools and you'll see the requests.

Retrieving file content from a url

Sending data or files to a url using AJAX

sending data to a php page generally i know of the following ways

anything you send, either via GET or via POST, is sent as a string.

sending data using FormData()

this is just like hitting submit on a form

  var formData = new FormData();
  formData.append('key', 'value'); 
  formData.append('file', e.dataTransfer.files[0]); // apppends as a binary string?
  let xhr = new XMLHttpRequest();
  xhr.open('POST', URL, true);
  xhr.send(formData);

In the first appended key, if you send the formData to a php page, you can see the send data using $_POST. You might do echo print_r($_POST); or something to that effect.

The second wont show up that way because it's a file. imagine you're sending a file you collected thru drag/drop. but you can do print_r($_FILES); and that will show the file itself. Now it's on the php page and you can work with it there. you might want to validate it or something.

so in fact, you dont even have to send formData, you can send your own object.

Sending a Javascript object to a PHP page via AJAX

Lets say you have an object, like obj = {a: 1, b: 2} and you want to send it to a php page, file_name.php

a minimal example. on the js side :

  let url = 'file_name.php';
  let obj = {
   'a': 1,
   'b': 2
  }
  let xhr = new XMLHttpRequest();
  
  xhr.open('POST', url, true);
  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xhr.send(JSON.stringify(obj));

on the php side, inside file_name.php :

  // THIS COLLECTS EVERYTHING THAT HITS THE PAGE. IN THIS CASE, A STRINGIFIED JSON OBJECT 
  $x = file_get_contents("php://input"); 
  
  // CONVERT THE STRINGIFIED JSON OBJECT INTO A PHP ASSOCIATIVE ARRAY 
  $y = json_decode($x, true);
  
  // NOW WE CAN USE OUR OBJECT LIKE NORMAL 
  $a = $y["a"];
  $b = $y["b"];
Minimal + waiting for a response

This version is similar except I'm also setting up the xhr event listener to wait for the response.

We can check that the object was sent and recovered successfully.

  let url = 'file_name.php';
  let obj = {
   'a': 1,
   'b': 2
  }

  let xhr = new XMLHttpRequest();
  
  // THIS BLOCK WAITS FOR A RESPONSE 
  xhr.onreadystatechange = function() {
    if (this.readyState === 4 && this.status === 200) {

      // THE PHP PAGE WILL RETURN A STRINGIFIED ARRAY OF JS OBJECTS. WE NEED TO PARSE IT
      let arr = JSON.parse(this.responseText);
      console.log(arr);
    }
  };
  
  xhr.open('POST', url, true);
  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xhr.send(JSON.stringify(obj));

on the php side, inside file_name.php :


  $x = file_get_contents("php://input"); 
  $y = json_decode($x, true);
  
  // NOW WE CAN USE OUR OBJECT LIKE NORMAL 
  $a = $y["a"];
  $b = $y["b"];
  
  // THIS PAGE WILL RETURN A STRINGIFIED ARRAY OF JS OBJECTS 
  echo '[{"a":0,"b":0},{"a":0,"b":0}]'; 
Comments

everything gets sent and received as a string. so what we send needs to be parsed into a string, or from a string.

php has echo and print_r().

  $x = file_get_contents("php://input"); 
  $y = json_decode($x, true);

  echo "PRINT POST : \r\n \r\n";
  print_r($_POST);

  echo "\r\n";

  echo "PRINT PAGE INPUT : \r\n \r\n";
  $x = file_get_contents("php://input");
  print_r($x);

  echo "\r\n \r\n";

  echo "PRINT AS PHP ASSOCIATIVE ARRAY : \r\n \r\n";
  $y = json_decode($x, true);
  print_r($y);

Here's a button that executes the code above

Check out the console and hit the button. You'll see what it looks like.

VOMIT NOTES CONCERNING THE ABOVE

It seems like file_get_contents("php://input"); captures everything that hits the page.

That's why $x = file_get_contents("php://input"); worked whether I used application/json or application/x-www-form-urlencoded.

Is there something about application/json and $_POST that's not compatible?

***

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send

the link above has a good thing on how to send a file, use a bufferarray

https://www.youtube.com/watch?v=mNrJDGfQGz0

the reason content type application/json didnt work i think has to do with how i understand or not the php superglobal $_POST

sending data of your own construction but modelled after an html form

To POST data like an HTML form, add an HTTP header with setRequestHeader(). Specify the data you want to send in the send() method:

Example
xhttp.open("POST", "demo_post2.asp", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Henry&lname=Ford");