Eugen-Andrei Coliban
Eugen-Andrei Coliban

Reputation: 1090

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?

Upvotes: 0

Views: 2023

Answers (2)

Quentin
Quentin

Reputation: 944441

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

Upvotes: 2

Carlos Salazar
Carlos Salazar

Reputation: 1908

An XmlHttpRequest or Ajax for short is a requests that will not reload the page, with this logic you are sending a POST request like you would do in a form, when you send a form, you're sending a pair key : values to the file you're sending lets say you have a form like this

<input name="transactionID">
<input name="time">
<input name="senders">
<input name="receivers">
<input name="finalSum">

the values will be received like this in the global $_POST array

{
    "transactionID": "some id",
    "time": "some time",
    "senders": "some senders",
    "receivers": "some receivers",
    "finalSum": "final sum"
}

when you do a Ajax request, you do the same but without the inputs html, when you send the data like this

newTransaction.data = {
    "transactionID": document.getElementById('trans-id').value,
    "time": document.getElementById('creation-time').value,
    "senders": getSenders(),
    "receivers": getReceivers(),
    "finalSum": setSum()
};
xmlhttp.send({newTransaction});

In your admin.php you will receive something like

{
    "data" : {
        {
            "transactionID": "some id",
            "time": "some time",
            "senders": "some senders",
            "receivers": "some receivers",
            "finalSum": "final sum"
        }
    }
}

I recommend you 2 thigns

  1. in your admin.php use echo var_dump($_POST);die(); to see exactly what are you receiving
  2. use a plugin to perform the ajax call like jQuery, axios, etc. this will give you tools to better handling the request and responses.

Upvotes: -1

Related Questions