Javascript functions function properly only if they contain the 'alert()' command

My aim is to utilize Ajax (Javascript + php) for checking user name availability when a user moves focus to another form field. The strange part is that my functions only work when I include some alert(), without them, the functions fail to operate.

Another peculiar observation is that alert(requestObject.readyState); only displays state 1. Ideally, it should show all states, or at least state 4 as well.

Here's my javascript code placed in the HTML page header:

    var requestObject = false;
    function funcReceiveData()
    {
        alert(requestObject.readyState);
        if(requestObject.readyState == 4)
        {
            if(requestObject.status == 200)
            {
                var status = requestObject.responseText;
                if(status == "ok")
                {
                    document.getElementById('userValid').innerHTML = 'Valid user';
                }
                else
                {
                    document.getElementById('userValid').innerHTML = 'Choose another username';
                }
            }
        }
    }

if (window.XMLHttpRequest)
{
    requestObject = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
    requestObject = new ActiveXObject("Microsoft.XMLHTTP");
}

function checkUser()
{
    if(requestObject){
        requestObject.open("POST", "addUser.php", true);
        requestObject.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        var user = document.getElementById('username').value;
        var tobesent = "username=" + user;
        requestObject.send(tobesent);
        requestObject.onreadystatechange = funcReceiveData();
        alert(tobesent);
    }
}

This forms the body section of my HTML code:

<BODY>
<form method="POST" action="addUser.php">
    <table>

        <tr>
            <td><strong>Username:</strong></td>
            <td><input type="text" name="username" size="25" onblur="checkUser();" id="username"></td>
            <td><i id='userValid'>bla</i>
        </tr>

        <tr valign="top">
            <td><strong>Password:</strong></td>
            <td><input type="password" name="password" size="25"></td>
        </tr>

        <tr valign="top">
            <td><strong>Frist name:</strong></td>
            <td><input type="text" name="Fname" size="25"></td>
        </tr>

        <tr valign="top">
            <td><strong>Last name:</strong></td>
            <td><input type="text" name="Lname" size="25"></td>
        </tr>

        <tr valign="top">
            <td><strong>Address line 1:</strong></td>
            <td><input type="text" name="address1" size="50"></td>
        </tr>

        [<!-- More form fields here -->]

    </table>
</form>

Below is my PHP code for testing purposes before integrating with a database:

<?php 
$user = $_POST['username'];
if($user == "Tiago")
    echo("ok");
else
    echo("Error");
?>

The page is hosted at:

Any insights into what might be causing this issue?

Answer №1

Ensure to assign funcReceiveData as the handler for the readyStateChange event, rather than calling it directly.

The reason it may not be working is because the HTTP request hasn't received a response yet. By adding an alert, you are delaying the read value of requestObject.readyState until you interact with the alert box, giving enough time for the response to arrive.

To fix this issue, remove the parentheses when assigning the event handler and make sure to do so before sending the request:

requestObject.onreadystatechange = funcReceiveData;
requestObject.send(tobesent);

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

Oops, it seems like there is a TypeError with the function window.initMap in Google Maps

For the past week, I have been struggling to update my marks on Google Maps while using AJAX in an HTML page. My controller fetches data from the database and sends it back, but now I am encountering the following error: TypeError: window.initMap is not a ...

Issue with firing Facebook pixel after router.push() in Next.js

Within this code block is FB pixel tracking code <Script id="some-id" strategy="afterInteractive">some fb pixel code</Script> The issue arises when navigating to a page containing the script using router.push(SOME_ROUTE). T ...

I am unable to make changes to the Text Field component in Material-UI

