The JavaScript Ajax request appears to be malfunctioning in both Firefox and Google Chrome, however, it seems to be functioning properly

I am currently using JavaScript to make an Ajax request to communicate with an Arduino webserver and dynamically update the content on a webpage.

While this functionality has been working smoothly in Safari, I have encountered issues when trying to use it in Firefox and Google Chrome. Despite having verified that the requests and responses are being received in the debugger consoles, it appears that there may be a problem with parsing the response into an array?

Below is the code snippet:

function GetSwitchState()
{
    nocache = "&nocache=" + Math.random() * 1000000;
    var request = new XMLHttpRequest();
    request.onreadystatechange = function()
    {
        if (this.readyState == 4)  {
            if (this.status == 200) {
                if (this.responseText != null) {
                    var response = this.responseText;
                    var comma = ",";
                    var inputArray = response.split(comma);
                    var green = inputArray[0];
                    var red = inputArray[1];
                    var fault = inputArray[2];
                    var counter = inputArray[3];
                    document.getElementById('green').innerHTML = green;
                    document.getElementById("red").innerHTML = red;
                    document.getElementById("status").innerHTML = fault;
                    document.getElementById("cars").innerHTML = counter;
                }
            }
        }
    }
    request.open("GET", "url" + nocache, true);
    request.send(null);
    setTimeout('GetSwitchState()', 1000);
}

The response from the Arduino webserver consists of four comma-separated values.

Answer №1

After some investigation, it seems that the main issue was overcoming a hurdle related to the

