Posting plain text on php using JavaScript - javascript

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);

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'];

Related

How can i select text in javascript Ajax

I am not able to select text which i retrieve from directoryScanner.php file into the div container. So what ever gets displayed in div container , i cannot select it by mouse.
<div id="file_link_panel">
</div>
Following javascript code
function dirRefresher(){
ajax = new XMLHttpRequest();
ajax.open("POST","directoryScanner.php");
ajax.onreadystatechange = function(){
if(ajax.readyState ==4 & ajax.status == 200){
msg = this.responseText;
document.getElementById("file_link_panel").innerHTML = msg;
}
}
ajax.send();
}
setInterval(dirRefresher,1000);
And this simple php script named directoryScanner.php
<?php
echo "kunal";
echo "pankaj";
echo "shekhar";
?>
The problem is you are making tons of Ajax calls and updating the element over and over again so as you try to make the selection, it is being replaced. You are better off increasing the timeout and only firing the next one after you get the call back from the server. Also there is no need to replace the html, if the content is the same.
function dirRefresher(){
var ajax = new XMLHttpRequest();
ajax.open("POST","directoryScanner.php");
ajax.onreadystatechange = function(){
if(ajax.readyState ==4 & ajax.status == 200){
var msg = this.responseText;
var elem = document.getElementById("file_link_panel");
if(elem.innerHTML !== msg) {
elem.innerHTML = msg;
}
setTimeout(dirRefresher, 5000);
}
}
ajax.send();
}
dirRefresher()
If you need quicker updates, you should be looking into webSockets, not Ajax.
Try using innerText besides innerHTML:
You return from php just text so you need to include innerText. Like so:
function dirRefresher(){
ajax = new XMLHttpRequest();
ajax.open("POST","directoryScanner.php");
ajax.onreadystatechange = function(){
if(ajax.readyState ==4 & ajax.status == 200){
msg = this.responseText;
document.getElementById("file_link_panel").innerText= msg;
}
}
ajax.send();
}
setInterval(dirRefresher,1000);

JavaScript: reading $_POST & $_FILES variables after AJAX submission

I'm submitting a form through AJAX for the express purpose of displaying a pre-selected image. Selecting an image from the local drive will trigger the "onchange" event for the file-type input, and in turn call the AJAX routine. It works fine, and upon a successful "move_uploaded_file", the PHP handler returns the validated file name. The following illustrates how the AJAX submission was effected:
var xhr = new XMLHttpRequest();
var xForm = new FormData(document.forms.namedItem("form"));
xhr.open("POST", "handler.php", true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
document.getElementById("imgDiv").src = xhr.responseText;
}
}
xhr.send(xForm);
Instead of getting the handler to return the file name, is there any way to access the $_POST and $_FILES variables after returning from an AJAX submission? This is usually possible when returning from a normal form post, using:
<?php echo $_POST['stringInput'];?>
<?php echo $_FILES['imageInput']['fileName'];?>
but I'm not able to get anything in this case.
Thanking you,
Sofia
EDIT: in case it may be relevant, the handler is not in the same HTML script, but in a separate PHP file. Thanks again!
Because you made a mistake in code typing here:-
Old code
x.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
document.getElementById("imgDiv").src = xhr.responseText;
}
}
New code
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
document.getElementById("imgDiv").src = xhr.responseText;
}
}
Means replace x.onreadystatechange with xhr.onreadystatechange

Retrieving AJAX data in PHP

I need to use the xhr.send(VALUE) to send the data in AJAX. How do I get this data in a PHP file?
JS:
window.onload = function() {
var value = 'hello';
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
} else {
alert("no");
}
}
xhr.open('POST', 'json.php', true);
xhr.send(value);
}
You are just sending a string to the PHP file. You are not sending it as a query string or with a content type, so PHP doesn't populate the $POST array.
You can try to read the raw post data:
$post = file_get_contents('php://input');
echo $post; // hello
Or, if you want PHP to populate $_POST, you need to do some extra steps in your JavaScript.
window.onload = function() {
var value = 'hello';
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
} else {
alert("no");
}
}
xhr.open('POST', 'json.php', true);
// Tell the server you are sending form data
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// Send it as a query string
xhr.send('value='+value);
}
Then in your PHP, you can access $_POST['value'].
echo $_POST['value']; // hello
If you want to see the $_POST variables on the PHP page you can use this code to display them all so you can visually see their keys and values
echo "<pre>";
print_r($_POST);
echo "</pre>";
From there you will know how to use the data in any file. You can do the same thing with $_GET
Try this, replace your xhr.send with
JS
xhr.send('value='+value);
PHP
echo($_POST['value']);

I can't send PHP variables to JavaScript

