I've been working on a web page which can't use PHP so I had to look up a solution without. I now have the following jQuery code:
function writeFile() {
alert("writing file...");
$.ajax({
type: 'POST',
url: "test.txt", // url of receiver file on server
data: "test", // your data
success: alert("sucess writing the file!"), // callback when ajax request finishes
dataType: "text" // text/json
});
};
The file is where it should be and the alert() are showing up (also the success alert) but somehow the file is empty. Why?
AJAX cannot directly write to a file, because JavaScript is a client side only and not server side. What you want is a server that catches your AJAX request; server can be anything, including PHP, JAVA or NodeJS. You can only read static files using AJAX but that is all.
You can't just write to a text file on the server using client-side AJAX scripting. You will have to use Node.JS or a PHP server-side script to write to the file on the server. This example below uses a PHP script. You will want a file called test.php in the same directory as the page the AJAX is on. This will POST the string "hello world" to test.php, as the superglobal $_POST['textcontent']. It is possible, using an anonymous function in the success field, to get the output from the PHP script and show it on the page. Note that you can replace "hello world" in the example below, to a $("#my-input-area").val() variable, if you want to write user input to a file.
function writeFile() {
alert("writing file...");
$.ajax({
type: "post",
url: "test.php",
data: {
textcontent: "hello world",
},
success: function(response) {
$("#ajax-area").html(response);
}
});
};
And then your PHP will look like this.
test.php
<?php
if (!empty($_POST['textcontent'])) {
file_put_contents("test.txt", $_POST['textcontent']);
exit("<p>TXT file written successfully!</p>");
}
// This is where you write to the text file.
// The string in the exit() function will appear in your $("#ajax-area")
else {
exit("<p>No text string submitted.</p>");
}
?>
Using the above example, the PHP script will receive the string "hello world" from the AJAX call. This will write to the test.txt file in the same directory as your PHP script, which would be in the same directory as the page with the AJAX. You can put these in a different folder on the server if you want. Anything the PHP script outputs, either with echo or with exit, will be returned as the response parameter, in your success function in your AJAX call.
I hope any of this helps.
Related
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 want a local file (on the server) to be downloaded by the user. The user first kicks off the file creation by pressing a button and once the file is ready, he should be able to clock on a link or a button to download the file.
Creating the file has not been a problem, as i simply send an AJAX call to my backend which looks like
#POST
#Path("/createFile")
#Produces("application/text")
#Consumes("application/json")
public String createFile(String argsFromPage) {
/*File creation code here*/
return "Path of file created";
}
Now, that the file is created, all I want is to create a link which the user can click and download this file. For now, the file can be either a binary or a CSV file. I have made several attempts but without any success
<button onclick='create_file()'>Create</button>
function create_file() {
$.ajax({
method : "POST",
url : ".path/to/backend/service",
contentType : "application/json",
data : JSON.stringify({
param1 : val1
})
}).done(function(data) {
console.log(data);
});
}
now once the file has been created, is it possible to create a download link? Better still, is it possible to invoke the download as soon as the file is created? Should this be done in the browser, or the back end?
Follow Up
Once the file has been downloaded, how can i delete it form the server? Is there any way to endure that the file download has been completed?
To create a link to the file you can just create an a element in the DOM within the done() handler. Try this:
function create_file() {
$.ajax({
method: "POST",
url: ".path/to/backend/service",
contentType: "application/json",
data: { param1: val1 } // I assume 'val1' is declared in a higher scope?
}).done(function(path) {
$('#someContainer').append('Click here to download');
});
}
Note that I removed the manual JSON.stringify call as jQuery will do this for you. Also note that it would be better to return JSON from the AJAX request as it avoids issues with whitespace, although the above should still work given the code sample you provided.
I have this function on the client-side
function ajaxPost(obj){
$.ajax({
type: "POST",
url: "url to the php file",//I'm not sure about this line
contentType: 'application/json',
data: JSON.stringify(obj),
dataType: 'json'
});
}
and this php on server-side
<?php
$json = file_get_contents('php://input');
?>
I'm calling ajaxPost function on button click from client side. So when i call the function php on the server puts the json object inside $json variable.
How to paste this json object to existing .js file on the server while replacing previous code inside .js file.
So the object send from the client side must replace already existing .js content.
So what im trying is to change the script inside this .js file on the server with the passed object from the client
To clearify im using this .js file on the server as an API that i call from the client side every minute but i want to be able to change its content from an admin panel
I need to send variables (username+password) from a js function inside a .js file, to a PHP file, and store them inside the file.
I tried to use ajax but it doesn't work for me:
function func(){
var user = ...
var pass = ...
$.ajax({
type:"POST",
url:"myphp.php",
data: user,
success: function(){
alert("success!");
},
error: function(){
alert("error!")
}
});
}
when I open the PHP file I see nothing.
EDIT: my problem is much more basic. My ajax code just doesn't run inside the function. I have a .js file that contains only one function (the function above) and the ajax code doesn't get executed. I get no success nor error messages.
You need to pass the data to jQuery like this:
$.ajax({
type:"POST",
url:"myphp.php",
data: {user: user, password: pass},
success: function(data){
alert(data);
}
});
PHP won't have any problems parsing this, since jQuery automatically sends it in application/x-www-form-urlencoded. If you need to send JSON and have PHP read JSON, then that's a different story.
I'm currently trying to use Ajax to use my php array in javascript. Even though I have json encoded the array, set the php content-type, and ajax datatype, it looks like javascript is still trying to process my php script instead of the json it outputs. This is because I always get a 'Unexpected Token <' error (the beginning of my php script).
Here is my ajax:
$.ajax({
type: 'GET',
cache: false,
url: 'api.php',
dataType: "json",
error: function(jqXHR, textStatus, errorThrown) {alert(errorThrown);},
success: function(data) {
alert(data);}
});
And here's my php (filename is api.php):
<?php
header('Content-Type: application/json');
$aliases = array('angry','birds');
echo json_encode($aliases);
?>
I know my php outputs the correct json format, because when I run it in my browser, the output is ["angry","birds"]
Can't seem to figure out what's going on.
It seems like you're trying to send a request via file system. You're getting the original source code back, because the server/PHP doesn't parse your file.
If you're opening your page via file system (e.g file://some/path/test.html) then the request gets send via file system too. Either you open your page from the server or you need to specify the full qualified location then. I.e. in your case something like http://localhost/api.php.