DEV Community

WangLiwen
WangLiwen

Posted on

Some uncommon Ajax techniques that most people don't know

Here are some uncommon but useful Ajax techniques, along with example code snippets:

1. Utilizing the fetch API Instead of XMLHttpRequest

The fetch API is a modern, Promise-based approach for making network requests. It's cleaner and easier to use compared to XMLHttpRequest.

Example:

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error('Error:', error);
  });
Enter fullscreen mode Exit fullscreen mode

2. Canceling Requests with AbortController

If you need to cancel an ongoing Ajax request, AbortController can be used.

Example:

const controller = new AbortController();
const signal = controller.signal;

fetch('https://api.example.com/data', { signal })
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    if (error.name === 'AbortError') {
      console.log('Fetch aborted');
    } else {
      console.error('Error:', error);
    }
  });

// Cancel the request under certain conditions
controller.abort();
Enter fullscreen mode Exit fullscreen mode

3. Handling Binary Data with Blob and URL.createObjectURL

When dealing with binary data like images or files, Blob and URL.createObjectURL can be used to display them.

Example:

fetch('https://example.com/image.jpg')
  .then(response => response.blob())
  .then(blob => {
    const url = URL.createObjectURL(blob);
    const img = document.createElement('img');
    img.src = url;
    document.body.appendChild(img);
  })
  .catch(error => {
    console.error('Error:', error);
  });
Enter fullscreen mode Exit fullscreen mode

4. Sending Form Data or Uploading Files with FormData

FormData objects are useful when sending form data or uploading files.

Example:

const formData = new FormData();
formData.append('username', 'john_doe');
formData.append('avatar', fileInput.files[0]); // Assuming fileInput is a file input element

fetch('https://api.example.com/upload', {
  method: 'POST',
  body: formData
})
.then(response => response.json())
.then(data => {
  console.log(data);
})
.catch(error => {
  console.error('Error:', error);
});
Enter fullscreen mode Exit fullscreen mode

5. Customizing Request Headers

Sometimes, servers require specific headers to properly process requests. You can customize these headers through Ajax.

Example:

fetch('https://api.example.com/data', {
  headers: {
    'Custom-Header': 'CustomValue',
    'Content-Type': 'application/json'
  }
})
.then(response => response.json())
.then(data => {
  console.log(data);
})
.catch(error => {
  console.error('Error:', error);
});
Enter fullscreen mode Exit fullscreen mode

6. Monitoring Request Progress

For large file uploads or downloads, listening to progress events can be useful.

Example (using XMLHttpRequest since fetch doesn't directly support progress events):

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/largefile', true);

xhr.onprogress = function(e) {
  if (e.lengthComputable) {
    const percentComplete = (e.loaded / e.total) * 100;
    console.log(percentComplete + '% downloaded');
  }
};

xhr.onload = function() {
  if (this.status === 200) {
    console.log(this.responseText);
  }
};

xhr.send();
Enter fullscreen mode Exit fullscreen mode

These techniques provide greater and finer control over Ajax, enabling you to solve complex problems and create more robust applications.

Top comments (0)