A guide on showing POST values from javascript XMLHttpRequest() in php

I have encountered an issue where I am using the XMLHttpRequest() javascript function to send parameters in Json format to another php page, but for some reason $_POST['appoverGUID'] is not receiving the posted values.

Below is my Javascript code:

function loadPage(href){

    var http = new XMLHttpRequest();
    var url = json.php;
    var approverGUID = "Test";
    var params = JSON.stringify({ appoverGUID: approverGUID });
    http.open("POST", url, true);
    http.setRequestHeader("Content-type", "application/json; charset=utf-8");
    http.setRequestHeader("Content-length", params.length);
    http.setRequestHeader("Connection", "close");
    http.onreadystatechange = function() {
        if(http.readyState == 4 && http.status == 200) {
            document.getElementById('bottom').innerHTML = http.responseText;

        }
    } 
    http.send(params);

}

Here is the code from my json.php file:

if(isset($_POST['appoverGUID'])){
echo $_POST['appoverGUID'];
}

Answer №1

To begin with, it is advisable to remove these headers as they will be automatically sent by the browser.

http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

This particular code serves as a universal solution that has been thoroughly tested across different web browsers.

// This works on IE 5.5+ and all other browsers
var xhr = new(window.XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0');
var params = "appoverGUID="+approverGUID;
xhr.open("POST", url, true);

xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.setRequestHeader("Accept", "application/json");
xhr.onreadystatechange = function () {
    if (this.readyState === 4) {
        if (this.status >= 200 && this.status < 400) {
            console.log(JSON.parse(this.responseText));
        }
    }
}
xhr.send(params);
xhr = null;

Answer №2

To decode the JSON data, you can utilize the json_decode function. Here is an example of how to do it:

if ("application/json" === getallheaders())
    $_JSON = json_decode(file_get_contents("php://input"), true) ?: [];

Answer №3

To populate parameters like this (no escaping or encoding of approverGUID content has been done here):

params = "appoverGUID="+approverGUID;

For more information, please refer to:

http://www.example.com/ajax_xmlhttp_using_post

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

The closing dialogue feature is not functioning properly

Currently, I am working with primefaces version 5.0 and I have come across this particular scenario: <composite:implementation> <p:dialog id="confirmDialog#{cc.attrs.someParam}" rendered="#{cc.attrs ...

What is the best way to connect the elements in two separate arrays?

I have a scenario with two arrays and a variable: var Names = ['jack', 'peter', 'jack', 'john']; var Ids = ['1' , '2' , '3' , '4' ]; Also, I have this search varia ...

Can someone please guide me on how to transfer information from a material ui datagrid Row to a form input?

I need assistance. I have a table that holds user data and I want to create a functionality where clicking on the edit button opens a dialogue box with a form pre-filled with the user's initial data. However, I'm currently only able to pass the u ...

Setting up a personalized JSPM registry configuration

I have chosen to use Verdaccio as the platform for hosting a private package. In my current project, I am looking to incorporate this package locally. The package has been successfully published and is now hosted on Verdaccio running on localhost (http://l ...

Are the frameworks Vue, Angular, and React known for

During a conversation, I came across an interesting viewpoint criticizing popular frameworks such as Angular, Vue, and React. It was argued that these frameworks have a significant disadvantage: apart from the API part that interacts with the server's ...

Uploading images to a database with Codignitor

Is there any way to store images in the MySQL database using a BLOB field? I need to upload them through a web form and then display them afterwards. It's not an ideal solution, but due to certain circumstances, I am forced to do it this way. Currentl ...

persistently drifting towards the right despite the absence of direction

Why is the adminbox floating when no command is present? The fixed div center is not functioning properly .adminbox { width: 200px; height: 17px; margin-top: 20px; padding: 20px; font-size: 12px; ...

Transmitting Map data from Ajax to a Spring controller poses a significant challenge for me

I need assistance with implementing a function to send map data to a Spring Controller via ajax. However, I am encountering an issue where the received map data from the controller is empty. The size of the map is currently 0... Please help me resolve t ...

Error: Unexpected data type encountered. Expected an array but found a string instead at line 1, column 2

I have tried multiple suggestions from similar questions but none of them have helped. How can I successfully execute this test? @Test fun isJsonCorrectPersonConvert() { val gson = GsonBuilder().create() val json = gson.toJson("[{\"Id\": ...

I am encountering a 404 error when attempting to make a GET request for a file located in the same directory

Here is the Javascript code that utilizes the get method. The directory contains both files - the HTML file where the JS code resides, and the text file. Below is an image of the console displaying errors. ...

"Enhancement in Chrome: Inclusion of Origin header in same-origin requests

When we POST an AJAX request to a server running locally, the code looks like this: xhr.open("POST", "http://localhost:9000/context/request"); xhr.addHeader(someCustomHeaders); xhr.send(someData); The webpage where this javascript is executed is also on ...

What is the best way to flatten object literal properties?

I have received an object from a legacy server that I need to restructure on the client-side using JavaScript, jQuery, or Underscore.js. Here is the original structure of the object: [ { "Id":{ "LValue":1, "Value":1 }, ...

Instructions on merging the firstName and lastName fields to display them in the Full name column within Sonata admin

I am attempting to display a column for Full name that combines the firstName and lastName properties from my entity. How should I go about this? Below is the Entity and Admin.php code snippets: class test{ private firstName; //other properties privat ...

shifting the length of o to the right by zero with the

While exploring the polyfill function for Array.includes, I stumbled upon the following lines of code: // 2. Let len be ? ToLength(? Get(O, "length")). var len = o.length >>> 0; // 4. Let n be ? ToInteger(fromIndex). // (If fromIndex is undef ...

Displaying a success dialog after closing a Bootstrap modal

I have set up a bootstrap modal containing a form. Upon submitting the form, the form content is hidden and a bootstrap alert message is displayed. However, upon clicking the bootstrap popup, the same alert message is shown in the popup instead of displayi ...

How can I obtain the model values for all cars in the primary object?

const vehicles={ vehicle1:{ brand:"Suzuki", model:565, price:1200 }, vehicle2:{ brand:"Hyundai", model:567, price:1300 }, vehicle3:{ brand:"Toyota", model ...

Why does this function execute even after clicking only one of the two keys when using jQuery?

Here is the code snippet I am working with: $(document).bind('keydown', 'ctrl+1', function () { alert('You found the hotkey ctrl+1!'); }); However, when I press either the Ctrl or the 1 key, this code triggers. I specific ...

Enhancing the functionality of the CakeDC users plugin to be compatible with Opauth or OpenID authentication methods

I am currently facing challenges while attempting to expand the functionality of the cakeDC users plugin by integrating it with the Opauth plugin. Particularly, I am struggling with incorporating the Opauth plugin for authentication purposes such as regist ...

Javascript issue: opening mail client causes page to lose focus

Looking for a solution! I'm dealing with an iPad app that runs html5 pages... one specific page requires an email to be sent which triggers the Mail program using this code var mailLink = 'mailto:' + recipientEmail +'?subject=PDFs ...

Utilizing Powershell to eliminate characters from a string

After pulling a list of IPs from a JSON file, I've been using the code snippet below: $Request = 'https://url-to-json.com/file.json' $AWSIPs = Invoke-WebRequest $Request | ConvertFrom-Json | Select-Object prefix -ExpandProperty prefixes -Ex ...