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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay