Why does the following php file does not work? - javascript

The following is the log.php file that is running on google app engine locally (on localhost).
<?php
if (isset($_POST['name'])) {
$name = $_POST['name'];
$filename = "log.txt";
file_put_contents($filename, $name, FILE_APPEND | LOCK_EX);
}
?>
I am calling the above file using the following jquery call:
$.ajax({
url: './php/log.php',
type: 'POST',
data: {name: name},
success: function (data) {
console.log(data);
}
});
I believe the ajax is working as I get a log on console which is just the entire php code. But the php is not writing anything into the log.txt file. Can anyone please help?

As you get in the AJAX response the entire PHP code then you most probably don't have the App Engine or PHP configured properly.
Since you get the PHP code as plain text, then the server isn't configured to run it as code and does not recognize it as such.
Check that.

Related

Writing to JSON file using ajax and php. Server not recieving POST

I tried following the steps in a few other stackoverflow questions, but for some reason my server is not showing any indicator of recieving a request. I know that the client is sending the request since it shows up in firefox debugger.
Here is the js method:
function writeToFile(dat) {
$.ajax({
url : 'dataSaveAjax.php',
method : 'post',
data : { 'data': JSON.stringify(dat) },
success : function( response ) {
alert( response);
}
});
}
PHP code:
<?php
$fp = fopen('general.json', 'w');
fwrite($fp, json_encode($_POST['data']));
fclose($fp);
?>
Try updating your code like that
<?php
$fp = fopen('general.json', 'w');
$writtingResponse = fwrite($fp, $_POST['data']);
fclose($fp);
echo $writtingResponse;
?>
You did not write any response and you encode json twice.
first you need to understand what is the reason and why our script does not work. First, let's look at the server part (php). First, put the data in a variable, instead of $ _POST ['data'] try to do something like:
<?php
$fp = fopen('general.json', 'w');
fwrite($fp, 'MyTest');
fclose($fp);
?>
If this does not work, most likely the reason is that you need to set the write permissions for the file (Chmod).
If everything is recorded correctly, then something is wrong with the client part of your site. When it comes to POST / GET queries, I usually use Postman. It allows not only to test requests, but also to generate code. If you run a query through Postman and the result is written to a file, then the error is unambiguous in javascript. Try to press F12 in the browser and go to the js console, there you will see an error message. Do you use jQuery in the example, and is it connected? Is it connected before you try to execute the script?
Try to look at the data that you are trying to send using console (F12)
console.log(JSON.stringify(dat));
Are your data really going to be collected, or are you trying to send empty data to the file?

can not Send data to php file using ajax

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.

AJAX sucess writing to file but file is empty

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.

Garbage output while downloading apk from server using PHP

I'm using PHP to compile an app on an apache server based on the input provided by the user and then provide the app to them using the readfile() method.
The problem that I'm facing is that instead of actually downloading the app, the .apk file is being opened as a text file.
I have added the android app mime type in the PHP code.
My php code is :
<?php
echo "Please wait while the app is being generated, it can take around 10 minutes for the build to finish.The completed app will be mailed to you ";
if(isset($_POST['timestamp']))
{
$uid = $_POST['timestamp'];
exec("sudo python /var/www/html/appgenserver.py $uid");
header("Content-Description: File Transfer");
header("Content-Type: application/vnd.android.package-archive");
header("Content-Transfer-Encoding: Binary"); //Adding or removing this hass no effect
header('Content-Disposition: attachment; filename="Foo.apk"');
ob_clean();
flush();
readfile("/var/www/html/".$uid."/releaseapk.apk");
exit();
}
?>
Any help would be appreciated.
I think you can solve it by removing the echo. Don't output to the page before the headers have been sent.
The garbled output caused by the buffer is not clean, search for the output on the page before headers or Try using ob_end_clean() instead of ob_clean() and put it before your header()
So what I did was, rather than return the app from PHP script, I returned it URL to the AJAX call.
From there I navigated to that URL and the download initiated automatically.
PHP code :
<?php
{
echo "http://server_ip/release/".$uid."/releaseapk.apk";
}
?>
Ajax cal :
$.ajax({
type: "POST",
url: "/test.php",
data: { timestamp : timestamp },
success: function(response){
console.log("Success",response);
window.location = response;
}
});

PHP request through AJAX fails

This is probably something very simple, and I've seen that there are/have been more people with the same issue. But the solutions provided there did not seem to work.
So, I want to execute a .php file through AJAX. For the sake of testing the php file (consolefunctions) is very small.
<?php
if(isset($_POST['action'])) {
<script>console.log('consolefunctions.php called.');</script>
}
?>
And now for the javascript/ajax part.
$(".startConsole").click(function(){
var consoleID = $(this).attr("value");
$.ajax({ url: 'include/consolefunctions.php',
type: 'post',
data: {action: 'dosomething'},
success: function(output) {
//alert("meeh");
}
});
});
Somewhere, somehow there's an issue because the message from the PHP file never shows. I've tested the location from the php file, which is valid.
First the php code is not correct, you should add an echo
<?php
if(isset($_POST['action'])) {
echo"<script>console.log('consolefunctions.php called.');</script>";
}
?>
but the problem is, when you send this code to js, you'll get it as a string on your variable output, not as a code that will be executed after making the ajax call, so the best way to do this is to echo only the message to display on your console and then once you receive this message you can call console.log function
<?php
if(isset($_POST['action'])) {
echo"consolefunctions.php called";
}
?>
in the success function :
console.log(output);

Categories