Can you please let me know if it's possible to store an ajax function/call for future reuse?

While developing a web app using JavaScript and PHP, I've noticed that I keep rewriting the same ajax calls repeatedly. Is there a way to create a reusable function or variable for these calls, with or without parameters?

I'm fairly new to JavaScript, so please bear with me as I am still learning.

Instead of coding like this:

  $("body").on("click", ".all-forms-link", function() {
         $.ajax({ 
            url: "forms.php", 
            type: "post", 
            data: {formsPage: 1}, 
            success: function(data) {
                     stage.html(data)
             }

          }); 
     }); 
     //similar code repeated multiple times

We can approach it in a more organized manner, like shown below:

      function loadForms() {
            $.ajax({ 
            url: "forms.php", 
            type: "post", 
            data: {formsPage: 1}, 
            success: function(data) {
                     stage.html(data)
                                     }
                   }); 
                             }

  body.on("click", ".all-forms-link", function() {
        loadForms(); //or something similar
   }); 

Answer №1

Absolutely. If you define a named function like this:

function foo(){
   . . .
}

You can use that function by its name wherever a function is required.

Therefore, your code could be simplified further as shown below:

function loadForms() {
  console.log("AJAX Call Initiated!");
  $.ajax({ 
    url: "forms.php", 
    type: "post", 
    data: {formsPage: 1}, 
    success: function(data) {
      stage.html(data)
    }
  }); 
}

// Simply refer to your function's name (without adding parenthesis 
// because we are not executing it here, just referencing it) where a function is expected.
$(document).on("click", ".all-forms-link", loadForms);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="all-forms-link">Click me</div>

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

Utilizing Varnish Cache to optimize AJAX GET requests

I am currently dealing with an AJAX request that is running on a server equipped with Varnish. The specific request is structured as follows: (function() { $("#name").autocomplete({ minLength:3, //minimum length of characters for t ...

Utilize key-value pairs to reference variables when importing as a namespace

Is it feasible to utilize a string for performing a lookup on an imported namespace, or am I approaching this the wrong way? Consider a file named my_file.ts with contents similar to: export const MyThing: CustomType = { propertyOne: "name", ...

Tips for updating form tag details within the same blade file upon reloading

I have set up a payment page that displays the total amount to be paid. To facilitate payments through a 3rd party gateway, I have utilized a form tag on the page. Now, I am looking to integrate a promo code feature on this payment page so that the total a ...

I want to display events from my database table on their corresponding dates using JavaScript and jQuery. How can I achieve this?

Using the FullCalendar plugin, I attempted to achieve a specific functionality, but unfortunately fell short of my goal. Below is the snippet of my scripting code: $('#calendar').fullCalendar({ //theme: true, header: { ...

Error: The function get_post() is not defined and cannot be called

I am new to WordPress and trying to build my first website. I have an index.php page with a link to the about section, which is supposed to display content from a page (post) in the WordPress dashboard named "about". I am using the Magnific Popup plugin fo ...

Issue with PHP Namespace: Parent Class variables are not being properly transmitted to Child Class

While developing a WordPress plugin, I encountered a strange issue with implementing namespaces. In my child class, the parent variables are accessible in the __construct method but not in any other method. The Parent Class is named class.db.php. This cla ...

How can CKEditor ensure that there is a paragraph tag within a div element?

Working on my current CMS, I have the need to include some custom HTML (which is functioning as expected): var element = CKEDITOR.dom.element.createFromHtml("<div class='sidebar'>Edit Sidebar Text</div>"); The issue arises when atte ...

Understanding the specific types of subclasses derived from an abstract generic class in Typescript

There is a Base generic class: abstract class BaseClass<T> { abstract itemArray: Array<T>; static getName(): string { throw new Error(`BaseClass - 'getName' was not overridden!`); } internalLogic() {} } and its inherito ...

Exploring the Reach and Sequence of AJAX Callbacks

This particular piece of code aims to achieve three main tasks: 1) validate the online status of users, 2) retrieve their information from a slightly different URL, and 3) present both sets of data in HTML format. The implementation appears functional bu ...

Problem with submitting forms created dynamically using jQuery

I'm completely puzzled by this issue. I've been struggling to make it work, but for some reason, the submit event is not being captured in the first block where the login form is displayed: function appInit() { $.post(clubapp,function(d){ ...

Converting HTML into an object using $compile

I am currently working on calling an HTML template and want to bind the data with Angular. I successfully retrieve the data to bind and the HTML, but when I try to compile it, it returns all the HTML binded as an object. How can I convert it back to plain ...

Implementing AJAX requests in jQuery DataTable with ASP.NET MVC

For some time now, I have been using the jQuery DataTables 1.10.13 plugin. Recently, I encountered an issue related to the ajax data source for my HTML table. This is how I initialized jQuery DataTable inside Files.cshtml <script language="javascript" ...

Solution for fixing the error: MongooseError [OverwriteModelError]: It is not possible to overwrite the `User` model after it has been compiled in

I am new to working with the MERN stack and currently attempting to create an exercise tracker app following a tutorial on YouTube. However, I am encountering the Mongoose: OverwriteModelError when running the server and cannot seem to identify where I am ...

Include a lower border on the webview that's being shown

Currently, the webview I'm working with has horizontal scrolling similar to a book layout for displaying HTML content. To achieve this effect, I am utilizing the scroll function. My inquiry revolves around implementing a bottom border on each page usi ...

Loading AJAX content within the existing page instead of a pop-up window

My goal is to have the page links load in a popup, but after adding this script, the page loads at the bottom instead. How can I make it open in a popup window instead? $('a[rel="ajax:jmodal"]').click(function(event) { $.ajax({ url: $(this).a ...

The function did not execute properly, resulting in the express route returning no value

Encountering some issues with Express routes that are behaving inconsistently despite having identical code execution. The goal is to have a client application make API calls like this: async search(){ const query = this.$refs.searchInput.value; ...

Tips for sending a file to a Servlet using an Ajax request

When working with an HTML form in AEM that requires file attachments, the challenge arises when trying to send these files via a Java Servlet through a Rest API. The issue lies in transmitting file arrays through Ajax to the Java Servlet, as only string da ...

The Heroku and Jekyll collaboration yields a distinctive feature where the deployment process seamlessly includes the index

I am encountering an issue with an ajax call that posts to /php/rsvp.php. When this call goes through the web server, it appends index.html onto the path for some reason. The application is hosted on Heroku using Puma. I have included the stack trace below ...

Using Typescript to import an npm package that lacks a definition file

I am facing an issue with an npm package (@salesforce/canvas-js-sdk) as it doesn't come with a Typescript definition file. Since I am using React, I have been using the "import from" syntax to bring in dependencies. Visual Studio is not happy about th ...

How can you deactivate the vue-router for specific routes? Is it possible to operate a single-page application backend while utilizing a non-single-page

I'm currently working on a website/webapp using Laravel 5.3 and Vue 2. Since SEO is crucial, I've decided to keep the frontend/crawlable part of the site in Laravel + Blade, with only minimal sections in Vue 2.0. This way, I can avoid using Ajax ...