Sending an XMLHttpRequest in PHP causes a blank array to be returned

> xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
       var jsondata = xmlhttp.responseText;
        console.log(xmlhttp.responseText);
        document.getElementById("jsondata").value = jsondata;


        console.log(innerHTML = jsondata.word);
        document.getElementById("approved").innerHTML = "Thank you! We will get back to you.";
    }
};
xmlhttp.open("POST", url,false);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
xmlhttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xmlhttp.setRequestHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
xmlhttp.setRequestHeader("Access-Control-Allow-Headers", "Content-Type");
xmlhttp.send("a="+a+ "&b="+b);

}

PHP:

<?php
header('Access-Control-Allow-Origin: *');


if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']) && $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'] == 'POST') {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Headers: X-Requested-With, content-type, access-control-allow-origin, access-control-allow-methods, access-control-allow-headers');
    }
    exit;
}


$req = file_get_contents("php://input");
$req = json_decode($req);

Answer №1

To start, there is a redundancy in sending CORS response headers during a request - this action serves no purpose other than triggering a preflight check due to non-standard headers. Therefore, it is recommended to eliminate the following lines:

xmlhttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xmlhttp.setRequestHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
xmlhttp.setRequestHeader("Access-Control-Allow-Headers", "Content-Type");

Additionally, the use of onreadystatechange with a synchronous (deprecated) request is not efficient. In the amended code below, the request is made asynchronous and switches to the more contemporary onload.

The comments provided should shed light on the remaining modifications.

var xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var data = JSON.parse(xmlhttp.responseText); // parsing JSON response
        console.log(xmlhttp.responseText);
        document.getElementById("jsondata").value = data;
        //console.log(innerHTML = jsondata.word); removed for unclear functionality
    }
};
xmlhttp.open("POST", url, true); // utilizing ASYNCHRONOUS request as per modern standards
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
xmlhttp.send("a="+a+ "&b="+b);

As for the PHP snippet:

<?php
// Potential removal of pre-flight request! Retaining code just in case
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']) && $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'] == 'POST') {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Headers: X-Requested-With, content-type');
    }
    exit;
}
// Placed after conditional exit to prevent duplication in an OPTIONS request
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json; charset=UTF-8'); // Optional but courteous
$a = $_POST["a"];
$b = $_POST["b"];
// Returning JSON response requested by client code
echo json_encode(array('result'=>$a + $b));
?>

Answer №2

It seems like your XMLhttprequest.send is not sending a blank request, but actually values of 'a' and 'b'. I tested your code by setting random values to 'a' and 'b', and found that the $req variable does get populated with the values of 'a' and 'b.

<script>
    var xmlhttp = new XMLHttpRequest();
    var url = 'http://localhost/test/test.php';
    var a= 5;
    var b=6;
  xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var jsondata = xmlhttp.responseText;
            console.log(xmlhttp.responseText);
            document.getElementById("jsondata").value = jsondata;


            console.log(innerHTML = jsondata.word);
            document.getElementById("approved").innerHTML = "Thank you! We will get back to you.";
        }
    };
    xmlhttp.open("POST", url,false);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
    xmlhttp.setRequestHeader("Access-Control-Allow-Origin", "*");
    xmlhttp.setRequestHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
    xmlhttp.setRequestHeader("Access-Control-Allow-Headers", "Content-Type");
    xmlhttp.send("a="+a+ "&b="+b);

</script>

Upon running this code, I received a=5&b=6. One issue I noticed in your code is that you are not echoing the results. To fix this, add the following:

$req = file_get_contents("php://input");
echo $req;

In response to Jaromanda X's suggestion, it should be noted that there is no JSON data being sent to the PHP script, so trying to decode it would result in errors.

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

Issue in Laravel: Unable to catch exceptions from a specific package using try-catch block

I am currently utilizing a package https://github.com/barbushin/php-imap in my project to retrieve emails from a mail server. Below is the snippet of code I have implemented: $folder = Storage::disk('local')->getAdapter()->getPathPrefix(); ...

What is the best method for clearing all cookies in PHP?

unset($_COOKIE['id']); The code snippet shown above will remove a specific cookie. But what if we want to delete all cookies at once? ...

A basic structure for a JSON array

Perhaps my next question may appear silly, but I'll ask it anyway :) Here is the structure in question: { "name": "Erjet Malaj", "first_name": "Erjet", "work": [ { "employer": { "id": "110108059015688 ...

