Log In Sign Up
HomeDocsUtilitiesAjax Request

Ajax Request

Category: Utilities
Ajax is a fundamental method for asynchronous data retrieval in frontend development. While similar to jQuery's $.ajax in usage, OrcaUI's implementation has unique characteristics: supports automatic ...

Preface

Asynchronous operations are one of the most important concepts in JavaScript. Using AJAX to fetch same-origin content and validate results are common operations in project development. This framework has its own AJAX implementation.

The framework's AJAX approach doesn't aim to be all-encompassing, but rather continuously improves during framework development.

Key points about this utility function:

  • By default sends data in application/x-www-form-urlencoded format (URL-encoded form data)
  • Automatically detects if data is in FormData format (for file uploads) - in this case sends raw without processing (PHP pages can access files via $_FILES)
  • To send data as JSON, specify contType as application/json (data will be converted using JSON.stringify())
  • If data is string format, it must follow name=LiLei&age=16 query string format
  • Returns a Promise object that can use then() method for chaining

Full syntax: orca.ajax(option).then(resolve,reject); Simplified syntax:orca.ajax(option)

Parameters

Parameter Type Default Description
target Same as getEl first param - Target DOM node for content injection, executes default event behavior
url string - URL endpoint for async content
type 'post'/'get' 'post' HTTP request method
async boolean true Whether to make async request (set false for synchronous)
data object null Request payload data (object format)
holdTime number (positive) 0 Delay before execution in ms (0=immediate)
stopTime number (positive) 3600000 Request timeout threshold in ms
contType 'application/x-www-form-urlencoded'/
'application/json'/'text/xml'
'application/x-www-form-urlencoded' Content-Type header
headers object - Additional request headers (extends contType)
respType ''/'text'/'json'/'blob'/'arraybuffer'/'document' '' Expected response data type
catchable boolean false Whether to catch Promise rejections
spinStr string '' Loading indicator HTML
spinSel Same as getEl first param - Node(s) to show loading state
xhrName string - If set, assigns XMLHttpRequest instance to this.xhrName
repeat object - Retry configuration
repeat.index 0~9 0 Retry index position (0-9)
repeat.max number (positive) 0 Maximum retry attempts
repeat.keyword string - Retry trigger keyword (searches error response)
cb function null Callback that executes for all outcomes (success/error/timeout)
xhrFields object null Additional XHR configuration fields
abort function null Abort request callback
error function null Error handler callback
opened function null Pre-request callback (after XHR creation)
before function null Pre-success callback
success function null Success handler callback
uploading function null Upload progress callback
downloading function null Download progress callback
complete function null Upload/download completion callback
timeout function null Timeout handler callback

Common events in execution order:

  1. opened - When request is created but not yet sent (readyState === 1)
  2. before - Before response is received (readyState < 4)
  3. success/error - When response is received (readyState === 4)
  4. timeout - When request times out (asynchronous)
  5. abort - When manually aborted (asynchronous, must be in opened event)

All the above events support the resp parameter, which is an object containing the following properties:

Property Type Default Description
content string/json/array - Retrieved content
status number - Status code (200 indicates success)
target HTMLElement - Target element for content display
label HTMLElement - Dynamic indicator element (e.g. ax-spin label)
xhr XMLHttpRequest - Current XMLHttpRequest instance
abort function - Executable abort method (only in opened event)

For uploading and downloading events, the resp parameter has different properties:

Property Type Default Description
current number - Downloaded bytes
total number - Total file size in bytes
ratio number - Download ratio (current / total)
percent number - Percentage (ratio*100 rounded)
result string - Progress string with % (percent+'%')
status number - Status code (200 indicates success)
target HTMLElement - Target element for content display
label HTMLElement - Dynamic indicator element (e.g. ax-spin label)
xhr XMLHttpRequest - Current XMLHttpRequest instance
abort function - Executable abort method

Basic Usage

The url parameter is required for all requests. The target parameter specifies where to inject the response content.

  • Output
  • HTML
  • JS
  •                 
                    
                
  •                 
                    let btnPage = document.querySelector('#btnPage'),
                        ajaxPage =  document.querySelector('#ajaxPage');
                    btnPage.onclick = function () {
                        orca.ajax({
                            target:ajaxPage,
                            url: 'https://req.orcaui.com/v1/html/v1_en_earth_01.html',
                        });
                    }
                    
                

