Invoking function to utilize xmlhttprequest open() and send()

I have encountered an issue while attempting to send a GET request from a form using the form's onsubmit='function();' and AJAX.

<html>
<head>
<script type='text/javascript'>
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function(){
        window.alert("readystate change: " + xmlhttp.readyState + " , " + xmlhttp.status); 
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
            document.getElementById('adminPanel').innerHTML = xmlhttp.responseText;
        }
    }

    function submit_password(){
        xmlhttp.open("GET","./src/admin_pass.php");
        xmlhttp.send();         
    }
</script>
</head>
<body>
    <form onsubmit='submit_password();'>
        <input type='password' placeholder='PASSWORD'>
    </form>
    <div id='adminPanel'>
    </div>
</body>
</html>


<?php
    echo "test text";
?>

Upon investigation, I noticed that when I make calls from within the function using form submit, I receive a status=0 error. However, if I remove the function and let everything run at once, it executes smoothly. This has left me puzzled as to why this is happening. While searching online for solutions, I could not find any examples similar to what I am trying to achieve. Despite thinking about resorting to jQuery's ajax function in the end, I prefer not to include it just for this purpose.

EDIT: After further analysis, I discovered that the XMLhttprequest status=0 implies a HTTP connection error. Could it be due to an issue with my URL structure? The directory layout appears as follows:

root
    src
        admin_pass.php

Should I specify http:// localhost/src/admin_pass.php? In previous test scenarios, utilizing relative URLs worked without any problems.

EDIT: Updated with a comprehensive example

FIXED:

To my surprise, removing the unnecessary form resolved the problem. Though unsure of the exact reason behind this solution, responses suggesting issues with the form prompted me to take this action.

<html>
<head>
    <title>Admin Page</title>