I'm trying to send parametres from a .php file to my Javascript but I can't even manage to send a String.
Javascript fragment:
var params = "action=getAlbums";
var request = new XMLHttpRequest();
request.open("POST", PHP CODE URL, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");
request.send(params);
request.onreadystatechange = function() {
var phpmessage = request.responseText;
alert(phpmessage);
};
PHP fragment:
$deviceFunction = $_POST["action"];
if ($deviceFunction == "") $deviceFunction = $_GET["action"];
// Go to a function depending the action required
switch ($deviceFunction)
{
case "getAlbums":
getAlbumsFromDB();
break;
}
function getAlbumsFromDB()
{
echo "test message!";
}
The alert containing phpmessage pops up but it's empty (it actually appears twice). If I do this the alert won't even work:
request.onreadystatechange = function() {
if(request.status == 200) {
var phpmessage = request.responseText;
alert(phpmessage);
}
};
The readystatenchange event will be called each time the state changes. There are 5 states, see here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#readyState
Rewrite your JS:
request.onreadystatechange = function () {
if (request.readyState == 4) {
console.log('AJAX finished, got ' + request.status + ' status code');
console.log('Response text is: ' + request.responseText);
}
}
In your code, you only check for the returned status code. The code above will check for the ready state and then output the status code for debbuging.
I know that this answer is more a comment than an answer to the actual question, but I felt writing an answer in order to include nicely formatted code.
I faced a similar problem working with Django. What I did:
I used a template language to generate the javascript variables I needed.
I'm not a PHP programmer but I'm going to give you the idea, let me now if works. The following isn't php code, is just for ilustrate.
<?php
<script type="text/javascript" ... >
SOME_VARIABLE = "{0}".format(php_function()) // php_function resolve the value you need
</script>
?>
The I use SOME_VARIABLE in my scripts.
Please specify your onreadystatechange event handler before calling open and send methods.
You also should make your choice between GET and POST method for your request.
If you want to popup your message only when your request object status is OK (=200) and readyState is finished whith the response ready (=4), you can write :
request.onreadystatechange = function() {
if (request.readyState==4 && request.status==200) {
var phpMessage = request.responseText;
alert(phpMessage);
}
};

send an http request without XHR in an event handler

How to send an http request with either post/get method using javascript as an eventhandler? Thanks! Paul
Okay, you don't want to use Ajax.
You can use an event handler to submit a form!
<a href='#' onclick='cow_submit("zoodle")'>send</a>
<form method='post' id='formie' action='find_some_action.php'>
<input type='hidden' id='snoutvar' name='snoutvar' value='snout'>
</form>
<script>
function cow_submit(a_var_to_set){
var plip=document.getElementById('formie');
var snout=document.getElementById('snoutvar');
snout.value=a_var_to_set;
plip.submit();
}
See https://developer.mozilla.org/en/DOM/form
use XmlHttpRequest
sample code:
var client = new XMLHttpRequest();
client.onreadystatechange = handler;
client.open("GET", "test.xml");
client.send();
function handler()
{
// your handler
}
You can use XMLHttpRequest for sending request from javascript
Sending GET request
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("GET", url+"?"+params, true);
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(null);
Sending POST request
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
And don't forget to encode parameters using encodeURIComponent for param value encoding in case of user input
e.g.
params="paramName="+encodeURIComponent(paramValue);
The standard class for doing this is XmlHttpRequest, but it's not universally supported. On some browsers you have to use ActiveXObject("Microsoft.XMLHTTP") instead.
Look into the jQuery system which provides HTTP download (AJAX style) methods regardless of the underlying browser APIs (hence avoiding a lot of the code shown in Tzury's answer).
The jQuery AJAX documentation is at http://docs.jquery.com/Ajax
You should try to add atring in a hidden field and then call the form.submit() to submit your form into the page define in action.
<script type="text/javascript">
function doTestFormSubmit(yourString) {
document.getElementById("myString").value=myString;
document.getElementById("testForm").submit();
}
</script>
<form name="testForm" id="testForm" action="yourDesiredPage.php" method="post">
<input type="hidden" name="myString" id="myString" value=""/>
</form>
Ajax Tutorial (http://code.google.com/edu/ajax/tutorials/ajax-tutorial.html)
var obj;
function ProcessXML(url) {
// native object
if (window.XMLHttpRequest) {
// obtain new object
obj = new XMLHttpRequest();
// set the callback function
obj.onreadystatechange = processChange;
// we will do a GET with the url; "true" for asynch
obj.open("GET", url, true);
// null for GET with native object
obj.send(null);
// IE/Windows ActiveX object
} else if (window.ActiveXObject) {
obj = new ActiveXObject("Microsoft.XMLHTTP");
if (obj) {
obj.onreadystatechange = processChange;
obj.open("GET", url, true);
// don't send null for ActiveX
obj.send();
}
} else {
alert("Your browser does not support AJAX");
}
}
function processChange() {
// 4 means the response has been returned and ready to be processed
if (obj.readyState == 4) {
// 200 means "OK"
if (obj.status == 200) {
// process whatever has been sent back here:
// anything else means a problem
} else {
alert("There was a problem in the returned data:\n");
}
}
}

Categories

Resources