Leveraging XMLHttpRequest in Mozilla Extension creation

I'm encountering some issues when trying to call a PHP file using Ajax in my Mozilla Extension. Both the JavaScript (Ajax) and PHP files are located in the directory /myextension/content. Here is the function I use to make the Ajax call:


function ajaxFunction(){
    var req = new XMLHttpRequest();
    req.open('GET', 'myphp.php', true);
    req.onreadystatechange = function (aEvt) {
      if (req.readyState == 4) {
         if(req.status == 200)
          alert(req.responseText);
         else
          alert("Error\n");
      }
    };
    req.send(null);
}

And this is how my PHP file looks like:


<? php 
echo "Server Received with thanks!";
?>

However, when I try to run the code, I keep getting an "alert("Error\n");". Can anyone spot what I might be doing wrong?

Answer №1

Here is a properly structured Ajax script specifically for Firefox:

var URL="http://yourwebsite.com/Process.php?value=Example";
var xhr = null;

try 
{
    xhr = new XMLHttpRequest();
}
catch(e)
{return;}

xhr.onreadystatechange=function()
{
    if ((xhr.readyState == 4 || xhr.readyState == "complete") && xhr.status == 200)
    {
        //Add your success logic here
    }
    else if (xhr.status == 404)
    {
        //Handle errors
    }
    else 
    {
        //Code to execute while waiting
    }
}

xhr.open("GET", URL, true);
xhr.send(null);

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

Retrieve the most recent version of the document stored in MongoDB

Is there a way to retrieve the _id (the Mongo ObjectID) of an updated document without having to find it by newData/oldData? I attempted the following: ... collection.update(oldData, newData, function(err, doc) { console.log(docs); // This prints "1" ...

Word.js alternative for document files

I'm on the lookout for a JavaScript library that can handle Word Documents (.doc and .docx) like pdf.js. Any recommendations? UPDATE: Just discovered an intriguing library called DOCX.js, but I'm in search of something with a bit more sophistic ...

Is there a way for me to verify if I have already made an AJAX data request

I have an image gallery with thumbnails. When a user clicks on a thumbnail, an ajax request is fired. I want to prevent the ajax request from firing again if the user clicks on the same thumbnail and instead use the existing data. $.getJSON(url, function( ...

Conceal cash on delivery payment option in WooCommerce checkout by customizing select field options

Currently, I am utilizing WooCommerce and have integrated a custom checkout field in the form of a selection list. My goal is to eliminate the COD gateway when a customer selects a specific option ("newyork" in this particular case). Displayed below is my ...

Please indicate the IP address and host in the AJAX request

Currently, I am working on an internal project where I am using $.ajax to retrieve data from a different server. Although my hosts file is correctly configured and everything is operating smoothly for me, the same cannot be said for my co-workers due to is ...

Identifying when an element hovers over a particular section

I am facing an issue with the side dot navigation on my website. The navigation is standard with a fixed position, but I also have two types of sections with different backgrounds - one white and the other black. The problem arises when the dots are not vi ...

Guide on how to streamline JSON output from aggregation result

I have written a NodeJs api using mongo db aggregation to obtain some output. However, the result I received is not what I expected. Can anyone help me figure out how to get the desired output? app.get('/polute', function (req, res) { Light. ...

Is there a way to retrieve an ASP element with runat="server" using JavaScript?

It appears that many people are engaging in this practice (within code posts and the like)...but unfortunately, I'm at a loss. :( Every time I attempt to alter an asp element using JavaScript, I am met with an error message stating ""element is ...

What is the best way to automatically log out a user when a different user logs in on the same browser?

Currently, I am encountering an issue where there are two separate dashboards for different types of users - one for admin and the other for a merchant. The problem arises when an admin logs in on one tab and then a merchant logs in on another tab in the s ...

Instructions on how to dynamically update a form field based on the input in another field using conditional statements

I'm seeking advice on how to automatically update a field based on user input without the need for manual saving. For example, if the user types '95' in the input field, the equivalent value displayed should be '1.0' in real-time. ...

What purpose does "Phaser.Display.Align.In.Center" serve when we already have the function `setOrigin` available?

I'm puzzled about the purpose of Phaser.Display.Align.In.Center. The code snippet below is taken from an official example class Example extends Phaser.Scene { constructor () { super(); } preload() { this.load.path = 'https:// ...

Tips for utilizing ajax function to refresh database entries

I am working with a customer information table that is populated from a database. The last column in this table contains an edit button which, when clicked, shows a popup window with text fields pre-filled with database values. I want users to be able to u ...

The revalidation feature in Next.js' getStaticProps function does not seem to be

https://i.stack.imgur.com/vnNMQ.png I have a question regarding my use of the getStaticProps function in index.js. I am trying to ensure that my API call runs every 60 seconds when a user visits my page, but I am experiencing issues with revalidate not wo ...

Creating printable reports using Jspdf with data from SlickGrid

Has anyone successfully used JsPdf with a slickgrid on a webpage? I am currently using their HTML renderer, but I know it's still in early stages. I have added the HTML2Canvas cdn, but I'm unsure how to implement it. Here is my Fiddle $(docum ...

Sending a variable from JavaScript to an external PHP file

There are numerous questions on similar topics, but I'm struggling to figure it out, my apologies. I have a file containing some JavaScript variables that depend on user input (without using a form) and a normal HTML link to my PHP file. <script& ...

Return to the previous location on the page when clicking the browser's back button

I'm looking to incorporate the following functionality: When on page a, clicking a link takes me to page b and displays all content from the beginning. Pressing the browser back button should then return me to page a and show the content starting fro ...

Enable lodash access throughout a React Native application

Is it possible to have lodash automatically accessible in all files within a React Native project without needing to import it every time? ...

How to transfer a PHP array encoded in JSON to a JavaScript function

I've been attempting to transfer a PHP array into a JavaScript function in order to send it via a GET request. Despite using JSON encode for this purpose, I have not been successful. It appears that JavaScript is unable to recognize the array. Below ...

Display list items in HTML based on the length of an array

In my backend, I have a user-defined array of cars. If the user selects 3 cars, the array will contain 3 elements. I would like to display specific details of the cars in HTML elements within a list. The array is based on JavaScript. Here is an example of ...

Multiple button clicks causing events to fire repeatedly

My PHP file echoes a button, but when I click it, the action fires multiple times. Why is it behaving like this? I have tried solutions from Stack Overflow, but none of them seem to work. Any suggestions or corrections? $(document).on('click',& ...