Search code examples
javascriptphpxmlhttprequest

Pass data from JS to PHP via XmlHttpRequest


I'm confronting now with a problem, which consists in sending a JS object to PHP, and I found that it should be done via HtmlHttpRequest, but the problem is that I'm a novice in PHP,and furthermore, I do not understand very well how this XmlHttpRequest works. I've tried different methods but, the one which I found suitable for me, returns constantly the same error. The code will be posted below, and now about the problem, I canperform this request, but when I perform this, the PHP side returns me an error message that there exists an undefined index.

And here's the desired code

JS part :

function createTransaction() {
    var xmlhttp = new XMLHttpRequest();
    var newTransaction = {"name": document.getElementById('wallets').value}
    newTransaction.data = {
        "transactionID": document.getElementById('trans-id').value,
        "time": document.getElementById('creation-time').value,
        "senders": getSenders(),
        "receivers": getReceivers(),
        "finalSum": setSum()
    };
    xmlhttp.open('POST', '/admin.php', true);
    xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xmlhttp.onreadystatechange = function () {
        if (this.readyState === 4 || this.status === 200) {
            console.log(this.responseText); // echo from php
        }
    };
    xmlhttp.send({newTransaction});
    console.log(JSON.stringify(newTransaction));
}

A short description : In this function I'm generating a an object, then send to PHP via XmlHttpRequest using a POST request, that's all, on the PHP side there's a variable which catches this request and echoes it. Here's the code :

$newTransaction = $_POST['newTransaction'];
echo $newTransaction;

What is wrong and/or how it should be better to resolve this issue?


Solution

  • You are doing two things wrong.

    1. You are not converting your object to JSON before you send it: xmlhttp.send(JSON.stringify({newTransaction}));. Instead you are sending the default string representation of an object: "[object Object]" which isn't helpful.
    2. Your PHP is expecting to receive URL encoded or Multipart form data. It is not expecting to receive JSON. See this answer