After switching from jQuery to pure JavaScript, the code is now up and

After initially coding in jQuery + AJAX, I attempted to rewrite it in vanilla JavaScript. However, the code is not functioning as expected now. Can someone help me identify the mistake causing nothing to display when I run it through the server? I have checked the console for errors but found none.

Original code in jQuery:

$(document).ready(function(){

    findteacher = function() {
        var file = "course.php?course="+ $("#course").val();
        $.ajax({
            type: "GET",
            url: file,
            datatype: "text",
            success: function(response) {
                var file2 = response.split(",");
                $("#courseInfo").html("The course: " + file2[0] + " Taught by: " + file2[1]);
            }
        });
    }

    clear = function() {
        $("#courseInfo").html("");
    };

    $("#course").click(clear);
    $("#go").click(findteacher);
});

Rewritten code in JavaScript:

function findteacher () {

    var file = "course.php" + document.getElementById('course');

    function callAjax(){
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function(){
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
                document.getElementById('courseInfo').innerHTML =   xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET", file, true);
        xmlhttp.send(null);

        var file2 = callAjax.split(",");
        document.getElementById('courseInfo').text("The course: " + file2[0] + " Taught by: " + file2[1]);
    }
    document.getElementById('go').onclick(findteacher)
}   
window.onload = findteacher;

Answer â„–1

Ensure you include ?course= in your file in order to retrieve the value of the course element correctly. Avoid using callAjax.split(",") as it is a function, not a string—instead, utilize xmlhttp.responseText.split(",") within the onreadystatechange function. Remember that onclick is a property assignment, not a method call, so change from .onclick(findteacher) to onclick = findteacher; this should be set up once when the page loads, not inside the function.

function findteacher () {

    var file = "course.php?course=" + document.getElementById('course').value;

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
            var file2 = xmlhttp.responseText.split(",");
            document.getElementById('courseInfo').innerHTML = "The course: " + file2[0] + " Taught by: " + file2[1];
        }
    }
    xmlhttp.open("GET", file, true);
    xmlhttp.send(null);
}   

function clear () {
    document.getElementById('courseInfo').innerHTML = '';
}

window.onload = function() {
    document.getElementById('go').onclick = findteacher;
    document.getElementById('course').onclick = clear;
}

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

Custom options in MUI Autocomplete are not displaying the selected option

I am currently implementing MUI v5's Autocomplete for a dropdown feature on my website. Within this dropdown, I have options that include both a title and an id. My goal is to store the selected option's id in the state while also updating the d ...

choosing between different options within Angular reactive forms

I am attempting to create a select element with one option for each item in my classes array. Here is the TypeScript file: @Component({ selector: 'app-create-deck', templateUrl: './create-deck.component.html', styleUrls: [' ...

Disable the use of componentWillUnmount in case of an incomplete form

I have implemented a form using redux-form and I am trying to set up a scenario where if any of the form's inputs have content and the user tries to navigate away from the page, a prompt should appear. My goal is to prevent the page from being unmoun ...

Transitioning the style code from inline to the head of the document disrupts the straightforward JavaScript intended to

As I delve into the world of web development, I encountered a simple issue that has been causing me frustration for the past hour. It involves code to display the border color of a div element using an alert. The code works perfectly fine when the style is ...

The cross-origin resource sharing (CORS) functionality is functioning properly on the

I've encountered an unusual problem with express cors. While my Cors configuration works perfectly on localhost, it fails to function in the production environment. Every time I encounter the same error. Failed to load : Response to preflight r ...

Using ThreeJS to project a mouse click onto the XZ plane

I am currently working on implementing offline routing in a 3D map within a ThreeJS scene. My goal is to allow the user to click on a point and have a cube navigate to that point. While the navigation functionality is working correctly, I am facing an issu ...

Adding design to distinct element after clicking a button

Struggling with a JS/Jquery issue on my portfolio website, I admit that I am still just an average programmer. My portfolio website has five buttons, each representing a different project. For each project, there is a corresponding text description and an ...

Contrast between v-for arrangements

Would anyone be able to clarify the distinction between these two v-for structures? <li v-for="item in items" :key="item"> </li> and <li v-for="(item, i) in items" :key="i"> </li> ...

The AngularJS Navbar is Bootstrapped

I'm currently working on a project where I need to make a bootstrap navbar show and hide html elements based on data retrieved from an angular controller. Below is the jade code snippet: div.navbar.navbar-fixed-top div.navbar-inner div.c ...

Reset checkboxes in Material UI data grid

Currently, I am immersed in a React Js project that involves various tabs, each containing a unique data grid table with rows featuring checkboxes. Issue: Whenever I select a row from Table 1 and navigate to Tab 2 before returning to Tab 1, the checkboxes ...

Unable to see Bootstrap 5.2 Modals in action with documentation demo

Here is an example that I copied and pasted from the documentation on https://getbootstrap.com/docs/5.2/components/modal/: <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-bs-toggle="modal&q ...

Can you guide me on creating a post and get request using ReactJS, Axios, and Mailchimp?

I am brand new to ReactJS and I am currently working on developing an app that requires integration with Mailchimp to allow users to subscribe to a newsletter. I am looking for assistance on making a request using axios. Where should I input my API key? ...

Tips on how to navigate to the end of a div that has been created through ng-repeat in Angular JS with the

Here is the template code I am working with: <div class="chatbox" id="mailBody" > <div class="panel-body" ng-repeat="mail in mails"> <div class="m-b-none" ng-if="mail.inboxMessageType == 1"> <a href class="pull-left ...

Troubleshooting Coffeescript Jasmine-Node Tests in Webstorm/Intellij

Using node-jasmine 2 beta4 and writing in Coffeescript, I have successfully set up my tests to run in Intellij 13.1 by configuring the following Run Settings: Node interpreter: /usr/local/bin/node Working Dir: [Project Directory] Javascript File: node_mo ...

An issue with jQuery's :not selector and hash symbol syntax

I encountered a syntax error that is quite charming. It appears when attempting to select all anchor tags without an href attribute containing a placeholder URL, such as href="#". Here are the attempts I have made: $("a:not(href='#')"); // cha ...

If the next element in the sequence happens to be the final element, then conceal a separate

Continue pressing the downward button consistently on until you reach the bottom. The down arrow should disappear slightly before reaching the end. Is there a way to achieve this using the code provided below? I'm new at this, but I believe I need t ...

Differences between const and let when utilizing the require function

With io.js now offering ES6 support, you can finally take advantage of the powerful const and let keywords. While let is seen as the successor to var with added capabilities, what about const? We all know what "constant" means, but when is it best practice ...

Tips for utilizing JavaScript to upload a file in Webform and make it accessible in the global PHP variable $_FILES

I'm feeling a little overwhelmed and frustrated. I've come across a bunch of solutions, but none of them seem to work fully or correctly!? My task is to create an HTML form that allows users to upload one or more files to the web server using AJ ...

Error in Chart.jsx: Unable to retrieve the length property of an undefined object in the COVID-19 Tracker App

INQUIRY Greetings, I am in need of assistance to identify an error that is perplexing me. The source of this code can be traced back to a tutorial on creating a covid tracker available on YouTube. While attempting to implement the chart feature, I encounte ...

The system is unable to locate the module at 'C:UsersSanjaiAppDataRoaming pm ode_modulesprotractorinprotractor'. This error originates from internal/modules/cjs/loader.js at line 960

After running "protractor conf.js" without any issues, I decided to install protractor globally using the command "npm install -g protractor". However, after installing protractor globally, I encountered the following error message: internal/modules/cjs/lo ...