The request for JSON parsing encountered a failed attempt, resulting in an error while trying to parse the JSON


var userData = {
    "emailAddress": document.getElementById('emailAddress').value,
    "password": document.getElementById('password').value
}

var userDataString = JSON.stringify(userData);
alert(userDataString);

var url = "url";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        alert('connected..');
    }
};
xmlhttp.open("POST", url, true);
xmlhttp.send(userDataString);

$.ajax({
    type: "POST",
    URL: "login.php",
    contentType: "application/json",
    CrossDomain: true,
    data: JSON.stringify(userData),
    dataType: 'json',
    success: function(data) {

        alert("success");
        var response = jQuery.parseJSON(data);
        alert(response);

I have a login form that contains user ID and password. I need to convert the entered information into JSON and send it to the server. However, I'm getting a JSON parsing error. I've been trying for hours but can't find the mistake. Can you please help me identify where I'm going wrong?

Answer №1

Without focusing on the XHR code, let's take a closer look at the ajax call:

  1. It's important to note that there isn't a CrossDomain option present. However, there is a crossDomain option available. Remember, JavaScript is case-sensitive. It might be best to exclude this option altogether, especially considering the URL you are using.

  2. By specifying that the data being returned is in JSON format, jQuery will automatically parse it for you and provide the parsed data as the data argument in your success function. Avoid calling JSON.parse on it, as this step has already been taken care of by jQuery. The data variable will contain the parsed information.

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

"Encountered an issue: Error occurred while attempting to synchronize Protractor with the page" during the execution of Protractor tests

I am facing an issue while running Protractor tests on a web application that includes both Angular and non-angular elements. Here is the structure of my code: describe("Test Name", function() { it("Test case", function() { // starting with steps on ...

Mixing strings with missing slashes in links

console.log(mylink) When using the console to log mylink, the expected result is a normal link like http://example.com/something.jpg. I tried concatenating it as shown below: var html = '<div id="head" style="background:linear-gradient(rgba(0, 0 ...

Guide on how to load just the content section upon clicking the submit button

Here is an example of my code: <html> <head> <title>Test Loading</title> </head> <body> <div id="header"> This is header </div> <div id="navigation" ...

Are RSS and Atom the Same? Challenges Encountered in Retrieving and Parsing

$.ajax({ type: 'GET', url : 'http://examplewebsite.com/feeds/items/123456.atom', dataType : 'xml', error: function(xhr) { console.log('Failed to parse feed'); }, ...

Error 500: Issue with CascadingDropDownExtender detected in AJAX Request

Currently, I am troubleshooting an issue with the CascadingDropDownExtender in AJAX. Upon running the sample code, I encountered a problem where I am receiving a "[Method Error 500]" message in the Dropdowns. In my attempt to resolve this, I created a We ...

Tips for preventing my component from being duplicated during the development process

I found a helpful guide on creating a JavaScript calendar in React that I am currently following. After implementing the code, I successfully have a functional calendar UI as shown below: // https://medium.com/@nitinpatel_20236/challenge-of-building-a-cal ...

Traveling within a layered object

Currently, I'm working with an object and iterating through it to retrieve outputs as shown below: var obj = { "first": { "Bob": { "1": "foo", "2": "bar" }, "Jim": { "1": "baz" } }, "second": { "Bob": { ...

Generated Form Data Automatically

Seeking advice on achieving a specific functionality in ASP.NET Web Form that is similar to the AutocompleteExtender, but requires more flexibility. Here is what I aim to accomplish: There are 2 TextBox fields on the form: CompanyName and CompanyRef (a u ...

Encountering a tucked-away issue with the Safari scroll bar?

Encountered an interesting bug where users are unable to scroll down a text nested inside a div. This issue seems to be isolated to Safari, as it doesn't occur in other browsers. I have prepared a sample file to demonstrate the bug and would apprecia ...

Please refrain from utilizing MUI - useGridRootProps outside of the DataGrid/DataGridPro component

When we click on "Filter" in the context menu of our DataGrid, we encounter this error. We are working on implementing a component hierarchy for the DataGrid as follows: MigrationJobTable.tsx: return ( <div data-testid='migrationJobTa ...

NGRX Store: Unable to modify the immutable property '18' of the object '[object Array]'

While attempting to set up an ngrx store, I encountered 7 errors. Error Messages: TypeError: Cannot assign to read only property '18' of object '[object Array]' | TypeError: Cannot assign to read only property 'incompleteFirstPass ...

Most effective method for sending information from an HTTP server to a browser client

What is the most effective method for transferring data from the server side to the client when the client is a web browser? The server side is developed in Java, while the client side uses HTML, JavaScript, and AJAX. The communication protocol being uti ...

When utilizing botocore.response.StreamingBody, encountering a JSONDecodeError may occur

I have encountered an issue while trying to load a payload returned by a lambda invocation, resulting in a JSONDecodeError. Below is the lambda code snippet that I am working with: from datetime import datetime metadata={} metadata["execution_info&quo ...

Dynamic properties in JQuery

Here is the HTML DOM element I have... <input type="text" style="width: 200px;" id="input1"/> I want to make sure it stores date values. How can I specify that in the DOM element? Please provide your suggestions. Thanks! ...

A simple method for bulk editing in Angular UI Grid

Is there a way to enable mass editing in Angular UI Grid by allowing all rows to show editable input fields at once, rather than just one at a time? I have searched online for a solution without success and am now turning to this forum for help. If anyone ...

reactjs implementation of a virtualized list

Recently, I stumbled upon the React-window library and found it to be incredibly useful. Intrigued by how it was built, I decided to try my hand at creating my own virtualized list. However, I encountered an issue where the list could only scroll up to it ...

PHP Foreach Loop doesn't execute JavaScript Sum Function as expected

Currently, I have a JavaScript function implemented that utilizes the IDs of 3 textboxes to retrieve their numeric values, sum them together, and display the result in the fourth textbox. In addition, I am fetching a list of individuals from my database an ...

Utilizing AngularJS to dynamically display content based on specific grandson JSON property

My application currently contains the following JSON data: { "Success":true, "Error":null, "Data":{ "VersionId":1, "SecretaryId":1, "SecretaryName":"Foo", "Status":1, "Schools":[ { "Schoo ...

Choose key and value pairs in AngularJS

Currently, I am retrieving JSON values from an HTTP service for each ID and attempting to create a dropdown with a list of names and IDs as keys to store. Below is the HTML code snippet: <select> <option ng-repeat="(key, value) in data" value="{{ ...

Ways to execute the pdf.js node demonstrations?

I've been attempting to run the pdf.js node examples, specifically getinfo.js. Unfortunately, I encountered an issue that resulted in the following error: C:\Repositories\pdf.js>node getinfo.js node:internal/modules/cjs/loader:1080 thro ...