Invoke the REST API by utilizing Ajax through invoking a function

I have a task that involves calling a REST API and getting the response. Currently, I am able to achieve this by directly making the AJAX call, which works perfectly fine. However, I now need to refactor this process into a function where I can pass two parameters that will be used in the URL. The goal is to return the response from this function so that it can be utilized in other classes.

function fetchData(param1, param2) {
  $.ajax({
    url: "BaseURL" + param1 + "/" + param2
  }).then(function(data) {
    if (data.test == null)
      self.prop1(data.test);
    if (data.test2 !== null)
      self.prop2(data.test2);
    if (data.test3 !== null)
      self.prop3(data.test3)
  });
}

Can you please provide any suggestions on how to approach this? Let me know if you require any additional information from my end.

Answer №1

It is recommended to construct the URL outside of the function for better organization:

// Declare the URL components
var BaseURL = 'www.baseurl.com';
var param1 = '<param1>';
var param2 = '<param2>';
var URL = `${BaseURL}${param1}/${param2}`

// Function to handle AJAX POST request
function AJAXPost(RequestType, formData, URL){
    $.ajax({
      url: URL,
      type: RequestType,
      data: formData
      // Test for success or error
    })
}

Answer №2

A convenient way to fetch data is by defining a function that takes parameters and a callback for handling the retrieved information

function fetchData(param1, param2, callback) {
  $.ajax({
    url: "BaseURL"+param1+"/" + param2
  }).then(function(data) {
    callback(data);
  });
}

Alternatively, you can use async/await for asynchronous operations

const fetchDataAsync = async (param1, param2) => {
  try {
    let data = await $.ajax({url: `BaseURL${param1}/${param2}`});
    return data;
  } catch(e) {
    console.error(e);
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Alternative Solution for JSONP Secure Connection

My typical approach of making JSONP requests to a different domain from the root of my website, https://example.com/, is no longer viable due to the switch to a secure connection. I need a solution that allows me to continue sending asynchronous requests ...

Error message: Encountered JavaScript heap out-of-memory error during Azure DevOps React Container Production Build

I am facing challenges in building a React production Docker container with Azure DevOps pipelines. Despite upgrading my build environment and code, the pipeline failed to run successfully. After conducting some research, I attempted to add the "--node-fla ...

Utilizing @casl/vue in conjunction with pinia: A guide to integrating these

I'm currently facing an issue with integrating @casl/ability and Vue 3 with Pinia. I'm unsure of how to make it work seamlessly. Here is a snippet from my app.js: import { createApp } from "vue" const app = createApp({}) // pinetree i ...

Getting the selected value from a dropdown menu in ReactJS

I am working on creating a form that resembles the following structure: var BasicTaskForm = React.createClass({ getInitialState: function() { return { taskName: '', description: '', emp ...

What is the best way to handle '<%=>' syntax in grunt?

Many grunt plugins support the following syntax for including files: ['<%= src_dir %>/common/**/*.js', '<%= src_dir %>/app/**/*.js'] or ['<%= test_files.js %>'] Is there a way to utilize a library that ca ...

What could be causing React to throw an invalid hook error when using useRoutes?

I encountered an error while attempting to add a new route to my project. import React from "react"; import News from "./NewsComponents/News"; import Photos from "./PhotosComponents/Photos"; import Contact from "./Contact"; import Home from "./Home"; ...

Exploring the integration of React Context API within a Next.js application to streamline the authentication process

I am looking to build a react app using Next.js. However, I am currently stuck and need assistance in figuring out how to proceed. I have implemented user authentication on the backend with node.js, passport.js, passport-local-mongoose, and express.sessi ...

Parsing JSON data in array format sent from jQuery and processed by Node.js

I'm currently experimenting with Node Js and working on an app for learning purposes. In this app, I aim to send data from an HTML form using jQuery/AJAX and have Node Js/Express handle and process the data. Here is the HTML code containing a series ...

Unable to associate Slider values with TextFields in MaterialUI

Currently, I am trying to create a slide with 2 markers to indicate a price range and interact with it on the slide. Although I have linked the input with the slider, the connection from the slider to the input is not functioning properly. My attempt was t ...

Ways to disseminate arguments when dealing with an array of arrays in JavaScript

Struggling to pass an array as arguments into the join method on path in node, but hitting a roadblock: var path = require("path"); var paths = [__dirname]; var userInput = ["app", "js"]; paths.push(userInput); var target = path.join.apply(null, paths); ...

When an HTML element is deleted, its events are not being removed as expected

I currently have events bound in my backbone view. sampleView = Backbone.View.extend({ events: { "click .sum": "sumButtonFunc", "click .diff": "diffButtonFunc" } sumButtonFunc: function(){ console.log("sum called") ...

JavaScript tabs that smoothly fade in and out

I'm currently working on implementing tabbed content, but I'm struggling with getting the fade effect to apply to the content itself when clicked, rather than just the tab headers. Check out my demo here $('#tab-wrapper li:first').add ...

Utilize .map function to format a date string and generate a table

I am currently utilizing .map along with React in order to generate a table using a coupons object. My goal is to format a date string into the "mm/dd/yyyy" format, with coupon.starts_at typically being set as coupon.starts_at = "2013-08-03T02:00:00Z" I h ...

Issues with Thunderbird not displaying copied HTML emails

Hello there amazing people at Stackoverflow. I need some assistance with HTML formatting. I am currently working on a bootstrap modal that is being dynamically modified through jQuery using the append() function. Check out the code snippet below: <div ...

Can you provide a basic illustration of how routes are implemented in AngularJS?

After searching through numerous examples of using Routes with Angular, I have unfortunately not been able to find a working solution. Even the example provided in the official guide did not work properly (clicking on it resulted in a wrong URL that did no ...

Optimizing performance with ng-if for 500 watchers

When repeating data with ng repeat, I encountered an issue where some of the data.image (src) values were null and I did not want them to be included in the repeat process. To solve this issue, I implemented a simple ng-if statement. <div ng-repeat="d ...

What is the best location to house the fetching logic for mounting an app with intricate React v6 routing?

I have a protected route component that handles various tasks: Authorizing users with Auth0. Checking if the store is empty and making a request to the backend API for user data. Passing a function that returns an access token to the axios interceptor so ...

Application: The initialization event in the electron app is not being triggered

I am facing an issue while trying to run my electron app with TypeScript and webpack. I have a main.ts file along with the compiled main.js file. To troubleshoot, I made some edits to the main.js file to verify if the "ready" function is being called. ...

Combining rows with identical IDs within an array of objects

Here is a representation of the array I am working with: var exampleArray = [ { "ItemID": "001", "Jan": "130", "Feb": "500" }, { "ItemID": "001", "Jan": "0&q ...

Tips for avoiding view refreshes while switching routes in AngularJS

I'm currently developing a web application that allows users to view objects on a map, click on a marker, and navigate to a new section with specific information. This information can lead to further details as well. For example: /map /tree/{treeid ...