Custom Events

While plain text responses may not need processing, most responses require data transformation in the success callback.

  • Output
  • HTML
  • JS
  •                 
                    
                
  •                 
                    let btnEvent = document.querySelector('#btnEvent'),
                        ajaxEvent =  document.querySelector('#ajaxEvent');
                    btnEvent.onclick = function () {
                        orca.ajax({
                            target:ajaxEvent,
                            url: 'https://req.orcaui.com/v1/html/v1_en_earth_01.html',
                            success: function (resp) {
                                // Use setTimeout to simulate loading delay effect
                                setTimeout(function () {
                                    ajaxEvent.innerHTML = 'Success! Please open F12 and check the console.';
                                    console.log(resp)
                                }, 3000);
                            },
                        });
                    }
                    
                

Partial Content

To fetch specific element content instead of entire page:

  1. Append #ID to the URL
  2. Or pass element selector as data parameter
  • Output
  • HTML
  • JS
  •                 
                    
                
  •                 
                    let btnPart01 = document.querySelector('#btnPart01'),
                        btnPart02 = document.querySelector('#btnPart02'),
                        ajaxPart =  document.querySelector('#ajaxPart');
                    btnPart01.onclick = function () {
                        orca.ajax({
                            target:ajaxPart,
                            url: 'https://req.orcaui.com/v1/html/v1_en_earth_01.html#post01',
                        });
                    }
                    btnPart02.onclick = function () {
                        orca.ajax({
                            target:ajaxPart,
                            url: 'https://req.orcaui.com/v1/html/v1_en_earth_01.html',
                            data:'#post02',
                        });
                    }
                    
                

JSON Requests

