Fetch Library (Ajax Requests)

The Stratox framework provides built-in Ajax integration using the JavaScript Fetch API, which you can utilize if needed. While it's not mandatory, you can easily integrate your own Ajax library in the dispatcher within the main JavaScript file, main.js.

The Ajax response will be passed to the controllers!

Triggering Ajax Calls

You can trigger Ajax calls in 3 different ways:

  1. Bind Ajax call to a view and the view's response

  2. Configure the main app's settings to enable Ajax calls for every router request automatically (though you can manually disable Ajax calls in each route if necessary).

  3. Manually add Ajax configuration in each route.

  4. Or all of the above

1. Binding Ajax to a View

Binding an Ajax request to a view allows the view to automatically trigger the request upon rendering, updating with the JSON response as soon as it's received.

Quick Start

Here’s the fastest way to bind an Ajax request to a view:

const ingressView = this.layout(Ingress, StratoxFetch.get("https://dummyjson.com/products/1"));

That’s it! The view will display the response from the URL as soon as the data is fetched.

You can make GET, POST, PUT, and DELETE requests by simply changing the get method above to the appropriate request type.

StratoxFetch.get(url, config);
StratoxFetch.post(url, data, config);
StratoxFetch.put(url, data, config);
StratoxFetch.delete(url, config);
  • url: Expects a string and URL value

  • config: expects a object and is the Fetch API config

  • data: expects a object and it is the the parsed body/post request items

Modifying the Response

You can modify the Ajax response before passing it to the view. Here’s how:

const fetch = new StratoxFetch("https://dummyjson.com/products/1");
const ingressView = this.layout(Ingress, fetch.execute(function(response) {
    response.title = "Modified title";
}));

You can make GET, POST, PUT, and DELETE requests by simply specifying it in the setMethod method to the appropriate request type:

fetch.setMethod("POST");

If you want to configure the fetch API, you pass an object in second parameter of the class:

const fetch = new StratoxFetch(url, config);

Creating the View

The view function will receive the Ajax response data once the request is complete. While waiting for the data, you can use context.isLoading() to manage loading states and display an appropriate message if needed.

Here’s an example:

export function Ingress(props, container, helper, context) {
  // Add loading screen
  if(context.isLoading()) {
    return `<div class="p-5">Loading...</div>`;
  }

  return  `
    <article class="relative card-1 border-bottom ingress">
      <div class="wrapper md">
        <h1 class="headline-1">${props.title}</h1>
        <p>${props.description}</p>
      </div>
    </article>
  `
}

Summary

  • Quick Setup: Simply pass the Ajax request to this.layout.

  • Modify Data: Use .execute() to adjust the response before it reaches the view.

  • Loading State: Use context.isLoading() to manage loading behavior and provide feedback to the user while waiting for the request to complete.

This approach allows for flexible and dynamic updates within your views, with minimal setup.

2. Enable Ajax on Every Router Request

To enable Ajax for every router request, open the main JavaScript file ./src/main.js and add the request configuration to the App class. Below, I've filled in each config option:

Note: The full configuration list is at the end of the guide.

const app = new App({
    request: {
        dataType: "json",
        url: "https://example.se/backend-location/",
        //startPath: "home", // Not required, will set a default start path
        config: {
            headers: {
                'Accept': 'application/json'
            }
        },
        get: function(searchParams) {
            searchParams.append("param", 1);
            return searchParams;
        },
        post: function(object) {
            object.param = 1;
            return object;
        }
    }
});

Click here for full configuration.

The dataType configuration automatically sets certain headers in the fetch config to correspond to each data type. However, you can overwrite these headers with your own custom headers if needed.

3. Enable Ajax Manually on a Router

To enable Ajax manually on a specific router, open the main JavaScript file ./src/routes/app.js and add the request configuration to the route. Below, I've filled in each config option:

router.get('/contact', [PagesController, "contact"], {
    url: "https://example.se/backend-location/",
    //path: '/new-contact-path', 
    config: {
        headers: {
            'Accept': 'application/json'
        }
    },
    get: function(searchParams) {
        // Add static Query string
        searchParams.append("param", 1);
        return searchParams;
    },
    post: function(object) {
        // Add static Parsed body parameter
        object.param = 1;
        return object;
    }
});

Click here for full configuration.

With these configurations, you can easily enable Ajax functionality for your Stratox application, either globally or on specific routes. Adjust the options as needed to suit your application's requirements.

Accessing the Ajax Response

Accessing the Ajax response is as simple as accessing the http parameter to retrieve the Ajax request body response. This process works the same in controllers.

router.get('/', function(http, container, helper, context) {
    console.log(http.response); // The Ajax response
    return this;
});

In this example, http.response allows you to access the Ajax response data within the router/controller function. You can then use this data as needed in your application logic.

Fetch Ajax Configurations

For the fetch option 2-3, both approaches use the same object parameters:

  • url: The URL to your site/API location to access via Ajax.

  • dataType: Set expected response data type (json, xml, or text). JSON response will be converted to an object, XML to DOMParser, and text will be returned as is. (default: json)

  • path: Overwrites the expected URI path. (optional)

  • startPath: Adds a default start path if the URI path is empty. (optional)

  • config: Supplies the Fetch API with options. You can read more about these options here. (optional)

  • get: Passes or modifies a GET parameter for the controller result. (optional)

  • post: Passes or modifies a POST parameter for the controller result. (optional)

Last updated