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?
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'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;
}
});
I am trying to solve one problem with reading json object sent via ajax request in php file and I am keep gettin null in the console.
Javascript file
//create function to send ajax request
function ajax_request(){
console.log("hello");
var post_data = {
"news_data" : 'hello',
"news_date" : '1st march'
}
$.ajax({
url : 'index.php',
dataType : 'json',
type : 'post',
data : post_data,
success : function(data){
console.log(data);
}
});
}
//on click event
$('#news_post_button').on('click', ajax_request);
and php file which is only for testing to see what i get
<?php
header('Content-Type: application/json');
$aRequest = json_decode($_POST);
echo json_encode($aRequest[0]->news_data);
?>
Try using json_last_error function.
And print out Your post as a string:
print_r($_POST);
echo '<br /> json_last_error: '.json_last_error();
This way You will see what You got and what potentially had gone wrong.
For testing this kind of things I suggest Postman chrome extension.
You aren't sending a JSON object at all.
You are passing jQuery an object, so it will serialise it using standard form encoding.
<?php
header('Content-Type: application/json');
echo json_encode($_POST["news_data"]);
?>
If you want to actually send a JSON text, then you need to:
Set the content type of the request
Encode the data as JSON and pass it as a string to data
See this answer for an example.
To read the JSON, you would then need to read from STDIN and not $_POST as per this answer/
You can read properties of objects directly in $POST var, like this:
$_POST['news_data'] and $_POST['news_date']
You can check the post vars through the developer tools of the browser, in network tab.
The dataType property of the $.post options specifies the format of data you expect to receive from the server as a response, not the format of the data you send to the server. If you send data by the method POST - just like you do, if you use $.post - there is no need to call $aRequest = json_decode($_POST); on the serverside. The data will be available as a plain PHP array.
If you just want to get the news_data field as a response from the server, your serverside script should look something like this:
<?php
header('Content-Type: application/json');
$post = $_POST;
echo json_encode($post['news_data']);
?>
Notice, that you should check for the key news_data whether it is set.
Edit: changed $.alert() to alert()
I've got a file, planner.php that uses JQuery to send an ajax request to the same page.
Using the debugger, I can see that the php correctly gets the request, accesses my database, and then sends the data. However even after sending it I get no success callback in the javascript. What's wrong?
JQuery:
$(function()
{
$.post('planner.php', {"want": "keys"}, success_func, 'json');
});
function success_func(result)
{
//This is never called :(
alert("Worked");
}
PHP:
<?php
require_once "./php/couch.php";
require_once "./php/couchClient.php";
require_once "./php/couchDocument.php";
if (count($_POST) > 0 && array_key_exists("want", $_POST)) {
$couch_dsn = "http://localhost:5984/";
$couch_db = "subjects";
$client = new couchClient($couch_dsn, $couch_db);
header('Content-type: application/json');
$response = $client->getView('subject_views', 'keys');
echo json_encode($response); //This all seems to work fine
}
?>
It's that simple. All of the PHP code there is just accessing couchDB which you don't have to worry about because I know that $response is set correctly.
For knowing where the ajax call is done or faced a error
$(function()
{
$.post('planner.php', {"want": "keys"},function(){
alert( "success" );
})
.done(function(){
alert("second success");
})
.error(function(){
alert("error");
});
});
link : http://api.jquery.com/jquery.post/
This is probably be cause there is no such thing like $.alert(), use simple alert() instead.
Also your success_func is declared below the ajax call, move it up before $.post();
EDIT:
as the function is declared, there is no need to type it before executing.
you can use like that it may be your sucess function not calling
var data = 'want=keys';
$.post(
'planner.php',
data
).success(function(resp){
json = $.parseJSON(resp);
alert(json);
});
Credit to vivek for giving me a method to work out the problem.
Basically I fundamentally didn't understand how php worked. The code for sending the POST response was halfway down the page, so PHP was sending back the entire page along with any extra json I had encoded, and then JQuery attempted to parse this html page as json, failed, and then didn't run the success function because it never succeeded in its request. Read this answer for some more insight
The obvious solutions are:
Make a new page for the response
Put the php at the top of the
page.
I ended up going with option #2 for simplicity's sake.
Thanks everyone!
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.