Using an external function to implement Javascript and AJAX interactions

function makeAjaxRequest(destination_full_url) {

    if (window.XMLHttpRequest) {// code for modern browsers
        xmlhttp = new XMLHttpRequest();
    } else {// code for old Internet Explorer versions
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            alert("Response: \n" + xmlhttp.responseText);
            return xmlhttp.responseText;

        }
    }

    xmlhttp.open("GET", destination_full_url, true);
    xmlhttp.send();
}



    function callThirdPartyFunction(obj) {
       var response;
       response = makeAjaxRequest("info.php?keyword=obj.value");
       alert(response);         
    }


<textarea onkeypress="callThirdPartyFunction(this);"></textarea>

A "undefined" message box shows up first and then a message box with the ajax request data appears.

The question is why the alert(response); runs before the ajax_request() function finishes and how to make it wait until the function is complete before moving to the next line?

Answer №1

due to the asynchronous nature of ajax, it operates in the background by default. To change this and make it synchronous, you can switch from

xmlhttp.open("GET", destination_full_url, true);

to

xmlhttp.open("GET", destination_full_url, false);

=== latest update ===

function perform_ajax_request(destination_full_url, callback){
.....
xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            alert("server response: \n" + xmlhttp.responseText);
           callback(xmlhttp.responseText);

        }
    }
...
}

....


function execute_third_party_function(obj) {
       perform_ajax_request("info.php?keyword=obj.value", function(response){alert(response) });

    }

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

Determining the condition of the menu: understanding whether it is open or closed

I'm diving into the world of jQuery and JavaScript, trying to grasp the ins and outs of the mmenu API. Despite my efforts to understand the libraries, the JavaScript code remains a mystery to me. Following the tutorial provided on , I successfully cr ...

JavaScript Navigation Bar Error: The value of 'undefined' is not recognized as an object

Having just started learning HTML, CSS, and JavaScript, I encountered an error message that reads: TypeError: 'undefined' is not an object. Despite my best efforts to troubleshoot the issue, I have been unable to resolve it. Is there anyone who c ...

Combine two elements in an array

I am faced with a challenge in binding values from an Array. My goal is to display two values in a row, then the next two values in the following row, and so on. Unfortunately, I have been unable to achieve this using *ngFor. Any assistance would be greatl ...

What could be the reason for only one of my states being modified when I call my function?

Currently, I have a single state in React.js consisting of two key-value pairs for length validation and character validation: const [validation, setValidationState] = useState({ lengthValidation: "", characterValidation: "", }); These states are e ...

Passing parameters in a callback function using $.getJSON in Javascript

I am currently using a $.getJSON call that is working perfectly fine, as demonstrated below. var jsonUrl = "http://www.somesite.co.uk/jsonusv.php?callback=?"; $.getJSON(jsonUrl,function(zippy){ ...some code } However, I want to pass a ...

Every time I switch tabs in Material UI, React rebuilds my component

I integrated a Material UI Tabs component into my application, following a similar approach to the one showcased in their Simple Tabs demo. However, I have noticed that the components within each tab — specifically those defined in the render method ...

What could be causing the error "no controller found" when attempting to call a web API post method?

I recently created a basic ASP.NET project that includes a WebAPI. However, I encountered an issue when trying to send a POST request from an HTML page to the WebAPI. Instead of success, I received an error message. The controller named 'api' do ...

Learn how to show the current page number using React Js with the help of material-ui's

Take a look at the code snippet below from my App.js Component: const App = () => { const [workstations, setWorkstations] = useState([]); let [page, setPage] = useState(1); const PER_PAGE = 1; useEffect(() => { loadWorkstations(); }, [] ...

Merge JSON objects while retaining duplicate keys

I am looking to merge two arrays containing JSON objects while retaining duplicate keys by adding a prefix to the keys. In this specific scenario, the data from 'json2' is replacing the data from 'json1' due to having identical keys, bu ...

Storing jQuery output in a global variable can be achieved by assigning the result

Take a look at the Code snippet below - $(function() { $.fn.getPosition = function() { var results = $(this).position(); results.right = results.left + $(this).width(); results.bottom = results.top + $(this).height(); return results; } ...

What is the best way to trigger an event in VueJS?

I recently implemented a table using Vuetify in my project. The table is now split into two components - the Table component and the Row component. My challenge is how to handle the same function, this.selected = !this.selected!, when dealing with 2 differ ...

Open a JavaScript file to retrieve data from a nearby JSON object

I've been trying to access a local JSON file using a JavaScript file, but for some reason it's not working. Even though I'm sure the URL is correct, the code keeps failing to retrieve data from the JSON object. JavaScript file: var pieData ...

Is there a way to showcase the data of each table row within the tr tag in an Angular 8 application?

I have been developing an application using Angular 8. The employee-list component is responsible for presenting data in a table format. Within the employee-list.component.ts file, I have defined: import { Component } from '@angular/core'; impo ...

Using model binding to dynamically sort data in a KendoUI Grid

I am currently using KendoUI Grid to display data, and I have successfully implemented server-side paging. Each page change triggers an ajax request to the server, which then returns the appropriate page of data. Now, I am faced with the challenge of imple ...

Is there a way to verify that all CSS files have been successfully downloaded before injecting HTML with JavaScript?

I am looking to dynamically inject HTML content and CSS URLs using JavaScript. I have more than 3 CSS files that need to be downloaded before the content can be displayed on the page. Is there a way to check if the aforementioned CSS files have finished ...

How can you ensure a form is properly validated using javascript before utilizing ajax to submit it

I've been working on developing a website and I am in need of an attractive login/registration/forgot password form. My aim was to utilize 'ajax' to enhance the user experience, leading me to immerse myself in a steep learning curve for the ...

Tips for resolving state change issues in VUEX

I am facing an issue with making changes to the state while splicing an element from another array without affecting the state itself. To clarify, I want to remove one element from the array arrayWithFilters = [] without altering the state.selected.filte ...

Fade out when the anchor is clicked and fade in the href link

Is it possible to create fade transitions between two HTML documents? I have multiple HTML pages, but for the sake of example, let's use index.html and jobs.html. index.html, jobs.html Both pages have a menu with anchor buttons. What I am aiming to ...

Upon installation, the extension that replaces the new tab fails to detect the index.html file

edit: Check out the Chrome Extension here Edit 2: It seems that the recent update containing the index.html file was not published due to Google putting it under revision. Apologies for forgetting to include the index.html file in the upload zip, as I ...

What is the best way for me to determine the average number of likes on a post?

I have a Post model with various fields such as author, content, views, likedBy, tags, and comments. model Post { createdAt DateTime @default(now()) updatedAt DateTime @updatedAt id String @id @default(cuid()) author U ...