Selenium encountered an error when trying to execute the 'querySelector' function on the document. The selector provided, my_selector, is not recognized as a valid selector

Whenever I run this code: document.querySelector(my_selector) using selenium, an error is thrown: Failed to execute 'querySelector' on 'Document' my_selector is not a valid selector my_selector is definitely a valid selector that func ...

Guide on launching Selenium within an already open browser using manual settings

Issue The default behavior of Selenium is to open a new browser window during execution. However, I am looking to have Selenium operate within an existing browser session (preferably in Google Chrome). While there are solutions available in Java and Pytho ...

What is the best way to choose a key from a discriminated union type?

I have a discriminated union with different types type MyDUnion = { type: "anonymous"; name: string } | { type: "google"; idToken: string }; I am trying to directly access the 'name' key from the discriminator union, like thi ...

Guide on merging non-modular JavaScript files into a single file with webpack

I am trying to bundle a non-modular JS file that uses jQuery and registers a method on $.fn. This JS must be placed behind jQuery after bundling. Here is an example of the structure of this JS file: (function($){ $.fn.splitPane = ... }(JQuery) If y ...

Consider utilizing the return statement in a PHP function by incorporating an if statement

Can you incorporate a return statement in a function along with an if statement? I want to know if the function was executed up to the if statement or not. This would help me verify if the SQL query will also be executed. Although I understand that I can ...

React - The ._id received by the Modal inside the map function is incorrect

My map is generating edit and delete buttons. The delete button requires confirmation, so I implemented a modal. When I use console.log(additive._id) on the first delete button, I get the correct ._id, but when I click the confirm button inside the modal, ...

The addition of a cancel swipe feature to an HTML5 eBook is causing the text input field for note-taking to malfunction

I am currently working on the development of a process to create HTML5 based eBooks for both desktop and mobile use using Adobe InDesign and exporting them with a plugin called In5. This plugin allows for the incorporation of html, css, and javascript duri ...

There was an issue locating a declaration file for the module 'clarifai'

https://i.stack.imgur.com/PgfqO.jpg I recently encountered a problem after installing the Clarifai API for a face recognition project. Despite my efforts, I have been unable to find a solution. When I hover over "import clarifai," I receive the message: ...

Retrieving data from Node.js within an Angular application

I am currently working on retrieving data from MongoDB and displaying it on my website. However, I am facing an issue in sending the entire fetched object to a specific port (the response) so that I can retrieve it from Angular. I also need to know how to ...

Selenium - How to pass a file path to a dynamically generated input element that is not visible in the DOM

Check out this example of HTML code: This is how you create a visible button and display the selected file: <button id="visible-btn">visible button</button> <p>selected file is: <span id="selected-file"></spa ...

Displaying the current time and total time of a custom video player using Javascript

Currently, I'm in the process of creating an html5 video player and have incorporated javascript to update the current time as a fraction of the total time. The script I've written so far is as follows: function updateTime() { var curTime = ...

Leveraging useContext to alter the state of a React component

import { createContext, useState } from "react"; import React from "react"; import axios from "axios"; import { useContext } from "react"; import { useState } from "react"; import PermIdentityOutlinedIcon f ...

Showing the values of selected checkboxes in a select dropdown - here's how!

Link to the jsfiddle : https://jsfiddle.net/a1gsgh11/9/ The JavaScript code seems to not be working on the js fiddle platform. My main concern is that I would like the selected checkbox values to display immediately without needing to submit any buttons. ...

Why does PHP external API access fail when requested from a different page on the same domain?

Currently, I am experimenting with cross-site scripting using Jquery and PHP/Symfony (HttpFoundation Component), but I'm facing difficulties in obtaining the necessary data from the server. My objective is to have Jquery fetch JSON from the local dom ...

Tips for making an AJAX request using jQuery

I have a new project that involves collecting user data and displaying it on the same page. I was able to successfully implement an Ajax call using JavaScript, but now I want to transition to using jQuery. Below is my JavaScript code: var output1 = docum ...

Error: It is not possible to assign a value to the Request property of the Object since it only has a getter method

Encountering issues while attempting to deploy my Typescript Next.js application on Vercel. The build process fails despite functioning correctly and building without errors locally. Uncertain about the root cause of the error or how to resolve it. The f ...

"Encountered npm error: JSON input ended unexpectedly" while trying to install express-mysql-session"

I'm currently developing a nodejs project that uses passportjs for user authentication and mysql as the database. I'm now looking to incorporate session storage by utilizing the ""express-mysql-session" package. However, when attemptin ...