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.
Related
In php file:
if(isset($_POST["my_first_variable"]))
{
if(empty($_POST["my_first_variable"]))
{
//This $rtrn variable I need to return to another ajax function in
another javascript file
$rtrn["my_return_second_variable"]="First variable is empty";
echo json_encode($rtrn);
}
}
From first javascript file I send input data variable to php, where I check If that value is not empty and correct , If it is I need to send returning data to another javascript file that tells that input is empty or incorrect to disable submit button on main page.
PHP cannot arbitrarily send data to some random file. It sends data back to the file which requested it.
You need your Javascripts to communicate with each other:
myscript.php
if(isset($_POST["my_first_variable"]))
{
if(empty($_POST["my_first_variable"]))
{
//This $rtrn variable I need to return to another ajax function in
another javascript file
$rtrn["my_return_second_variable"]="First variable is empty";
echo json_encode($rtrn);
}
}
first.js
$(function(){
$.ajax({
url: 'www.example.com/myscript.php', // Send a request with POST data to this file
type: 'POST', // Send as a POST and not GET
data: { 'my_first_variable' : '' }, // Make sure this data is set but empty to satisfy the logic in myscript.php
dataType: 'json', // We expect to receive JSON data
success: function( data ){
doSomething( data ); // Send this data to second.js
}
});
});
second.js
function doSomething( incomingData ){
alert( incomingData[ 'my_return_second_variable' ] );
}
Make sure to load both of these files and it should work.
For the sake of anyone using Google, some common search phrases could be:
How to send data from one JS file to another?
How can PHP split which JS files receive data?
Pass data from one Js file to another.
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.
i have been reading some posts here regarding issues about storing values form JS to a PHP variable and most comments said to use AJAX.
both AJAX and JS codes can be used to store JS variable value to a PHP variable however can someone explain why most people suggest to use AJAX? or what advantages do I have if I used AJAX over JS to store that value
thanks
You cannot store a PHP value from javascript/jQuery without using AJAX.
After the DOM has been rendered, no additional PHP will run. That's it, all done. In order to send additional data to the server, you have two choices: (1) post a form to another PHP file, which will send the data typed into the form elements and will change/refresh the current page. or (2) use AJAX.
AJAX is a way to communicate with a separate PHP page, sending data back/forth, without refreshing/changing the page the user is on. An AJAX code block looks something like this:
$.ajax({
type: 'post',
url: 'ajax.php',
data: 'varName=' +varSomething,
success: function(d){
if (d.length) alert(d);
}
});
or
$.ajax({
type: 'post',
url: 'ajax.php',
data: 'varSomename=' +varValue
}).done(function(){
//success function
});
Data sent back from PHP is received in the AJAX code block's success function (and ONLY there), where it can be manipulated and/or injected back into the DOM, like this:
$.ajax({
type: 'post',
url: 'ajax.php',
data: 'thevar=' +theval,
success: function(d){
$('#someDIV').html(d);
}
});
Here are some additional links re AJAX:
dynamic drop down box?
Prevent Page Load on Jquery Form Submit with None Display Button
When the data arrives at the specified PHP file (ajax.php in above examples), you can get that data via the $_POST[] variable:
<?php
$summat = $_POST['someVarname'];
//To send data back to the AJAX success function, you just echo it:
$out = '<div style="font-size:3rem;color:blue;">';
$out .= $summat;
$out .= '</div>';
echo $out
Now you have the data in a local PHP variable. This variable will cease to exist when the PHP file execution is completed.
To retain the PHP variable, use a $_SESSION super-variable. In order to use the $_SESSION variable, you must add session_start() to the top of the PHP page:
<?php
session_start();
$_SESSION['summat'] = $_POST['someVarname'];
//Now you have a permanent variable on the server, associated with this user's PHP session
I am trying to post some variables to PHP server via json. One of this variable contains huge string. When I post data all other variable get posted successfully but one that contains huge string remains undefined.
If I make content of that variable sort, then its running fine.
$.ajax({
type: 'POST',
url: url,
data:{name:”aaa”,age:”aaaaa”,detail:”huge string”},
async:false
}).done(function( data ) {
alert(data);
}).fail(function() {
$.notify("Cannot connect to server", "error");
});
please check your php.ini setting for directive
post_max_size
and try to increase like as below
ini_set('post_max_size' '20m')
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.