Logo

dev-resources.site

for different kinds of informations.

Some uncommon Ajax techniques that most people don't know

Published at
3/11/2024
Categories
webdev
javascript
programming
ajax
Author
wangliwen
Author
9 person written this
wangliwen
open
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.

ajax Article's
30 articles in total
Favicon
How to Load More data using ajax pagination on scroll in laravel 11 Example
Favicon
Ajax: Revolutionizing Web Interaction - A Comprehensive Guide
Favicon
How to create ajax How to create ajax dependent dropdown in laravel 11
Favicon
A Comprehensive Guide with XHR, Fetch API, Axios and jQuery AJAX
Favicon
Vaadin, the battery-included server-side AJAX framework
Favicon
Augmenting the client with Alpine.js
Favicon
Augmenting the client with Vue.js
Favicon
A short history of AJAX and SSR
Favicon
Experimenting with AJAX and APIs: A Comprehensive Guide for Beginners
Favicon
Asynchronous Requests in JavaScript: AJAX, JQUERY, FETCH and AXIOS.
Favicon
JS: Geek Out with AJAX
Favicon
Exploring django-ajax: Simplifying AJAX Integration in Django
Favicon
Exploring The Power Of AJAX Flex In Web Development
Favicon
Laravel 11 Ajax Form Submit With Validation
Favicon
com.girl.brashcrab
Favicon
Some uncommon Ajax techniques that most people don't know
Favicon
A Simple Guide to Developing AJAX-Driven Plugins for WordPress
Favicon
Do you know AJAX?
Favicon
419 Page expired Laravel 10|9 postman, Ajax Post, Form Submit Login
Favicon
crud operation using ajax in laravel 10 with popup modal
Favicon
How do I get my text to connect to the ajax call I am trying to connect from the ajax call to the controller?
Favicon
Trending Tech: HTMX
Favicon
Send Form Data With Ajax
Favicon
Dependent Country State City Dropdown using jQuery Ajax in Laravel 10
Favicon
What is AJAX in JavaScript ?
Favicon
Laravel 10 Ajax Crop and Upload Image using Croppie js
Favicon
Laravel 10 Ajax CRUD with Image Upload Tutorial
Favicon
Tab Content Structure with Ajax and PHP
Favicon
Create a mini facebook clone in laravel and ajax
Favicon
How To Cancel an AJAX Request in JavaScript Using the AbortController

Featured ones: