Handle json object with php and push it to .js file - javascript

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

Related

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.

Passing Data from ajax in js file to php file and print php

I am trying to send data from a php page to another php page through JavaScript with ajax and the getting the new page to open with the data that was sent so that the user can print the page.. here is the js snippet processDateP and sourceID2 are entered by user.
$("#PrintShelf").click(function() {
$.ajax({
type: "POST",
url: "print2.php",
dataType: "json",
data: ({processDate: $('#processDateP').val(), sourceID: $('#sourceID2').val()}),
success: function(data){
if('#sourceID2' != null ){
window.open('print2.php');
}
}
});
});
I want this to open the file PHP file print2.php, but it either opens the file with no data if i move window.open outside of success function or it sends the data and the page popluates correctly (can see using firebug) but does not open the window..I have run just the print2.php file alone with dummy values and it works and prints.
Thanks in advance

Send javascript object to the server then handle it with php and replace .js file content with this object

I'm trying to update existing .js file on the server with ajax and php the whole content of the .js file must be replaced with the created object objcurrency
The Idea is that index.html page is the website which makes ajax request for data.js every minute and inside this data.js there is object with currency rates strings.
And i have panel.html that is accessed with username and password where i can change these currency rates string on the server.
So when i want to change the currency rates people who have opened the website will get currency rates that i updated instead of refreshing the page
function ajaxPost(obj){
$.ajax({
type: "POST",
url: "js/data.js",
contentType: 'application/json',
data: JSON.stringify(obj),
dataType: 'json'
});
}
$(document).ready(function(){
$('#update').on('click', function(){
var objrates = {
EURbuy : $('#eurbuy').val(),
EURsell : $('#eursell').val(),
USDbuy : $('#usdbuy').val(),
USDbuy : $('#usdbuy').val()
};
ajaxPost(objrates);
});
});
Edits:
Searched some things and came to this so far now i have to add php code that replaces data.js(file content) on the server with $json
<?php
$json = file_get_contents('php://input');
?>

Ajax reading PHP script instead of JSON output

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.

Categories