Retrieving JSON Data Using JavaScript from a Web Service

After clicking the button in my HTML file to execute the JavaScript, I encounter this error:

myapp.azurewebsites.net/:1 Uncaught SyntaxError: Unexpected end of JSON input
        at JSON.parse (<anonymous>)
    

Here is the JS code:

function ajaxFunction() {
        console.log("ajaxFunction()");
        var ajaxRequest;
        try {
            ajaxRequest = new XMLHttpRequest();
        } catch(e) {
            try {
                ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch(e) {
                try {
                    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch(e) {
                    alert("Broken");
                    return false;
                }
            }
        }
    
        ajaxRequest.onreadystatechange = function () {
            if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
    
                var form = document.getElementById("myform");
                var titleParagraph = document.getElementById("home_title");
                titleParagraph.innerHTML = ajaxRequest.responseText;
    
                form.style.display = "none";
    
            }
        } 
    
        var value1 = document.getElementById("field1").value;
        var value2 = document.getElementById("field2").value;
        var url = "https://webapp.azurewebsites.net/users/" + value1 + "/" + value2;
        console.log(url);
    
        // Call sign in web service
    
        ajaxRequest.open("GET", url, true);
        ajaxRequest.send(null);
        var jsonResponse = JSON.parse(ajaxRequest.responseText);
        console.log("RESPONSE:");
        console.log(jsonResponse);
    }
    

The response JSON from :

[{"ID":1,"UserName":"username","FirstName":"first","LastName":"last","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0d68756c607d61684d68756c607d6168236e6260">[email protected]</a>"}]
    

Answer №1

ajaxRequest.open("GET", url, true);

The third argument in the ajaxRequest function determines whether the request is asynchronous. Based on your code, it appears that it should be set to true for asynchronous requests.

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

The directive in an ionicModal is executed first, even before the controller is fully loaded

I recently encountered a challenge with a $ionicModal containing a directive called <scrap-link-cards>, which accepts a two-way binding scope object. This directive is included in the $ionicModal template: <scrap-link-cards datasource=(updates.up ...

Pressing the Button Increases the Counter, However the Counter Resets After

My goal is to create a basic counter with increment and reset buttons. When I click on the increment button, the counter properly goes from 0 to 1 (I can confirm this by checking the console log in Chrome). The issue arises when, after incrementing, the c ...

Setting up and customizing Express with Angular

Currently working on a straightforward Angular/Express todo-list app, I encountered some difficulties. As the project is still in progress, after running the code on localhost:3000, I noticed that {{ thing }} was displayed literally on the webpage. The di ...

Storing JSON data in SharedPrefrence and accessing it offline can be easily done by following a

How can JSON be saved in shared preferences and retrieved locally while also updating daily? The shared preferences need to check online for updated content. What is the implementation method for this? public class VOTD_Data extends AsyncTask { private S ...

Fetching data from an uploaded file and transmitting it to a specified URL

<? if(isset($_POST["submit"])) { $f_name = $_FILES["filetoupload"]["name"]; $f_tmp = $_FILES["filetoupload"]["tmp_name"]; $store = "uploads/".$f_name; if(move_uploaded_file($f_tmp,$store)) echo "file uploaded successfully"; echo"<br>"; ...

When using Google Maps Autocomplete, always make sure to input the full state name instead of just the state

Utilizing the Google Maps autocomplete API, we have enabled our customers to search for locations in the format of city, state, country. The functionality is effective overall, but a recurring issue arises when searching for cities, such as 'Toronto&a ...

The table disappears when there is no data available in the database

One of my challenges involves a table that displays data retrieved from a database. The code for this is as follows: <table class="table table-hover table-bordered" style="width:300px" id="contact"> <tbody data-bind="foreach:items"> ...

The error message states that the provided callback is not a valid function -

I seem to be encountering an issue with the code snippet below, which is part of a wrapper for the Pipl api: The main function here performs a get request and then retrieves information from the API Any assistance in resolving this error would be greatly ...

Utilize JSON Arrays within a JSON structure when programming in Java

Within my Array list are integer values ranging from 2 to 6, and I am checking if each number is odd or even using the code snippet below: JSONObject outerObject = new JSONObject(); JSONArray outerArray = new JSONArray(); JSONObject [] innerObject = new J ...

Error: Exceeded the maximum call stack size - What causes this and how can it be prevented?

I am currently utilizing standard JavaScript. As the title implies, I am encountering a RangeError and I'm unsure of how to prevent it. The issue at hand is that I shouldn't be receiving this error, and in reality, if I refresh the page there&ap ...

Error: Attempted to search for 'height' using the 'in' operator in an undefined variable

I came across the following code snippet: $('.p1').click(function(){ var num = 10; var count = 0; var intv = setInterval(anim,800); function anim(){ count++; num--; ...

The NoUiSlider had already been initialized

Currently, I am facing an issue when trying to incorporate noUiSlider with Angular JS. I have a directive that contains 4 sliders and I intend to display this directive on 2 different pages. However, each time I switch between the pages, an error occurs st ...

Is there a way to prompt Vue Router to refresh my page while attempting to navigate within the present location?

I currently have my project structured in the following way: Views Home.vue Classroom.vue App.vue Within the Home.vue file, I display the content and a login form. Essentially, users must submit their login information, and if correct, the isAuth vari ...

Calculation of percentages with automatic comma insertion

Having an issue with percentage computation when combined with an auto-comma function. For example, if I input 100,000 and a percentage of 10%, the calculation results in 110 instead of the correct value. Not sure how to properly integrate these functions. ...

A guide on accessing POST values from serializeArray in PHP

Recently, I came across a new method called serializeArray() and decided to give it a try. // Using ajax var formData = $("#form :input").serializeArray(); post_data = {'action': 'process', 'data': formData }; $.ajax({.....et ...

Resolving Unrecognized Vue Variable in PhpStorm

I'm encountering an issue with my Vue script in PhpStorm. Despite setting the variable redirect_to, I am getting an Unresolved variable syntax error during debugging. Please refer to the image below for further information. How can I resolve this prob ...

Creating a Dynamic Select Form using PHP, MySQL, and Ajax

Apologies if the title is not clear, but here is my issue. The Problem: I have a dynamic select element that gets its options from an ajax call. I have a function that triggers when the first select element changes. This works well when the user manually ...

Having trouble retrieving the JSON data received from the backend

After making an AJAX request, I receive a response which is then saved to a data variable. This is the controller logic: def retrieve data = params[:data] @question = Question.find_by(id: params[:question_id]) @choices = @question.choices results ...

Learn the steps to modify or remove table information from a database using a webpage

Hey there! I'm currently working on an Ajax jQuery function that displays table data, like in the image provided. I would like to add an option for users to edit and delete the table data, with the changes reflecting in the database. It's worth n ...

Utilize Jquery to hide radio buttons, while allowing users to click on an image to display a larger version

My current HTML structure is restricted to SAAS, so I only have control over jQuery implementation. https://i.stack.imgur.com/OHB9K.jpg I am attempting to achieve a similar layout as shown in the image below. The main issue lies in how to (1) conceal ...