Fetch JSON files and process responses using for...in iteration.

  • Output
  • HTML
  • JS
  •                 
                    
                
  •                 
                    let btnJson = document.querySelector('#btnJson'),
                        ajaxJson =  document.querySelector('#ajaxJson');
                    btnJson.onclick = function () {
                        orca.ajax({
                            target:ajaxJson,
                            url: 'https://req.orcaui.com/v1/json/orca.json',
                            success: function (resp) {
                                // Reassemble content
                                let html = '
      '; for(let k in resp.content){ html+='
    • '+k+':'+resp.content[k]+'
    • '; } html+='
    '; // Use setTimeout to simulate loading delay effect setTimeout(function () { ajaxJson.innerHTML = html; }, 3000); }, }) }

Custom Loading Indicators

Override default spinner by setting spinStr parameter with custom HTML.

  • Output
  • HTML
  • JS
  •                 
                    
                
  •                 
                    let btnBefore = document.querySelector('#btnBefore'),
                        ajaxBefore =  document.querySelector('#ajaxBefore');
                    btnBefore.onclick = function () {
                        orca.ajax({
                            target: ajaxBefore,
                            url: 'https://req.orcaui.com/v1/json/orca.json',
                            spinStr: 'Loading, please wait...',
                            success: function (resp) {
                                // Reassemble content
                                let html = '
      '; for(let k in resp.content){ html+='
    • '+k+':'+resp.content[k]+'
    • '; } html+='
    '; // Simulate loading wait effect using setTimeout setTimeout(function () { ajaxBefore.innerHTML = html; }, 3000); }, }) }

URL Errors

When a URL doesn't exist or is invalid, it triggers the error event. If you anticipate request failures, you can use the abort method to cancel the request prematurely. There are two approaches to abort requests:

  1. Get the XHR instance through the opened event (which fires before any other events including before, error, abort, etc.) and use the native abort() method to cancel the request
  2. Directly execute the abort method through parameters in the before event (the before event parameters include an abort method)
  • Output
  • HTML
  • JS
  •                 
                    
                
  •                 
                    let btnError = document.querySelector('#btnError'),
                        btnAbort = document.querySelector('#btnAbort'),
                        btnAbort2 = document.querySelector('#btnAbort2'),
                        ajaxError = document.querySelector('#ajaxError'),
                        xhr;
                    btnError.onclick = function() {
                        orca.ajax({
                            target: ajaxError,
                            url: 'https://xxxx.com/xxx.html',
                            opened: (resp) => {
                                xhr = resp.xhr; // Store XHR instance for later abort
                            },
                            abort: (el) => {
                                // Triggered when abort event is detected
                                el.innerHTML = 'Request aborted via before hook!';
                            },
                            before: (resp) => {
                                // resp.content contains default loader text
                                resp.label.innerHTML = resp.content;
                                btnAbort2.onclick = () => {
                                    // Abort request within before hook
                                    resp.abort();
                                }
                            },
                            error: (resp) => {
                                resp.target.innerHTML = 'Request failed!';
                            },
                        })
                    }
                    btnAbort.onclick = () => {
                        // Cancel request using native abort
                        xhr && xhr.abort();
                        ajaxError.innerHTML = 'Request canceled via native abort()!';
                    }
                    
                

Request Timeout

The stopTime parameter sets the timeout threshold (in milliseconds). For larger file requests, increase this value accordingly.

  • Output
  • HTML
  • JS
  •                 
                    
                
  •                 
                    let btnTimeout = document.querySelector('#btnTimeout'),
                        ajaxTimeout = document.querySelector('#ajaxTimeout');
                    btnTimeout.onclick = function() {
                        orca.ajax({
                            target: ajaxTimeout,
                            url: 'https://xxxx.com/xxx.html',
                            // Intentionally small value for testing
                            stopTime: 500,
                            timeout: (resp) => {
                                resp.target.innerHTML = 'Request timed out!';
                            },
                        })
                    }
                    
                

Associated Loading Indicators

The target parameter specifies the destination element for content injection. Additionally, when loading content asynchronously into the target, you often need to indicate this state in related elements. The spinSel parameter serves as a selector for these associated indicator elements, accepting either single or multiple nodes (with syntax identical to the first parameter of allToEls).

  • Output
  • HTML
  • JS
  • CSS
  • Spinning 01 Spinning 02
  •                 
                    
                
  •                 
                    let btnSel = document.querySelector('#btnSel'),
                        ajaxSel =  document.querySelector('#ajaxSel');
                    btnSel.onclick = function () {
                        orca.ajax({
                            target: ajaxSel,
                            url: 'https://req.orcaui.com/v1/html/v1_en_earth_01.html',
                            spinSel:'#sel01,#sel02',
                            success: function (resp) {
                                ajaxSel.innerHTML = 'Success! Please open F12 and check the console.';
                                console.log(resp)
                            },
                        })
                    }
                    
                
  •                 
                    [spinning]{color:red}
                    
                

Dynamic File Requests

Supports requesting any text files (HTML, JSON, PHP, Java etc). Dynamic endpoints should return JSON/array format.

  • Output
  • HTML
  • JS
  •                 
                    
                
  •                 
                    let btnPhp = document.querySelector('#btnPhp'),
                        ajaxPhp =  document.querySelector('#ajaxPhp');
                    btnPhp.onclick = function () {
                        orca.ajax({
                            target: ajaxPhp,
                            url: 'https://req.orcaui.com/v1/php/request_obj.php',
                            success: function (resp) {
                                ajaxPhp.innerHTML = JSON.stringify(resp.content);
                                console.log(resp)
                            },
                        })
                    }
                    
                

Promise then() Method

The ajax function returns a Promise, allowing you to handle success or error outcomes through its then method.

catchable Parameter controls whether to execute then.reject() in the Promise chain.

  • false (default) => Silently ignores errors in Promise chain
  • true => Executes rejection handler (then.reject)
  • Output
  • HTML
  • JS
  •                 
                    
                
  •                 
                    let btnThen = document.querySelector('#btnThen'),
                        ajaxThen = document.querySelector('#ajaxThen');
                    btnThen.onclick = function() {
                        orca.ajax({
                            target: ajaxThen,
                            // Try using an invalid URL to trigger reject
                            url: 'https://req.orcaui.com/v1/html/v1_en_earth_01.html',
                            catchable: true,
                        }).then((resp) => {
                            ajaxThen.innerHTML = 'Success! Please open DevTools (F12) to view console output.';
                            console.log(resp);
                        }, (resp) => {
                            ajaxThen.innerHTML = 'Request failed! Open DevTools (F12) to check console logs.';
                            console.log(resp);
                        })
                    }
                    
                

New Launch: 20% Off All Products

Unlock all examples and development resources