After developing a React App using Material-UI, I decided to create independent Components. Below are the independent components (<PanelDiv/>): render() { return ( <div className="panelDiv-component" style={{display:this.prop ...

Unexpected behavior observed with Gridview paging within ModalPopupExtender

Having an issue with my modal pop-up extender that displays a grid view. When I click a button, the grid is supposed to populate following this code: protected void btnViewRecipients_Click(object sender, EventArgs e) { ModalPopupExtender1.Show(); ...

Load CKEditor.js with RequireJS following the textarea element

If you need a WYSIWYG editor, CKEditor could be the answer. Check out their documentation here. To properly load CKEditor, make sure to add the following script tag in the header: <script src="../ckeditor/ckeditor.js"></script> ... Then, inc ...

Attempting to wipe out a request using ajax to access relationship entities in a ruby on rails framework

I'm currently working on implementing an ajax request to delete a "budget" (known as "orçamento" in Portuguese). These budgets are associated with a "cadastre", where each cadastre can have multiple budgets. Below, you can find the components involve ...

Is there a way to modify the button's color upon clicking in a React application?

I am a beginner in the world of React and currently exploring how to utilize the useState hook to dynamically change the color of a button upon clicking. Can someone kindly guide me through the process? Below is my current code snippet: import { Button } ...

Is the data set in stone, or is it just the API data that can

Recently, I embarked on the journey of creating a blog using nextjs, MongoDB, and express. Taking advantage of getStaticProps and getStaticPaths, I was able to dynamically generate pages for each blog post and display them individually. However, I encoun ...

Tips for implementing AngularJS on a webpage transfer

I am a beginner in learning AngularJS. I have gone through the basic tips on W3Schools, but now I am stuck on implementing the login function. When I click the "sign in" button, the webpage should redirect to the login page of the website. However, I am ...

Utilize AJAX to send a file within an HTTP request

In my attempt to send a form using an Ajax request, I encountered a challenge with uploading files. Here is a snippet of my form: <form> {{csrf_field()}} <div class="form-group"> <label for="company-name">Co ...

The functionality of Ajax is not supported on iPhone Safari browsers

I have encountered an issue where my ajax function works perfectly in Firefox, but it fails to work on my iPhone. Initially, I suspected the XMLHttpRequest was causing the problem, but that does not appear to be the case. I can confirm that the PHP script ...

Retrieve records where the ID is not found in another table limited by a specific date range

Is it possible to use the 'where not in' and 'between date intervals' clauses separately instead of combining them into one query? $this->db->select('*'); $this->db->from('admission'); $this->db->w ...

"Unlocking the power of Symfony bundles: Exploring the versatility of REST API

Seeking opinions here. I am working on a Symfony4 bundle that connects to an SMS service's REST API. The service allows authentication in two ways: Session Id, which expires in 5 minutes of inactivity Token that is always valid Both modes require u ...

display only the final outcome within the FOR loop of a Joomla module

Here is the code I have in tmpl/defult.php of my Joomla 2.5 module: $result = count($payed); for($i=0;$i<$result;$i++) { $pay=F.$payed[$i]; echo "<td>".JText::_("$pay")."</td>"; echo "<td>".number_format($item->$pay)."< ...

AngularJS tree grid component with customizable cell templates

I have been utilizing the tree-grid component in AngularJS from this link: Here is an example of it on Plunker: http://plnkr.co/edit/CQwY0sNh3jcLLc0vMP5D?p=preview In comparison to ng-grid, I am unable to define cellTemplate, but I do require the abilit ...

"Exploring the world of mocking module functions in Jest

I have been working on making assertions with jest mocked functions, and here is the code I am using: const mockSaveProduct = jest.fn((product) => { //some logic return }); jest.mock('./db', () => ({ saveProduct: mockSaveProduct })); ...

How can we optimize axios requests with lodash debounce?

Utilizing a state prop named network busy status to control elements in the UI. Due to the rapid changes in status, my spinner appears overly active. Is there a simple method, utilizing lodash _.debounce, to throttle this section of code? const instance ...

jquery is showing up in the browserify bundle.js file, however, it is not functioning properly

Currently, I am trying to follow a brief tutorial on how to use Browserify. Despite following the instructions precisely, jQuery seems to not be working properly when bundled. Specifically, the button element in my app.js code is not appended to the body. ...

Firebase Firestore is returning the dreaded [object Object] rather than the expected plain object

I've created a custom hook called useDocument.js that retrieves data from a firestore collection using a specific ID. However, I'm encountering an issue where it returns [object Object] instead of a plain object. When I attempt to access the nam ...

Why won't my controller function fire with ng-click in AngularJS?

I'm having trouble getting a function to execute when my button is clicked. Despite the fact that this code appears correct, the function defined in my controller isn't being triggered. The code compiles without errors as shown in the console. A ...