Special function to handle ajax requests malfunctioning

I am seeking to develop a unique function for AJAX post requests.

Below is the existing source code:

function handleAjax(url, data) {

  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        return xhr.responseText;
    }
  };
  xhr.open("POST", url, true);
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhr.send(data);

}

console.log(handleAjax('shipment.php', 'fname=test1&lname=test2'));

However, there seems to be an issue as the console displays "undefined".

If I replace `return` with `alert()` it works fine. So, why isn't `return` working in this case?

Answer №1

It appears that the function doAjax does not have a return value. By assigning

xhttp.onreadystatechange = function() {...};
, you are essentially setting up an event handler that will only execute when the specified event occurs. To ensure your desired actions take place, they must be included or triggered within this callback function.

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

Choose all the checkboxes alongside the markers on Google Maps

On this page , I have included a checkbox labeled "Select All" at the bottom, which automatically checks all other checkboxes. Although the code below achieves what I want, the marker icons are not showing up. How can this be fixed? $(document).ready(func ...

How can I update data in Select2 after it has been initialized?

After initializing select2, I am trying to set an array of data in the following way: var selection = $('#selection').select2({}); selection.data([ {id: 1, text: 'value1'}, {id: 1, text: 'value1'} ]); However, I am encou ...

jquery token selection dropdown box

I am not encountering any errors with this particular issue, however upon reviewing the plugin it appears that it should only toggle "admin admin" in the dropdown list. I am currently utilizing the most recent version of jquery. Upon further investigation ...

Getting data from jquery.ajax() in PHP - A comprehensive guide

When transferring data from JavaScript to PHP, I use the following method: $.ajax({'url': 'my.php', 'type': 'POST', 'data': JSON.stringify(update_data), 'success': functio ...

Issue with page not updating after local storage change and returning to previous page

I have encountered an issue where in Firefox and Safari, the value retrieved from localstorage on the first page is not updated until I manually refresh the page after setting the localstorage value on the second page. Disabling the cache did not resolve t ...

What is the best way to update a collection item while maintaining non-existing values in the query?

Consider this straightforward example, where an item is saved as: { "test": { "a1": "a1" } } When collection.updateOne is called with $set and the following object: await collection.updateOne(doc, {$set: {"test&q ...

Ways to segment into a proper array

I received the following object from an API and I am looking to convert it into an array using either JavaScript or C#. [ "1":"h1:first", "2":".content a > img", "3":"#content div p" ] I attempted converting it to a JSON object and using the spl ...

Populate HTML form with return values using jQuery AJAX

I am struggling with retrieving values from jQuery/AJAX and displaying them in an HTML form within the index.php file. This is what my index.php looks like: <script type="text/javascript"> $(document).ready(function () { $('#display'). ...

The issue of 'MessageChannel not defined' arises specifically on web pages that have implemented reCaptcha v2

I am currently working on scraping some websites that have implemented reCAPTCHA, but I keep encountering an error when loading the page's source: (node:15536) UnhandledPromiseRejectionWarning: ReferenceError: MessageChannel is not defined. Despite a ...

What is causing the click event handler to only function on the initial page?

Within my code for the "fnInitComplete" : function(oSettings, json), I am utilizing a selector like $('[id^=f_]').each(function (). The data for Datatables is retrieved server-side and "bProcessing":true I am aware that my selectors are only ef ...

Styling for the DataTable disappears upon loading jQuery

my PHP file named "zero3data.php" <?php printf('<table cellpadding="0" cellspacing="0" border="0" class="display" id="example" width="100%">'); printf('<thead>'); printf('<tr>'); ...

Check out how to utilize the jQuery .ajax Post method in a function

Can an AJAX POST be directed to a specific function in a PHP file? $.ajax({ type: "POST", url: "functions.php", //is there a way to specify a function here? data: "some data...", success: function(){ alert('Succ ...

The data I am trying to obtain is not being returned by my hook as expected

I am trying to create a hook that fetches all properties from a database. The function I have is asynchronous, and when I call the hook in another function, it returns an empty array []. I understand that fetching data from the database is an asynchronous ...

The script fails to work correctly when displaying the data

Last night, I finally cracked the code on how to transfer data from my form on the index page to the content page, and then display the results inside the content div back on the index page. However, a new challenge has emerged. My Javascript function (re ...

How can I use jQuery to choose and manipulate the text in my textbox within a repeater?

I am working with a repeater that contains textboxes populated with data from a database. During run-time, this repeater generates multiple textboxes with lots of data. <asp:Repeater ID="rpter" runat="server"> <ItemTemplate> <fieldset ...

Guide to Subscribing to a nested observable with mergeMap within a button's click event

The issue arises in the "addToWishlist" function as I attempt to concatenate the result of the outer observable with the inner observable array and then call the next method on the inner observable. The "addToWishlist" method is triggered by the click ha ...

Creating a realistic typewriter effect by incorporating Code Block as the input

I am looking to add a special touch to my website by showcasing a code segment with the Typewriter effect. I want this code block not only displayed but also "typed" out when the page loads. Unfortunately, I have been unable to find a suitable solution s ...

The back button functionality in Android cannot be altered or overridden using JavaScript

Hey everyone, I'm currently in the process of developing a mobile application using phonegap. I'm facing an issue where I want to disable the functionality of the back button from navigating to the previous page. I simply want it to do nothing or ...

Using AJAX to dynamically edit and update PHP data

The information displayed on my index.php page is fetched from a database using the mysqli_fetch_array function. The data is presented in a table format with fields like Name, Age, Email, and Update. An edit button allows users to modify the data. Here is ...

Ways to retrieve the highest date value in an array

I'm running into an issue where I am trying to find the maximum day in an array of dates, but for some reason it keeps returning either Invalid Date or null. I'm not sure what's going wrong. Do you think I should convert the values to a diff ...