<script type='text/javascript'>     
    function submit_password(){
        var xmlhttp = new XMLHttpRequest();

        xmlhttp.onreadystatechange = function(){
            window.alert("readystate change: " + xmlhttp.readyState + " , " + xmlhttp.status); 
            if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
                document.getElementById('adminPanel').innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET","./src/admin_pass.php",true);
        xmlhttp.send();         
    }
    function check_enter(e){
        if(e.keyCode == 13){
            submit_password();
        }
    }
</script>
</head>
<body>
<input id='password' type='password' placeholder='PASSWORD PLEASE' onkeyup='check_enter(event);'>

<div id='adminPanel'> 
</div>
</body>
</html>

Answer №1

Avoid declaring it as a global variable. You can test out the code provided above.

<script type='text/javascript'>
function enter_password(){
var request = new XMLHttpRequest();
     request.onreadystatechange = function(){
     window.alert("Ready State Change: " + xmlhttp.readyState + " , " + xmlhttp.status); 
     if(request.readyState == 4 && request.status == 200){
        document.getElementById('adminPanel').innerHTML = request.responseText;
     }
   }
    request.open("GET","./src/admin_pass.php");
    request.send();         
}
</script>

Answer №2

If you encounter a status 0 error, it typically means there is an issue with your request. You can check this example on jsfiddle to see how changing the request URL from / to http://google.com triggers a status 0 response.

It's important to ensure that you are making requests within the same domain. Even though your example appears to do so, double-check to make sure it aligns with your actual usage.

You can view the fiddle demonstrating the status 0 issue here.

Another factor to consider is consistency when using 'localhost' and '127.0.0.1'. Browsers may interpret them differently, so it's recommended to stick to one (e.g., '127.0.0.1') for both starting the server and specifying absolute URLs. Make sure the browser page also references the same IP address ('127.0.0.1').

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

Submitting a form and obtaining results without relying on jQuery

Finding information on how to accomplish this task without using jQuery has proven to be a challenge. It seems like everyone is pushing for jQuery for even the simplest tasks nowadays. Despite avoiding unnecessary use of jQuery in creating a rich experienc ...

How to synchronize $scope variables between controllers in AngularJS

As a newcomer to Angular, I have a seemingly simple question regarding setting up a comments system for articles. I've implemented two angular controllers - one for loading comments upon page load and another for submitting new comments to the server. ...

Maintain the original canvas aspect ratio while resizing the browser window

I am working with a canvas that has a width and height set to 100%. It occupies the entire screen, and I have drawn an image on it. My goal is to maintain the original aspect ratio of the image when resizing the browser window. I am looking to achieve the ...

The combination of jQuery 1.8.2 autocomplete, .live(), and .create() is causing issues and not functioning properly when

I am currently working on an asp.net MVC web application and utilizing jQuery version 1.8.2 along with jQuery-ui 1.8.24. The autocomplete code I have implemented is as follows: $("#ServerTag,#SDTag,#FirewallTag,#RouterTag,#SwitchTag").live("focus.autocomp ...

Tips for showcasing information stored in a JSON file: Input a value into the field provided, then utilize AngularJS to retrieve and display the corresponding data based on that specific value

https://plnkr.co/edit/iZqalOkrpSnjIzwvGchO?p=preview Is there a way to retrieve the data associated with each serial number entered in the search box? What elements might be missing from the current code? { "SerialNumbers": { "451651": [{ ...

When I use my loop to generate Google Map markers, the positioning is not accurate and the markers do not appear on the map. However, manually inputting the positions

There seems to be an issue with displaying Google map markers based on objects in the markers array after looping through it. I noticed that when creating a second component and setting the position manually, the marker appears correctly. However, upon ins ...

Unable to store a customized class object in Parse database

I have been attempting to create a Customer class object that is linked one-to-one with the User class. However, despite my efforts, the object does not save and no error message appears. Here is the code I am working with: Parse.Cloud.afterSave(Parse.Us ...

What is the method for linking images to URLs in my carousel?

I am in the process of revamping a confluence page that showcases a variety of visualizations. Here is the code snippet I am currently working with: <div class="carousel"> <img src="image1.jpg"> <img src="i ...

Attempting to utilize a Jquery Ajax post method to retrieve information from my specified URL and display it within my HTML Div element

Seeking assistance in fetching real-time data using a jQuery Ajax Post method. My experience lies mainly in SQL and C#, so coding in this language is relatively new to me. I was advised to use this script, which seemed straightforward. However, despite my ...

What are the steps to create a button within an Onsen sliding menu?

For instance, if I have a menu at http://codepen.io/onsen/pen/IDvFJ, how can I insert a new element named page3, so that when a user clicks on it, it triggers the following code: Appmenu.onclick('page3', function(){ alert("Hello"); }) ...

Why is my React hooks fetch request returning an empty array?

Hey everyone, I'm new to using react hooks and I've encountered an issue while trying to retrieve data from an API. It seems that when I make the request, I receive two responses - first an empty array and then the actual data from the API. Can a ...

Including items into an array through user input

My goal is to create a form that allows users to choose from two different "activities". The information entered will be saved along with personal details, and later displayed below each corresponding activity. Additionally, I want to give the ability to a ...

A JSX component cannot utilize the 'react' component

For the past two days, I've been encountering an error where React is not being recognized as a JSX component. Here's the full error message: 'ExportTemplateModal' cannot be used as a JSX component. Its element type 'ReactElemen ...

I need to figure out how to incorporate a specific feature into my personal list by leveraging Javascript

Looking at the list below, it's a simple one that allows users to add and remove items while also changing their order using buttons. However, I want to enhance this feature by removing the "up" button for the first item and the "down" button for the ...

Comprehending the fundamentals of Matrix Operations

I've been struggling with basic matrix transformations and can't seem to grasp it. There's a plethora of outdated code online and I'm unsure of what's current. Here's the snippet I've been working with: var matrixInitia ...

Displaying content on a webpage using PHP, AJAX, and HTML

Looking to update my current form setup. I have a basic Form below: <form action="" method="POST"> <input type="button" value="Generate Numbers" onclick="on_callPhp1()"/> </form> Accompanied by this javascript code: <script type="te ...

methods for retrieving nested JSON data from an API endpoint

My data has been exported in JSON format { "count":79, "stories":{ "23658975":{ "title":"NOMINATIVO", "description":"BUSDRAGHI PIERGIORGIO", "updated_at":"2013-06-16T18:55:56+02:00", "created_at":"2013-06-16T18:39:06+02:00", "du ...

A dynamic substitute for the Supersized slideshow option

I am in the process of updating my website and the final task on my to-do list is to replace the Supersized plugin with a more suitable alternative. The website is constructed using WordPress and I am utilizing jQuery. My goal is to find a fullscreen slid ...

Sending multipart/form-data with ajax in PHP returns as null

Recently, I encountered an issue with a form I have. It has the following attributes: method="post" and enctype="multipart/form-data" Every time I submit the form using AJAX $("#openTicketSubmit").click(function(){ var support_ticket_form_data = new ...

When using $dialogs.create on my website, a popup form appears with specific formatting limitations dictated by the defining code

When a user clicks a button on my website, a function in the controller is triggered. Here is the function that runs when the button is pressed: $scope.launch = function(idOfSpotOfInterest, schedOfSpotOfInterest){ var dlg = null; dlg = $dialogs. ...