All I'm trying to do is send a string, in html, to a script written in PHP. I've tried several solutions, including making an html element and putting it in a form and then passing the form (didn't work). I don't know the basics of AJAX or PHP, everything is just kind of being pieced together via what I can google. Here's one way I trying to remedy the situation: (The regexp replaces the first line of the file, which I works. I tried foreach loops with assigning a variable to $_POST[$key], I tried sending just the string with html hoping that would work. I believe the problem lies in the HTML, or in the AJAX call, because I can make the form submit() to the .php file and then it works, however, that would change the browser location to that file and obviously with AJAX, that's not what I want. Anyone have any ideas (other than JQuery syntax)?
HTML
<form>
<input type="hidden" name="test" id="test" value="testString">
</form>
JavaScript AJAX call
function sendString()
{
var data = document.getElementById("test");
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.open('POST', 'testing.php', true);
xhr.send(data);
}
PHP File
<?php
$line = $_POST['data'];
$file = 'test.txt';
file_put_contents($file,preg_replace('/^.+/',$line,file_get_contents($file),1));
?>
EDIT: Thanks for the responses, but non have worked. I tried:
document.getElementById("test");
document.getElementById("test").value;
and
xhr.send(data.value);
None of these worked. Still Blank lines. I also tried the extended solution.
Your problem is here:
var data = document.getElementById("test");
You're creating a reference to your html element. You need to reference the value property of your element.
var data = document.getElementById("test").value;
Also, you are only sending the value and not a key value pair to the server. So xhr.send(data); will only send the value. Your PHP script won't know that $_POST['data'] is what you mean. You need to format var data as
var data = "data=" + document.getElementById("test").value;
EDIT
To send form data via POST, you may need to add some header information.
xhr.open('POST', 'testing.php', true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(data);
http://www.openjs.com/articles/ajax_xmlhttp_using_post.php
// change your function
function sendString()
{
var data = "data="+document.getElementById("test").value;
var xhr= new XMLHttpRequest();
xhr.open('POST', 'testing.php', true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(data);
}
In testing.php you can call them via $_POST:
echo $_POST['data'];
Example here: http://www.openjs.com/scripts/examples/ajax_using_post.php
Related
I have been trying this for a few hours now, googling around and trying several approaches. The code is so simple I don't understand why it doesn't work. I am using 000webhost free hosting atm just to test this out.
I literally just wanna pass a variable to the php file for it to save in a text file, in this case "ayy".
Latest code (file does not even get created):
JS Code
function doSave(){
xhr.open("POST", "save.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.send("ayy");
}
PHP code (save.php)
<?php
file_put_contents('data.txt', file_get_contents('php://input'));
?>
I did also have this code below earlier, however it only created a blank file and would not append any text to it:
index.htm
function doSave(){
var datastr = "ayy";
var xmlhttp = new XMLHttpRequest();
xmlhttp.setRequestHeader('Content-Type', 'application/json');
xmlhttp.open("GET", "save.php", true);
xmlhttp.send(datastr);
}
save.php
<?php
$post_data = $_POST['datastr'];
$f = fopen("data.txt", "w+");
fwrite($f, $post_data);
fclose($f);
?>
Any suggestions why this might not be working? All I can think of is the server not supporting it or something, however I can get it working fine if I specify the variable IN the php file and using a GET request to simply just post the variable. However the data is going to be dynamic so I need to pass it from client-side using js.
Thanks.
Edit: Update - Solution
So I have achieved what I needed to do: Write data to file on the server. I am not exactly sure how things work but it seems that:
xhttp.send(data);
does not send all the data in a FormData variable but rather only the data with the "key" "data". (Sorry if I have the terminology wrong here.) So what I did is I took my object "userData" and applied the following:
userStringData = JSON.stringify(userData);
I then put the userStringData into a FormData variable as follows:
var data = new FormData();
data.append("data" , userStringData);
This then successfully wrote to the file on the sever. In the file I only had userStringData and not the "key" "data".
In my PHP file I also included a new line after every write so that each userString data would be on a new line:
if(!empty($_POST['data'])){
$data = $_POST['data'];
$fname = "users.txt";
$file = fopen("./AJG_Data/".$fname, 'a');
fwrite($file, $data);
fwrite($file, "\r\n");
fclose($file);
So this is working for me now. Thanks to those who offered advice and assistance.
Edit: Update:
Objective: To write data to the server using AJAX and PHP. (Please refer to original question below if necessary)
Thanks to ADyson's comments I have made a lot of progress. I have learnt that an XMHHttprequest is the way to make an AJAX request to the server. I have this code:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let successString = `Thank you ${userData.athlete.firstname} you have successfully granted permission to read your data.`
document.querySelector("#message-0").innerHTML = successString;
}
};
xhttp.open("POST","/path_to_my_php_file/file_write.php", true);
xhttp.send(data);
}
On the server side I have this in my php file:
<?php
$dir = 'AJG_Data';
// create new directory with 744 permissions if it does not exist yet
// owner will be the user/group the PHP script is run under
if ( !file_exists($dir) ) {
mkdir ($dir, 0744);
}
file_put_contents ($dir.'/test1.txt', 'Hello File');
if(!empty($_POST['data'])){
$data = $_POST['data'];
$fname = "users.txt";
$file = fopen("./AJG_Data/".$fname, 'w');
fwrite($file, $data);
fclose($file);
}
?>
The directory creation section above is not necessary it was part of my trouble shooting.
The above works perfectly if I send simple FormData created as follows:
var data = new FormData();
data.append("data" , "the_text_you_want_to_save");
The problem I have is that when I try to send more complex FormData. It doesn't work. It doesn't recognise my FormData and it doesn't get past this if statement:
if(!empty($_POST['data']))
I have checked my FormData using this code:
for (var pair of data.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
The above code returns the following:
token_type, Bearer
expires_at, 12345678910
expires_in, 1234
refresh_token, 1234567890abcefg...
access_token, 1234567890abcdefg...
athlete[id], 1234567
athlete[username], joe_soap
athelete[resouce_state], 2
athlete[firstname], Joe
...
...
athelete[created_at], 2017,01-03T16:07:37Z
...
...
athlete[profile], https://some.web.address/larg.jpg
So as far as I can tell I have good FormData but nothing gets written on the server side.
How can I correct this?
Thank you.
The original question follows below.
I have successfully retrieved data from the Strava API using JavaScript code. I have the data stored in a variable as a JavaScript object. I want to write the data to a file on the server.
I have spent hours searching the web and I can't find a solution. It seems this may be possible using ajax or jQuery but I can't find a simple step by step explanation of how to do this.
Bottom line: I want a simple way to write data to file on the server using JavaScript or something related to JavaScript that is quick and easy to implement. Assuming I can successfully write to file I will later want to read from file.
You would need another file on the back end, which would actually do the writing. I'll assume PHP. I'd recommend base64 encoding the data, and storing it encoded to save time.
Javascript:
if (window.XMLHTTPRequest) {
var xhttp = new XMLHTTPRequest();
} else {
var xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//Process output, get result text with this.responseText, decode base64, and parse JSON
alert(JSON.parse(window.atob(this.responseText)));
}
}
xhttp.open("POST", "file-load.php?key=" + window.btoa(JSON.stringify(value)), true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhttp.send();
PHP:
<?php
$key = $_POST['key'];
file_put_contents("storage.txt", $key); //Set file contents
Or, if you want to append it:
<?php
$key = $_POST['key'];
$current = file_get_contents("storage.txt");
file_put_contents("storage.txt", $current . "\n" . $key);
To read the file, just use the same setup as before for javascript, but instead of file-load.php, use file-read.php:
echo file_get_contents("storage.txt");
Use the onreadystatechange to read the output.
I'm trying to save a post request data to a google spreadsheet. However, the data is saved as undefined.
The original post uses a form and uses jquery. See the link below. But I'm trying to pass an array also without the use of jquery.
I'm using the following app script without using jquery - https://mashe.hawksey.info/2014/07/google-sheets-as-a-database-insert-with-apps-script-using-postget-methods-with-ajax-example/
I'm posting the code here.
function sendData(data) {
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
var theUrl = "spreadsheeturl";
xmlhttp.open("post", theUrl);
//xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xmlhttp.send(JSON.stringify(data))
}
I found the answer, you have to uncomment a block in the app script if you are passing JSON data.
I have this code that I want to use to pass information to a php file:
<script>
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "page.php?sess=123123", true);
xhttp.overrideMimeType('text/xml; charset=UTF-8');
xhttp.send(null);
</script>
If i echo this code in my .php page, it works on page load ("page.php" recieves the sess variable and stores it). However, when I copy this code (without the script tag) into a .js file that I use in my main php page, it doesn't work.
The idea is that I want to pass sess parameter to page.php when a specific javascript based timer is triggered.
Your help is appreciated.
I am trying to create form data to send within a post request (to a PHP script) with FormData.
However, the FormData object is always empty:
var oReq = new XMLHttpRequest();
var url = "http://www.test.com/test.php";
oReq.open("POST", url, true);
oReq.setRequestHeader("Content-Type","multipart/form-data");
var myFormData = new FormData();
myFormData.append("formType","PDF");
myFormData.append("pdf", pdf.output(),"thisPDF.pdf");
oReq.send(myFormData);
the 'pdf' variable is a jsPDF object (I've checked that it is a valid object and I have tried to remove that line and only have the "test" form data element sent. Yet, myFormData is always an empty object. Hoping I'm just missing something simple here.
In addition, when I try to check for the existence of the form elements in the PHP script, it shows no $_POST and no $_FILE elements at all.
ADDITIONAL INFO:
When I try this code:
var oReq = new XMLHttpRequest();
var url = "http://www.test.com/test.php";
oReq.open("POST", url, true);
oReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
var myFormData = new FormData();
myFormData.append("formType","PDF");
alert(JSON.stringify(myFormData));
oReq.send(myFormData);
I can then access the "formType" $_POST variable in the php script. But if I add in the File append statement to the myFormData object (and keep the same 'Content-Type', the PHP script errors returning a "not allowed access" error.
However, the $_POST is set according to isset($_POST) in both cases and with the file inserted the $_FILE variable is set according to isset($_FILE).
Remove the oReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); from the code. Browser automatically set multipart/form-data header, if you add file in FormData.