Posting plain text on php using JavaScript

–3 votes
asked Jun 4, 2015 by cobra

I need to use "POST" consisting of value and a variable structure using JavaScript. The plain text should be sent to a PHP page where it will be displayed. How should I get about this?

From what I understand according to my requirement. It needs to be something like a FROM submission, but run only using JavaScript.

document.body.innerHTML += '<form id="content" action="http://10.10.10.10/index.php" method="post"><input type="hidden" name="info" value="'+plainText+'"></form>';
document.getElementById("content").submit();

I tried this code as well.Do you have an Idea on how to display the text sent here on a PHP page?

var request = new XMLHttpRequest();
request.open("POST", "10.10.10.10/index.php", true); 
request.onreadystatechange = function () { 
    if(request.readyState === 4){ 
        if(request.status === 200 || request.status == 0){    
            request.setRequestHeader("Content-type","text/plain;charset=UTF-8");
            request.setRequestHeader("Content-length", plainText.length); 
            request.send(plainText); 
        }
    }
}
request.send(null);

1 Answer

+1 vote
answered Jun 4, 2015 by jcubic

You need to use ajax, if you need plain javascript then you should do something like this:

var request = new XMLHttpRequest();
request.onreadystatechange = function () {
    var DONE = this.DONE || 4;
    if (this.readyState === DONE){
        alert(xhr.responseText);
    }
};
request.open('POST', 'script.php', true);
request.send("<YOUR TEXT>");

if you use jQuery then simple:

$.post('script.php', '<YOUR TEXT>', function(response) { });

and then you can read it in php using:

file_get_contents('php://input');

or (deprecated):

$GLOBALS['HTTP_RAW_POST_DATA'];
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...