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

Transform the componentDidUpdate method that uses prevProps into a custom hook integrated with Redux

Trying to convert a life cycle method into a hook is not working as expected. When the component mounted, if the user ID exists in local storage, the user is connected and their name is displayed in the navbar. If they disconnect and reconnect, their name ...

Is there a way to use HTML and CSS to switch the style of a dynamic decimal number to either Roman numerals or Katakana characters within a specified HTML element, such as a tag, div

I've searched everywhere but only found guides on list styling and counter styling in CSS that didn't work out. So, for example, I have a number inside an HTML tag that is changed dynamically using Vue Watch. I want to display the number in upper ...

Delete a filename in Internet Explorer with the power of JavaScript and jQuery

In my attempts to clear the file input field in IE using $('#files').val('');, I found that it was not effective. $('#uploadimgdiv').html(''); var fil1 = document.getElementById("files"); $('#fil1').val(&a ...

Error: Uncaught TypeError - Unable to assign a value to the 'status' property

Hello everyone, I am currently facing an issue with validating the response from my server using Axios in VueJS. axios.post('/login', { email: this.email, password: this.password }).then(response => { if (response.status == 200) { $ ...

Avoid mutating the prop directly and instead, utilize a data or computed property that is based on the value of the prop. The prop that is being mutated in this case is

Help me understand this issue that Vue is displaying, I am not sure what is going on. This is my progress element: <el-progress :percentage="percentCompleted" v-show="uploadingVideo"></el-progress> data() { return{ percentCompleted: 0 ...

Tips for highlighting HTML syntax within JavaScript strings in Sublime Text

Is there a Sublime package available for syntax highlighting HTML within JavaScript strings specifically? (Please note that the inquiry pertains to highlighting HTML within JS strings only, not general syntax highlighting.) Currently, I am developing Ang ...

Exploring the function of variables in VueJS

I'm facing a tricky issue with VueJS as I am still getting acquainted with it. My objective is to access and modify variables within the data function, but so far, I haven't been successful. The problematic line: console.log('item: ' ...

Calculating the sum of values in a JSON array using a specific parameter in Typescript

A flat JSON array contains repetitive identifier, categoryId, and category: data: [ { "identifier": "data", "categoryId": "1", "category": "Baked goods", "product": "Aunt Hattie's", "price": "375" } ...

React JS - Breaking down the distinction between PublicTheme and PublicTheme

In my React project, I am currently working on creating the admin dashboard and designing the UI area for user interaction. I have encountered an issue where I am unable to separate the admin theme from the PublicTheme. Even when navigating to "/admin/lo ...

The Angular Google Maps Directive zooms in too much after the "place_changed" event has fired

Currently, I am developing a store locator app for DHL accessible at storefinder.hashfff.com/app/index.html For this project, I decided to utilize the angular-google-maps library for its features. However, in hindsight, working directly with the Google Ma ...

AJAX code fetching dynamic content without relying on file loading

When I load my program, the dynamic code does not appear on the page until I reload it again. I attempted to use the onload event in the body to load content from an XML file using AJAX, but it only works after closing and reopening the program, not dynam ...

How to build custom middleware with parameters in Node.js

I'm working on creating a middleware in nodejs for access levels, and I've written the following middleware: class AccessUser extends middlware { async AccessUser(access,req, res, next) { const getTokenFrom = (req) => { const autho ...

Obtain data attributes using JQuery's click event handler

I'm facing an issue with a div structure setup as follows: <div class='bar'> <div class='contents'> <div class='element' data-big='join'>JOIN ME</div> <div class=& ...

Tips for returning JSON data using AJAX

When working with native JS, I am familiar with using AJAX to display the output from PHP/mySql that is not Json Encoded in the element "some_id" like this: <script> function addItem(value) { xmlhttp = new XMLHttpRequest(); xmlhttp.onrea ...

Tips for eliminating double quotes from an input string

I am currently developing an input for a website that will generate a div tag along with its necessary child elements to ensure the website functions correctly. I have a couple of key questions regarding this setup: <!DOCTYPE html> <html> < ...

Obtain the ID of element 1 by clicking on element 2 using JQuery

In the world of javascript/jquery, When button1 is clicked, we can get its id like this: var button1id = $(this).attr("id"); If button2 is clicked, how do we retrieve button1's id? This brings us to the question: How does button2 access the i ...

How can you replicate a mouseover event using Selenium or JavaScript?

I have recently been working on a task involving web UI automation using Selenium, Javascript and SeLion. My goal is to capture a screenshot of a scenario similar to the Google homepage, specifically focusing on the "Search by voice" feature when hovering ...

Issue: Unable to open port (GetCommState) : Error code 1 not recognized - Utilizing Nodejs, express, SerialPort

I am currently attempting to establish a connection between a fiscal printer with serial input and nodejs. I am utilizing the SerialPort module, but encountering difficulty in establishing the connection. The console is displaying the following error messa ...

Is Jade monitoring *.jade files?

Though I am not sure of the internal workings of Jade, my best guess is that it compiles each template file once and then employs a compiled and cached version for subsequent HTTP requests. One intriguing observation I have made while running my Express a ...

Executing Promises in an Array through JavaScript

LIVE DEMO Here is a function provided: function isGood(number) { var defer = $q.defer(); $timeout(function() { if (<some condition on number>) { defer.resolve(); } else { defer.reject(); } }, 100); return defer.pro ...