I want to add text to a text document using JavaScript and PHP. What would be the best way to do this?
This is possible by using Javascript (front-end) to send an ajax request to the PHP server script that does the operation (back-end).
What you can do is use jQuery.ajax or XMLHttpRequest.
XMLHttpRequest
var url = "addtext.php"; // Your URL here
var data = {
text: "My Text"
}; // Your data here
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(data));
jQuery.ajax
var url = "addtext.php"; // Your URL here
var data = {
text: "My Text"
}; // Your data here
$.ajax({
url: url,
data: data,
method: "POST"
})
Note: There is also the jQuery.post method, but I have not included it.
And, in the PHP file, with the necessary permissions, you can write to the file using fwrite in combination with the other file functions.
<?php
$text = $_POST["text"]; // Gets the 'text' parameter from the AJAX POST request
$file = fopen('data.txt', 'a'); // Opens the file in append mode.
fwrite($file, $text); // Adds the text to the file
fclose($file); // Closes the file
?>
If you want to open the file in a different mode, there is a list of modes on the PHP website.
All the filesystem functions can be found here on the PHP website.
I don't think you can append to a text document unless you are writing server side code.
There are some possible workarounds mentioned in this post:
Is it possible to write data to file using only JavaScript?
Related
I send json data through ajax to a php file called in case 'receive.php'.
user_name , user_id, etc. are defined on top of my script page you may change by anything else.
Here is my js code :
const data = {
name: user_name,
id: user_id,
score: success,
time: endTime
};
const jsonString = JSON.stringify(data);
const xhr = new XMLHttpRequest();
xhr.open("POST", "receive.php", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(jsonString);
This is my php file
<?php
header('Content-Type' , 'application/json');
$requestPayload = file_get_contents('php://input');
$json = json_decode($requestPayload , true);
$not = 'gsvcgdsqc';
//This gives NULL
var_dump($json);
echo $not;
?>
in the browser (network), i can see sent data :
But when i try to store it in a variable and display it, it gives null :
So how can I access and store those data in a variable so I can use them after for other actions?
Since you're using jQuery:
$.ajax({
type: 'POST',
url: 'receive.php',
data: data
});
You can then get the data with $_POST, no need for json.
It's showing as NULL when you type the URL into the address bar of the browser.
That's a completely different (GET) request to the POST request you make with JavaScript.
The request body of the POST request (containing the JSON) doesn't exist on the GET request, so of course it is NULL.
If you want to see the response to the POST request you made, then look in the Preview tab instead of the Headers tab in the Network monitor.
If you want to store the data somewhere and then read it back on a subsequent request then you need to do that explicitly by writing code to do it.
Start by picking somewhere to store it (such as a session or a database).
I have this php file graph.php
$host = $_POST['hostname'];
echo $type=$_POST['type_char'];
include('rrdtools.inc.php');
include('graphs/'.$type.'.inc.php');
and I trying to send data to this file using this ajax code
var type_char='fortigate_cpu';//$('#graph').val();
var hostname='10.10.0.144';//$(this).attr('id');
//$('#device_host').val(id);
$.ajax({
type: 'POST',
url: 'SNMP/graph.php',
data: { hostname:hostname,type_char:type_char },
success: function(data) {
alert(data);
// show the response
$("#grph").attr("src", 'SNMP/graph.php');
console.log(data);
}
});
the result when I send data to that file is
fortigate_cpu as a value of type_char variable
when I opened error.log file in apache logs
I have this message
include(): Failed opening 'graphs/.inc.php' for inclusion (include_path='.:/usr/share/php')
as you see the value of fortigate not included in include function even if the char_type variable is send by ajax and printed in page
include file must be as this
include( 'graphs/fortigate_cpu.inc.php')
why type not included in the include session even if the variable is received from ajax
As was mentioned by other users in the comments, maybe your issue is that you are setting type to a different value after including rrdtools.inc.php .
Try randomizing ( changing the name), of the type variable:
$host = $_POST['hostname'];
echo $type123456=$_POST['type_char'];
include('rrdtools.inc.php');
include('graphs/'.$type123456.'.inc.php');
It's the only thing I can think of, since both I (and others) have tested your code.
(both front-end and back-end).
PS: Include using post param is a bad practice.
I know its super basic and probably simple as well, but i'm really stuck.
just trying to get data from php in an event of onkeyup, and post it into the HTML page.
this is my HTML
<input id="dell" type="text" onkeyup="dell_function()"<br>
<p id="gimr">get her the php variable var.</p>
php file:
<?
$var=11;
echo $var;
?>
Now i need to write the dell_function() which i want to open the php file and get the $var value, and post it as a string in here:
<p id="gimr">get her the php variable var.</p>
i know there is ajax involved but i really tried but couldn't figure it out, so how do i write the dell_function?
Ajax is really simple, especially if you are using JQuery. Here is how it would look in jQuery:
function dell_function() {
$.ajax({
url:"test.php", // replace test.php with the name of your PHP file
success: function(data) {
$("#gimr").html(data);
}
});
}
The jQuery documentation describes loads of other cool things you can do with Ajax : http://api.jquery.com/jquery.ajax/
function dell_function() {
var xhttp = new XMLHttpRequest(); // creates a ajax request object
xhttp.onreadystatechange = function () { // will fire when the status of the request changes
if (this.readyState == 4 && this.status == 200) { // checks if the current state indicates that the content has been loaded successfully. readyState=4 means that the request has been completed and the status 200 means that the request returned http status code 200, which means the server response is OK (404 would mean file not found, 408 means timeout, etc - you get the idea).
document.getElementById("gimr").innerHTML = this.responseText; //this will put the response text as html inside the "gimr" element.
}
};
xhttp.open("GET", "YOUR_PHP_FILE.php", true); //the first parameter sets the request method, the second defines the url, and the third defines if the data should be fetched asynchronously.
xhttp.send(); // sends the requests to the specified url.
}
Replace "YOUR_PHP_FILE.php" with the url to your php file.
Btw, take a look at jquery - it makes things like this alot easier ;D
I have a .pdf file client side that I would like to send in binary form to my server, which will be handling it with PHP.
Client side, I am using a POST request that looks like this:
var newFile = require("sdk/io/file");
var params = {};
params.log = newFile.read(filepath, "b");
var makeRequest = newRequest({
url: "SERVERURL",
headers: {
"Content-Type": "application/pdf"
},
content: params,
onComplete: function(response) {
console.error(response.text);
}
}).post();
On server side, I'm using
file_get_contents('php://input')
and file_put_contents to write to a path on the server.
I have tried base64_decode and urldecode on the input, neither of which have correctly regenerated the PDF on the server. With urldecode, I get a blank PDF with the correct number of pages, but no text.
I'm new to PHP, could someone help me out?
Thank you.
I do not know what all of your PHP code looks like but I would replace file_get_contents('php://input') with $_POST['log'].
I am trying to export my web page data and download it as excel file. but the download does not start even the response return succeed.
$.ajax({
type: "POST",
url: _url,
contentType: 'multipart/form-data;boundary=SzB12x',
data: json,
});
The responseText something like this:
PK�J;Fxl/theme/theme1.xml�YOo�6����,[r��n;v��i����#-�kJH:�oC{0X7�2��mZ���d��u#�(٦b:M���������{|��^�0t#��*"w$�!0I�[�՚n�i��'����iH� g�,��|�J�!���hRh�h��?r&�L ���߶S��v#���#���"���}��Жt%�hR�t"������+��������u{ނ��0K���oy�9OTWywkAͯ�
���F�� 6*�����[���U���
I think its the file but I cant download it!!
Any help please?
Thanks!
I faced the same issue and successfully solved it. My use-case is this.
Post JSON data to server and receive an excel file.
That excel file is created on the fly and returned as a response to client.
Code:
$("#my-button").on("click", function() {
// Data to post
data = {
ids: [1, 2, 3, 4, 5]
};
// Use XMLHttpRequest instead of Jquery $ajax
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
var a;
if (xhttp.readyState === 4 && xhttp.status === 200) {
// Trick for making downloadable link
a = document.createElement('a');
a.href = window.URL.createObjectURL(xhttp.response);
// Give filename you wish to download
a.download = "test-file.xls";
a.style.display = 'none';
document.body.appendChild(a);
a.click();
}
};
// Post data to URL which handles post request
xhttp.open("POST", excelDownloadUrl);
xhttp.setRequestHeader("Content-Type", "application/json");
// You should set responseType as blob for binary responses
xhttp.responseType = 'blob';
xhttp.send(JSON.stringify(data));
});
The above snippet is just doing following
Posting an array as JSON to the server using XMLHttpRequest
After fetching content as a blob(binary), we are creating a downloadable URL and attaching it to invisible "a" link then clicking it.
Here we need to carefully set few things at the server side. I set few headers in Python Django HttpResponse. You need to set them accordingly if you are use other programming languages.
# In python django code
response = HttpResponse(file_content, content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
Since I download xls(excel) here, I adjusted contentType to above one. You need to set it according to your file type.
Try to use a hidden form to submit the request.
When a user submits an HTML form, all the data entered into the form by the user is sent as either a GET or POST request to the URL specified in the “ACTION” attribute of FORM.
<FORM action="http://www.labnol.org/sendmail.php" method="post">
...form contents...
</FORM>
In the above example, an HTTP POST request is issued to the sendmail.php script on form submission. You can add target=”_blank” to the FORM tag to process the request in a new window.
However, if you would like to submit a FORM on the page in the background without directing the browser to another page (document.location.href changes on form submit), you have two options:
Option #1. You can either create an invisible IFRAME inside your HTML page and set that as a target for the Original FORM. This will submit the form but without reloading the parent window.
<FORM action="http://example.com/script.php"
method="POST" target="hidden-form">
...form contents...
</FORM>
<IFRAME style="display:none" name="hidden-form"></IFRAME>
Option #2: There’s another method that allows you create custom payloads before submitting the form. Unlike the IFRAME based form submission, the following code makes a standard form submit request and thus your browser location will change and the current page will get added to the browser history. Credit: Rakesh Pai.
submitFORM('http://example.com/script.php', 'POST',
{'name':'digital+inspiration', 'age':'100', 'sex','M'});
function submitFORM(path, params, method) {
method = method || "post";
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
//Move the submit function to another variable
//so that it doesn't get overwritten.
form._submit_function_ = form.submit;
for(var key in params) {
if(params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form._submit_function_();
}
In this link you can find the way to create hidden form and submit it.
enjoy!!
The approach here is directly lifted from https://gist.github.com/DavidMah/3533415.
This approach uses <form> and appends the data with a key. This approach works if the server is already expecting the data as an attribute of the request body, as opposed to being the request body itself. If the data to be uploaded is an object, you could iterate over that object's keys. If the data to be uploaded is an array, either modify the server route or [add idea here].
In browser
// Takes a URL, param name, and data string
// Sends to the server... The server can respond with binary data to download
jQuery.download = function(url, key, data) {
// Build a form
var form = $('<form></form>').attr('action', url).attr('method', 'post');
// Add the one key/value
form.append($("<input></input>").attr('type', 'hidden').attr('name', key).attr('value', data));
//send request
form.appendTo('body').submit().remove();
};
On server
# A Tidbit of sinatra code to respond
# Assume 'url' is a set variable
# Assume 'key' is the key of the value used in the javascript
post url do
data = params[:key]
puts request.body.read
headers['Content-Type'] = "application/octet-stream"
body(data)
end
Example
$.download('/path/resource/', 'data', JSON.stringify(data))
If you just want to download a file, you don't need to use ajax to do it. Actually, you cannot download file using ajax.
You can still do it by making a hyperlink Export request to a server page that responses content-type is application/vnd.ms-excel and content-disposition is attachment.
You can achieve this using an iFrame as well. A sample function:
// append the data to URL
var requestData = {
param1 : "value1",
param2 : "value2",
}
// call the function
downloadFile(<your_URL>, requestData);
function downloadFile(requestURL, data) {
// "transData" is just a user defined variable to encapsulate "downloadIFrame". It can be named anything as required.
var downloadIFrame = window.transData.downloadIFrame = window.transData.downloadIFrame || $("#downloadFileiFrame");
downloadIFrame.attr("src", requestURL + $.param(requestData));
}
// define the iFrame in your HTML and hide it.
<iframe id="downloadFileiFrame" style="display:none;"></iframe>"
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: yoururlpath,
success: function (response) {
var file = fileName+".xlsx";
window.location = "someFilePath?file=" + file;
}
});