Error: JSON parsing failed due to an unexpected character 'W' at the beginning

I am encountering an issue while sending a POST Request through the API in JavaScript. The method I have been using for multiple POST Requests is now displaying the error message: SyntaxError: Unexpected token W in JSON at position 0

Below is the snippet of my code:

function updateAlertSetting(data_json, callback){

var firebase_token = getCookie("firebase_token");
if(firebase_token===null){
    window.location.href="login.html";
    return;
}
var base_64_firebase_token = btoa(firebase_token);

console.log(typeof data_json);  
console.log(data_json);         

$.ajax(
    {
        type: 'POST',
        url: getApiURL(28),
        data: {
                "alertSetting_value": data_json.alertSetting_value,
                "alertSetting_name": data_json.alertSetting_name,
                "firebase_token": data_json.firebase_token
              },
        headers: { "Authorization": "Basic " + base_64_firebase_token },
        success : function(newData){
            callback(newData);
        },
        error: function (xhr,ajaxOptions,throwError){
            console.log(throwError);
            console.log("Error!!!");
        }
    }
);
}

Answer №1

I implemented the solution using the code below:

var xmlhttp;
    try{
        xmlhttp = new XMLHttpRequest();
    } catch (e){
        // For Internet Explorer Browsers
        try{
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                // Browser does not support AJAX  
                alert("Your browser is unsupported");
            }
        }
    }       
    if(xmlhttp){
        xmlhttp.onreadystatechange=function() {
            if (xmlhttp.readyState===4 && xmlhttp.status===200) {
                callback(xmlhttp.responseText);
            }
            if(xmlhttp.status === 404){
                alert("It couldn't connect to the server.");
            }               
        }
        xmlhttp.open("POST",getApiURL(28),true);
        xmlhttp.setRequestHeader("Authorization","Basic " + base_64_firebase_token);
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlhttp.send("alertSetting_value="+data_json.alertSetting_value+"&alertSetting_name="+data_json.alertSetting_name+"&firebase_token="+data_json.firebase_token);
    }

With these changes, the functionality is now working as expected. Many thanks to @jro for the help.

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

Using Javascript to parse a regular expression in a string

I am facing a challenge with a JavaScript string that contains contact information that needs to be filtered. For example, I want to mask any email or phone number in the message. I have attempted the following approach: function(filterMessage) { ...

Is there a way to incorporate a deletion feature within a list of items using JavaScript?

When adding a new item, I want to include a delete button next to it so I can easily remove the item by clicking on the button. However, I am having trouble figuring out how to implement this functionality using JavaScript. You can view my code snippet he ...

Error: 'error' is undefined

Error Alert: The code is encountering a ReferenceError, indicating that 'error' is not defined in the following snippet: app.post('/register', function(req, res) { var hash = bcrypt.hashSync(req.body.password, bcrypt.genSaltSync(10)) ...

The server response value is not appearing in Angular 5

It appears that my client is unable to capture the response data from the server and display it. Below is the code for my component: export class MyComponent implements OnInit { data: string; constructor(private myService: MyService) {} ngOnInit ...

Output the Partial View as a string within a Bootstrap Modal

Is there anyone who can help me? I am facing an issue with my View and Partial View (to be loaded in a Bootstrap modal). When I try to convert my partial view to a string, so it can be returned to my view, it comes back empty. However, if I add some tags ...

Ways to categorize by a particular date

const vehicleDetails = [ { "record_id": "2ff8212f-5ec9-4453-b1f3-91840a3fb152", "status_date_activity": { "On Rent": 1662021991000 } }, { "record_id": "c8c1 ...

Transferring information among PHP web pages using a list generated on-the-fly

I am working with a PHP code that dynamically generates a list within a form using data from a database: echo '<form name="List" action="checkList.php" method="post">'; while($rows=mysqli_fetch_array($sql)) { echo "<input type='pas ...

Is there a way to retrieve localStorage setItem after an hour has passed?

When the user clicks on the close icon, the notification screen disappears. How can I display the same screen to the user again after an hour? Please provide guidance. const [hideLearningMaterialClosed, setHideLearningMaterialClosed] = useState(false) ...

What is the reasoning behind the return type of void for Window.open()?

There is a difference in functionality between javascript and GWT in this scenario: var newWindow = window.open(...) In GWT (specifically version 1.5, not sure about later versions), the equivalent code does not work: Window window = Window.open("", "", ...

Tips for managing various modifications in input fields with just one function

I need to update the state object when data is entered into a form with 2 fields and submitted. Instead of creating a separate function for each input field, I want to handle the input changes in a more efficient way. Sample Code: import React, {Compone ...

Utilizing Vue CLI plugin to dynamically pass JS variables as props

I am currently using version 4.5 of the Vue CLI plugin. I have created a component that takes in a title as a prop. This component has been converted into a web component and added to an HTML webpage (which is not a Vue JS project) Now, I am attempting to ...

Troubleshooting: Why is my express-fileupload failing to upload images

I'm currently working on implementing a feature that allows users to upload a profile image for their profiles. I have the form set up the way I want it, but I keep encountering an error that says TypeError: Cannot read property 'profilePicUpload ...

What is the best way to ensure my fetchMovieDescription function is executed only after the story state has been updated?

I am facing a challenge with the fetchMovieDescription function. It is being called simultaneously with fetchBotReply instead of after my story state is updated. As a result, it generates a random image rather than using the one from the story result. impo ...

Exploring the characteristics of $scope elements generated by the $resource factory service within AngularJS

I need to access attributes of an object that originates from a $resource factory service (REST API). services.js: myApp.factory('userService', ['$resource', 'backendUrl', function($resource, backendUrl) { return $resource ...

Simulate a new Date object in Deno for testing purposes

Has anyone successfully implemented something similar to jest.spyOn(global, 'Date').mockImplementation(() => now); in Deno? I've searched through the Deno documentation for mock functionality available at this link, as well as explored t ...

Invoking PHP function within a specific class using Ajax

I am currently utilizing Zend Framework. My PHP class is structured as follows: FileName : AdminController.php Path : /admin/AdminController.php Ajax Function : function exportToExcel() { $.ajax({ url: "/admin/AdminController/testFunction", ty ...

The HTML Canvas arc function fails to properly align curves

UPDATE Upon further investigation, I've discovered that this problem only occurs in Chrome. Could it be a browser issue rather than a coding problem? I'm working on creating a circle with clickable sections using HTML5 Canvas. The circle itself ...

How can you apply filtering to a table using jQuery or AngularJS?

I am looking to implement a filtering system for my table. The table structure is as follows: name | date | agencyID test 2016-03-17 91282774 test 2016-03-18 27496321 My goal is to have a dropdown menu containing all the &apo ...

Connecting to a database using Vugen's Ajax TruClient feature

Recently, I've been experimenting with Ajax TruClient, but I'm struggling to find any functions that would enable me to connect to an Oracle database in order to retrieve information and compare it against the UI. Does anyone have any insights on ...

What is the process for generating an attribute in a system?

If I want to create an element using plain JavaScript, here is how I can do it: var btn = document.createElement('button'); btn.setAttribute('onClick', 'console.log(\'click\')'); document.body.appendChild( ...