0

I want to send data with the POST method to a php server, then retrieve data from the server, using GET method this time (I assume).

Here's the JS :

function send()

function send(leURL, laValeur) {
    try {
        return new Promise(function(resolve, reject) {
            var req = new XMLHttpRequest();
            req.open('POST', leURL);
            req.setRequestHeader("Content-Type", "application/json");
            req.onreadystatechange = function() {
                if (this.readyState == XMLHttpRequest.DONE && this.status == 200) {
                    document.getElementById("result").innerHTML = "Ok!";
                }
            };
            jmail = JSON.stringify(laValeur);
            req.send(jmail);
            resolve("true");                
        });
    }
    catch (err) {
        window.alert("erreur 2");
    }       
}

function recieve()

function recieve(laURL) {
    try {
        var reqt = new XMLHttpRequest();
        reqt.open('GET', laURL);
        reqt.onreadystatechange = function(e) {
            if (this.readyState == XMLHttpRequest.DONE && this.status = 200) {
                var rep = JSON.parse(this.responseText);
                try {
                    window.alert(rep);
                }
                catch (e) {
                    window.alert("erreur 4");
                }
            }
        }
        reqt.send();
        //return rep;   
    }
    catch (e) {
        window.alert("erreur 3");
    }
}

function calls :

//there's a form in the HTML (id="form")
document.getElementById("form").addEventListener('submit', function(evt) {
    evt.preventDefault();
    send(url, mail)
        .then(recieve(url));
});

Old recieve() function (for testing purposes) :

function recieve(laURL) {
    window.alert(laURL);
}

So, as long as I was using old recieve() function, I had send() print "Ok!" and recieve() creating an alert, which makes me think it worked fine. But now that I use the new recieve() function, the page just reloads. (No catch block is even displayed !)

Here's the PHP :

<?php
if (!empty($_POST)) {
    $var = //do something with the data, involving $_POST
    echo $var;
}
else {
    echo "Hello, there !";
}
?>

Since $var was generated out of the first HTTP request (POST), how do I retrieve it in javascript ?

I suspect the error is caused either by the php or because of using two XMLHttpRequests (still I don't know how I should do this using only one HTTP request)

AniMir
  • 150
  • 12
  • The POST request already returns the value (using echo). All you need to so is show it using your JavaScript – ADyson Apr 09 '19 at 09:21
  • 1
    e.g. in the POST request, `if (this.readyState == XMLHttpRequest.DONE && this.status == 200) { document.getElementById("result").innerHTML = this.responseText; }` . I don't see any need for the GET request, unless you intend to use this at a later time in your process, expecting that the data may have changed on the server. But for that to make any sense, you have to have stored the data somewhere on the server, and also send in the request some identifier telling the server which piece of data to retrieve. – ADyson Apr 09 '19 at 09:27
  • I can't seem to retrieve my javascript variable. $_POST is empty. – AniMir Apr 09 '19 at 11:02
  • Read this: https://stackoverflow.com/questions/18866571/receive-json-post-with-php – ADyson Apr 09 '19 at 11:03
  • Specifically, this answer: https://stackoverflow.com/a/50900047/5947043 should be all you'll need. – ADyson Apr 09 '19 at 11:04

3 Answers3

1

Your PHP stores the data in a variable, echos it out, then exits.

At this point, the PHP program has finished, the memory gets cleaned up, and the variable no longer exists.

If you want the data to be available to another request, then you have to store it somewhere persistent such as a session or a database.

If you want to use a single request, then read this.responseText in the readyStateChange handler.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

What do you do with your data ?

How do you store them ?

How do you retreive them on the server to sending them after to the client if needed ?

You should store the $var somewhere, generally we use session $_SESSION for that. All depends of what you want finally.

Documentation for PHP session : https://www.php.net/manual/fr/reserved.variables.session.php

Once you have start the session,

I think you want to do something like that:

<?php
if ($_SESSION['var']) {
    echo "already done";
    ...
} else {
  if(!empty($_POST)) {
    $_SESSION['var'] = //do something with the data, involving $_POST
    echo $_SESSION['var'];
  } else {
    echo "var = not done, post = empty";
  }
}
?>
Shim-Sao
  • 2,026
  • 2
  • 18
  • 23
0

The POST request already returns the value (using echo). All you need to so is show it using your JavaScript.

e.g. in the POST request:

if (this.readyState == XMLHttpRequest.DONE && this.status == 200) { 
  document.getElementById("result").innerHTML = this.responseText; 
} 

I don't see any need for the GET request, unless you intend to use this at a later time in your process, expecting that the data may have changed on the server. But for that to make any sense, you have to have stored the data somewhere on the server, and also send in the request some identifier telling the server which piece of data to retrieve.

ADyson
  • 57,178
  • 14
  • 51
  • 63