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

Is it possible to determine the total number of pages in a PDF using PDF.js in

Is there a way to retrieve the total page count using pdf.js? <script type="text/javascript"> $( document ).ready(function() { var pdf = pdfjs.getDocument('sample.pdf'); alert(pdf.numPages); }); </script> ...

Guide to custom sorting and sub-sorting in AngularJS

If I have an array of objects like this: [ { name: 'test1', status: 'pending', date: 'Jan 17 2017 21:00:23' }, { name: 'test2', sta ...

Seeking assistance with formatting output for OpenCPU and igraph

Here is my adjacency array data: var g = [[10, 2], [15, 0], [18, 3], [19, 6], [20, 8.5], [25, 10], [30, 9], [35, 8], [40, 5], [45, 6], [50, 2.5]] The code I am using in OpenCPU is as follows: ocpu.call("centralization.closeness", {graph: g} ...

Choose particular content enclosed by two strings (across multiple lines)

Looking to use regex to extract specific text between two strings. For example: foo I have four toys bar //single line foo //multiline I have four toys bar foo I have three pets bar foo I have three pets bar How can I extract the text between & ...

Enhance the table using Django URL tag along with JQuery

I am currently working on a table that is being populated with user details and I would like to include a Django URL tag within the row, extracting the primary key in the process. Here is an example of what I am trying to achieve: function putTableData(re ...

Creating middleware to intercept responses for all AJAX requests

I'm working on creating a middleware that will manage all web user responses. Here's what I have so far: function ajaxResponseMiddleware(req, res, next) { var code = res.locals._code || 200; var data = res.locals._response; res.json(co ...

The concept of using the `map` method within a

Hi there, I could use some assistance with a tricky issue I'm facing. My current task involves rendering a cart object that includes product names, prices, and quantities. Each product can have its own set of product options stored as an array of ob ...

What is the best method to retrieve the value of a button that has been selected from a collection of buttons?

Within a functional component, there is an issue where the choose function keeps printing 'undefined'. I have utilized const [chosen, setchosen] = useState([]) within this code snippet. The full code has been correctly imported and the purpose of ...

Tips for incorporating ajax to load a new webpage into a specific div container

I have a website with two pages. I want to load Page 2 into a div on Page 1 and then display Page 2 when clicked on. I'm attempting to implement the following code, but it doesn't seem to be working for me. As a beginner, I apologize if this is a ...

JQuery Validation - Implementing real-time validation on button click instead of form submission

I am currently attempting to use JQuery Validation with WebForms/html. I have simplified the HTML code below, displaying only the necessary elements: <input id="txtEmail"/> <input id="txtTicketID"/> <a id="create" href="#">Create a new t ...

Having trouble with ui-router: "$injector:modulerr" - it seems an error has occurred

I recently started the tutorial AngularJS Tutorial: Learn to Build Modern Web Apps with Angular and Rails by Thinkster, but encountered a problem. After creating an inline template, I ended up with a blank page and an error message $injector:modulerr with ...

Having difficulty retrieving text data from a web URL using JavaScript

I am trying to extract text data from a web URL () My approach involved using two node modules. 1) Using crawler-Request it('Read Pdf Data using crawler',function(){ const crawler = require('crawler-request'); functio ...

Uncertainty about the integration of a JavaScript file into a PHP file

Having two PHP files where one is executed through a URL and makes AJAX calls to the second PHP file can present challenges. Sometimes, the AJAX results return HTML content with JavaScript events that do not work as expected. To solve this issue, I have in ...

Combining two asynchronous requests in AJAX

In the process of customizing the form-edit-account.php template, I have added ajax requests to enhance the functionality of the account settings form. The form allows users to modify their name, surname, age, and other details. While the ajax implementati ...

Implementing Express 4: The Correct Way to Serve Routes from External Files

Something about my Express 4 application is causing me frustration. Here's the configuration: routes/profile.js var express = require('express'); var router = express.Router(); router.get('/profile', function(req, res) { res.s ...

Tips for mocking constructors in AngularJS, specifically the Date() constructor

Trying to verify a function which receives millisSinceEpoch and gives back the time if it is today's date, otherwise it gives the date. getLocaleAbbreviatedDatetimeString: function(millisSinceEpoch) { var date = new Date(millisSinceEpoch); if (d ...

Having trouble with the npm Twitter API functionality?

I'm attempting to execute a simple stream using an example code snippet. Here is the code I am working with: var twit = require('twitter'); var twitter = new twit({ consumer_key: '[KEY]', consumer_secret: &ap ...

What steps should I take to incorporate Google sign-in on my website and gather user information efficiently?

I am looking to add the Google sign-in button to my website. While I am knowledgeable in HTML, PHP and JavaScript are not my strong suits. My goal is to allow users to sign in with their Google account and securely store their information on my database th ...

Select component with nested checkboxes for multilevel dropdown

I am interested in developing nested dropdowns with checkboxes, similar to the example shown in this image: Image 1 Is there a way to achieve this functionality using React? I have not been able to find any specific library that allows for this implement ...

Utilizing Node and Express to transform an array into a "Object" Map

For my latest project, I decided to build a web application using Node Express for the backend and Vue for the front end. While working on it, I encountered an issue where an array in an object was being converted to a map when sent to Express via jQuery. ...