Executing ajax function when the page loads and when a user clicks simultaneously

My external javascript file called ajax.js has an Ajax function like so:

function webservice(x){

   jQuery.ajax
            ({
                //some code here
            });

  Data = function(data){
                    if(x==1)
                            {
                                for(i=0;i<10;i++)
                                {
                                     webservice(i);
                                alert("Onload");
                                }
                            }
                            else 
                            if(x==5)
                            {
                                for(i=0;i<10;i++)
                                {
                                webservice(i);
                                alert ("Onclick");
                                }
                            }

        }

In another html page named webservice.html, I have the following code:

 <html>
 <title>Call web service</title>
 <head>
 <script type="text/Javascript" src="jquery-1.9.1.js"></script>
 <script type = "text/javascript" src="ajax.js"></script>
 <script>

 window.onload=function()
 {
   webservice(1)('onload');    //call 1 

 }

 </script>
 </head>

  <body>


  <input id="webservice"  type = "button" name = "webservice" value = "Call Webservice"       
  onclick="webservice(5)"/>


  </body>
  </html>

I am trying to call the same function both on the onLoad event and the onclick of a button so that they run simultaneously. However, when onload runs multiple times and then I click the button, the previous instances of onload stop. How can I make them run concurrently from where they left off or display alerts one after the other?

If anyone has alternative methods, I would appreciate the help.

Answer №1

Due to the asynchronous nature of $.ajax, your code is being called before the completion of the AJAX call, resulting in unexpected behavior.

To resolve this issue, move your code inside the success callback function like so:

function webservice(x) {
    var inputParam = x;
    jQuery.ajax({
        url: 'test.php',
        data: {},
        success: function (data) {
            if (inputParam  == 1) {
                for (i = 0; i < 10; i++) {
                    webservice(i);
                    alert("Onload");
                }
            } else if (inputParam  == 5) {
                for (i = 0; i < 10; i++) {
                    webservice(i);
                    alert("Onclick");
                }
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert('an error occurred!');
        }
    });
}

Additionally, it is recommended to avoid inline JS.

Replace

window.onload=function()
 {
   webservice(1)('onload');    //call 1 
 }

With

$(document).ready(function(){
    webservice(1);//call 1 
});

And

<input id="webservice" type="button" name="webservice" value="Call Webservice" onclick="webservice(5)"/>

With

$('#webservice').click(function(){
    webservice(5);
});

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

What is the reason for restricting AJAX requests to the same domain?

I'm puzzled by the limitation of AJAX requests to the same domain. Can you explain the reasoning behind this restriction? I don't understand why requesting files from external locations is an issue, especially since servers making XMLHTTP reques ...

"Troubleshooting why the jQuery Click Function is malfunctioning specifically in

Can someone help me troubleshoot this animate out script? It works fine on chrome, but not on Firefox and I can't seem to figure out why. Any suggestions? The script is designed to animate certain elements when a specific link is clicked. <scrip ...

Failure to execute after Ajax success

Currently working on a login page using Spring MVC on the server side and JS/Ajax on the client side. I'm facing an issue where the server code executes but does not return anything. <script type="text/javascript"> $(function() { $( ...

Bringing in a feature within the Vue 3 setup

At the moment, I am attempting to utilize a throttle/debounce function within my Vue component. However, each time it is invoked, an error of Uncaught TypeError: functionTD is not a function is thrown. Below is the code snippet: useThrottleDebounce.ts imp ...

Continuously iterate through a PHP page until the session variable reaches a specific value

I am in the process of creating a web-based exam. All questions and answers are stored in a MySQL database. I began by retrieving and displaying one question along with multiple-choice answers. I used a session variable $_SESSION['questionno'] = ...

Run PHP code using JavaScript

I am currently using Windows and attempting to use JavaScript/PHP to call a specific form that is saved in a different location. The file D:\Test\Form.php has the following content: <form action="D:\Test\submit.php" method="post"&g ...

The functionality to save user likes in React is not properly functioning on the like button

I created a like button in React that saves my choices, but it seems to be not saving the choices of other users. Additionally, it doesn't appear to restrict only authenticated users from marking likes. Can someone please help me identify what I' ...

Efficiently sending VueJS data to a separate script

I am in the process of transitioning an existing site to VueJS, but I have encountered a roadblock when it comes to finding the best method to accomplish this task. The site currently utilizes D3-Funnel (https://github.com/jakezatecky/d3-funnel) to genera ...

Is it necessary to use the prefix meteor when incorporating npm with Meteor?

When I am working on Meteor 1.3 projects, is it necessary to always prepend meteor before npm? The Meteor documentation and code examples seem to offer different approaches. I believe that the recommended practice is: $ meteor npm install --save some-pac ...

Tips for getting the sum of an array using the reduce method in Vue.js and returning the result array

As someone new to JavaScript, I apologize if my description of the issue is not clear. It's challenging for me to explain the problem I am facing. I have a computed function where I use the reduce method to iterate over my objects, perform calculatio ...

The issue with the value of the textarea in Selenium automated tests using

I have a webpage with Javascript where I've implemented a textarea using the following code: var textarea = $("<textarea>"); textarea.change(() => { console.log(textarea.val()); }); When I update the value in the textarea and then chang ...

Please be patient for the function to complete its execution

I am currently facing a challenge where the execution of functionA needs to halt until functionB() has provided an answer. In this case, the duration for functionB to respond varies depending on user input, ranging from 1 second to up to 10 seconds. As a r ...

Why is my npm installation generating an ERESOLVE error specifically linked to karma-jasmine-html-reporter?

Could someone help me understand this dependency error I encountered while running npm install and provide guidance on how to resolve such errors? View Error Screenshot I am currently using Angular 16, the latest stable version. npm ERR! code ERESOLVE ...

Incrementing the index in Javascript when an event occurs

I am currently working on a project that involves incrementing an index of an array based on certain events, such as a left mouse click over a designated area. The code snippet provided below initializes all values to zero and briefly changes the relevan ...

It appears that the PHP file is not being executed when attempting the second JSON POST request

After successfully retrieving data from the database using jQuery, PHP, and MySQL, I encountered an issue with my second AJAX call. Here is the first part of my code: $( document ).ready(function() { $( '#create-checklist' ).submit(function( ...

Expand an image to its full dimensions when it is initially loaded

Currently, I am experimenting with placing images of bubbles randomly on a webpage. To create the illusion of the bubble expanding in size from nothing to its full scale, I have been using CSS and specifically the transform:scale(); property. However, my ...

Populating Hidden Form Fields with Dynamic Identifiers

I'm facing an issue with a form where I need to input a value into a hidden field upon clicking a button. Despite using unique IDs for all elements, the data is not being submitted in the POST request. The IDs are unique because there are multiple f ...

Include the array in the 'content' property of the CSS using Jquery

I need help formatting data in CSS. The code I have is as follows: if (ext){ switch (ext.toLowerCase()) { case 'doc': pos = 'doc'; break; case 'bmp': pos = 'bmp'; break; ...

Transforming a unirest 'GET' call into an axios request

I am currently utilizing TheRundown API to access sports data. The example provided to me makes use of unirest, but I am endeavoring to adapt that example into an axios request. While I have managed to make it work for the most part, my main challenge lies ...