{
            if (this.readyState == 4) {
                if (this.status == 200) {

conditions. I managed to progress by modifying it to:

{  
     if(response.readState == 4) {

This adjustment allowed me to move beyond that particular point in Firefox. In order to change the status from 0 to 200, I had to adjust the response header on the arduino side to include:

Access-Control-Allow-Origin: *

This alteration enabled Cross Origin Domain Requests in FireFox. Once these modifications were made, the code ran smoothly, highlighting that my initial assumption veered off course. Appreciate the assistance!

Answer №2

My day today was pretty much a repeat of yesterday!

While working on an Ajax request to a PHP file, I learned the importance of specifying the return datatype as "json." In the PHP file, I structured my return values like so:

return json_encode(array(
    'success' => false,
    'error' => $_POST['password_hashed']
));

I utilized jQuery to execute the request, here's a snippet:

$.ajax({
    type: 'POST',
    url: 'script.php',
    data: 'password_hashed=' + hex_sha512(str_password) + '&email=' + str_email, //Clientside password hashing
    cache: false,
    dataType: 'json',
    success: function(value){
    //Ajax successfully ran
        alert(value.success + '_' + value.error); //=false_[hash]
    },
    error: function(){
    //Ajax error occured -> Display error message in specified element
        alert('error with request');
    }
});

I'm still new to Ajax, but experimenting with it has been quite interesting.

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

prismjs plugin for highlighting code displays code in a horizontal format

If you're looking for a way to showcase source code on your website with highlighted syntax, prismjs.com may be just what you need. It offers a similar style to monokai... However, I've encountered an issue where the plugin displays my code in a ...

Is the ID "nodeName" specifically designated as reserved in the HTML5 language specifications?

I have an element with the following id: <span id="nodeName"></span> In my HTML code. Then, when using jQuery to do the following: $("#nodeName").html("someString"); I am getting an error in the console that says: Uncaught TypeError: Objec ...

How to perfectly position an image within a fixed full screen container

When you click on a thumbnail image, a full-screen overlay with a larger version of the image will be triggered using JavaScript. To ensure that the image is centered and resized inside the black overlay when the browser window size changes, I attempted t ...

Can the presence of buttons and links improve mobile responsiveness?

I can't help but wonder about this. Is it user-friendly to create a div that looks like a button and has a 'click' event attached to it? Will all mobile browsers handle it accurately and always trigger the event when the div is clicked? In t ...

Input field for postal code containing only numbers (maximum 5 digits) in Angular version 4/5

I am struggling with creating an input field that accepts numbers. If I use type="text", I can only type 5 characters of alphanumeric data, but if I use type="number", it allows any number input without limiting it to just 5 numbers. Thank you in advance f ...

Disappearing act: The vanishing act of the Bootstrap 4 Smart Scroll Mobile

Utilizing the Smart Scroll feature from in Bootstrap has been successful on desktop, but issues arise on mobile devices. When scrolling down and returning to the top, the navbar experiences glitches by hiding again. Attempting solutions from Bootstrap 4 S ...

Invalid extra parameters in the $.ajax function

I am attempting to access a web service in order to retrieve some data. I must include this URL using the GET method: http://localhost/ecosat/ws/api.php?t=vw_motorista However, when I check in Chrome Developer Tools, the link is shown as: http://localho ...

Transforming a cURL command into an HTTP POST request in Angular 2

I am struggling to convert this cURL command into an angular 2 post request curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -H "Authorization: Basic cGJob2xlOmlJelVNR3o4" -H "Origin: http://localhost:4200/form" -H "Postman-Token: fbf7ed ...

What is the solution to preventing Angular 1.3 ngMessages from affecting the size of my form?

Hey there, I'm diving into front-end design for the first time. My issue is with a form that I want to use ng-messages for validation error messages. Currently, my form's size changes depending on whether there are errors displayed or not, and it ...

Oops! The Route.get() function in Node.js is throwing an error because it's expecting a callback function, but it received

Currently, I am learning how to create a web music admin panel where users can upload MP3 files. However, I have encountered the following errors: Error: Route.get() requires a callback function but received an [object Undefined] at Route. [as get] (C:&bso ...

I have a dynamic blog site that is generated on the fly using Ajax, making the content unsearchable

I have a blog website that is created dynamically using Ajax (XMLHttpRequest) and the HTML History API. One issue I am facing is that my content is not searchable by search engines like Googlebot. I know that Google is now able to analyze such sites, but w ...

The v-model in Vue does not function correctly when used with a single index within an array

I am encountering a situation with a series of input fields, including a checkbox and a dropdown button in each row. Additionally, there is a button to add a new row of inputs. When the checkbox is checked, it should disable the dropdown menu and make it ...

Exploring the Difference Between $onChanges and $onInit in Angular Components

What sets apart the use of Controller1 compared to Controller2? angular.module('app', []) .component('foo', { templateUrl: 'foo.html', bindings: { user: '<', }, controller: Controller1, ...

Send JSON data using jQuery and process it in Node.js

Looking for guidance on how to send json form data from JavaScript by clicking the submit button and then receiving that json data on a Node.js server. My attempts so far have only resulted in printing '{} ' on the Node.js server terminal Below ...

I'm having an issue with my NextJS timer where it doesn't stop and ends up going into negative numbers. Any

Here is the code snippet for my timer component. It fetches the 'createdAt' prop from the database and functions correctly. However, I have encountered an issue where the timer does not stop at 0 but continues running indefinitely. I attempted to ...

Modifying background with JavaScript and AJAX技术

I currently have a table structured like the following; <table style="width: 100%; border: solid 1px #666600; min-width: 800px" cellpadding="0" cellspacing="0"> <tr> <td id="aaa">&nbsp;</td> ... Using jQuery's ajax functi ...

Multer failing to generate file during request process

My current setup involves a router and multer middleware, but I'm facing an issue where the file requested is not being created. As a result, req.file always remains undefined. const multer = require('multer'); let storage = multe ...

What steps can I take to trigger a 404 error instead of a cast error?

My route is defined as /mysafe/idofthemodel. When the idofthemodel is not found, it throws a cast error Cast to ObjectId failed for value "something" (type string) at path "_id" for model "modelname". Instead of this error, I ...

Ensure that the date range picker consistently shows dates in a sequential order

Currently utilizing the vuetify date range picker component https://i.stack.imgur.com/s5s19.png At this moment, it is showcasing https://i.stack.imgur.com/GgTgP.png I am looking to enforce a specific display format, always showing the lesser date first ...

``Are you experiencing trouble with form fields not being marked as dirty when submitting? This issue can be solved with React-H

Hey there, team! Our usual practice is to validate the input when a user touches it and display an error message. However, when the user clicks submit, all fields should be marked as dirty and any error messages should be visible. Unfortunately, this isn&a ...