My web server sends a xmlhttprequest to write a JSON file whenever a button is clicked. However, the file has only read permissions when written. Also, this ONLY happens when the web server asks the cgi script to execute. However, if I try executing this cgi script myself from command line, the file is written with both read and write permissions. Is there any way I can allow the web server to make this cgi script write a file with full permissions?
As requested, here is the part of my code which sends the xmlhttprequest and fetches/the json file.
<script>
function loadXMLdoc() {
var xmlhttp = new XMLHttpRequest();
var url = "/cgi-bin/run.cgi"
var id = document.getElementById("inputId").value;
var mutation = document.getElementById("inputMutation").value;
var position = document.getElementById("inputPosition").value;
var json;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status==200) {
$.getJSON("data.json",function(result){
$.each(result, function(i, field){
output = "<h1>Output<h1>"
for (var f in field){
output+="<p>Identifier: " + field[f]["value"]+" Position: "+field[f]["position"]+" Mutation: "+field[f]["mutation"]+"</p>"
}
});
});
document.getElementById("test_container").innerHTML = output
}
}
xmlhttp.open("GET", url+"?id=" + id + "&mutation=" + mutation + "&position=" + position, true);
xmlhttp.send()
}
</script>
And here's the part in run.cgi which writes the file.
write_file = open("%s/data.json" %(root_directory), 'w')
write_file.write('{"results": [\n')
for i,result in enumerate(results):
write_file.write('\t{"value": "%s", "mutation": "%s", "position": "%s"}' % (result["value"], result["mutation"], result["position"]))
if i != len(results) - 1:
write_file.write(",")
write_file.write("\n")
write_file.write("]}")
write_file.close()
Related
I'm trying to make javascript read a .txt file that contains links to websites, and with that can I press a button to get sent to a random website.
But my code won't work, I have tried a lot of things...
Here is my code
<script>
var sites = [];
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function () {
if(rawFile.readyState === 4) {
if(rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
alert(allText);
callback(allText);
}
}
}
rawFile.send(null);
}
readTextFile("file:../Nicklas Behrend/Desktop/links.txt", filesText =>{
sites = filesText.split('\n');
});
function randomSite() {
var i = parseInt(Math.random() * sites.length);
location.href = sites[i];
}
</script>
At this part it says
expression statement is not assignment or call
readTextFile("file:../Nicklas Behrend/Desktop/links.txt", filesText =>{
sites = filesText.split('\n');
});
When I press the button that I made, I get to a site that says "404 not found"
You cannot access file protocol (file:) using XMLHttpRequest.
Meaning the file you are trying to access must be uploaded to a server and get the path (e.g., http://...) before you can get it through XMLHttpRequest.
i was trying to write a javascript program which read list of token from the configuration file and set the token. But javascript program failed to read my local configuration file.
javascript program below
require([
"splunkjs/mvc",
"splunkjs/mvc/simplexml/ready!"
],
function(mvc) {
var defaultTokenModel = splunkjs.mvc.Components.getInstance("default");
alert("start");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.status == 200) {
var allText = xhttp.responseText;
alert('Text = ' + allText)
}
};
xhttp.open("GET", "rejected_panels.conf", true);
xhttp.send();
alert("end");
defaultTokenModel.set('home_panel_1', 'yes');
});
I am accessing javascript from splunk's simple xml as below
<form script="rejected_panels.js">
....
....
</form>
I got this error in chrome browser
rejected_panels.js:21 GET http://localhost:8000/en-GB/app/multi_tOP/rejected_panels.conf 404
Kindly Help me on this.
This is a tangent from the question here:
Returning value to Javascript from PHP called from XMLHttpRequest
I am adding an "image upload" button to my AjaxChat. I am using an XMLHttpRequest to send the image to the server, where I run a PHP script to move it to my images folder. Below is the Javascript function in charge of opening the XMLHttpRequest connection and sending the file:
function uploadImage() {
var form = document.getElementById('fileSelectForm');
var photo = document.getElementById('photo');
var uploadButton = document.getElementById('imageUploadButton');
form.onsubmit = function(event) {
event.preventDefault();
// Update button text
uploadButton.innerHTML = 'Uploading...';
//Get selected files from input
var files = photo.files;
// Create a new FormData object
var formData = new FormData();
// Loop through selected files
for (var i = 0; files.length > i; i++) {
var file = files[i];
// Check file type; only images are allowed
if (!file.type.match('image/*')) {
continue;
}
// Add file to request
formData.append('photo', file, file.name);
}
// Set up request
var xhr = new XMLHttpRequest();
// Open connection
xhr.open('POST', 'sites/all/modules/ajaxchat/upload.php', true);
// Set up handler for when request finishes
xhr.onload = function () {
if (xhr.status === 200) {
//File(s) uploaded
uploadButton.innerHTML = 'Upload';
var result = xhr.responseText;
ajaxChat.insertText('\n\[img\]http:\/\/www.mysite.com\/images' + result + '\[\/img\]');
ajaxChat.sendMessage();
} else {
alert('An error occurred!');
}
form.reset();
};
// Send data
xhr.send(formData);
}
}
Here is upload.php:
<?php
$valid_file = true;
if($_FILES['photo']['name']) {
//if no errors...
if(!$_FILES['photo']['error']) {
//now is the time to modify the future file name and validate the file
$new_file_name = strtolower($_FILES['photo']['tmp_name']); //rename file
if($_FILES['photo']['size'] > (1024000)) { //can't be larger than 1 MB
$valid_file = false;
}
//if the file has passed the test
if($valid_file) {
//move it to where we want it to be
move_uploaded_file($_FILES['photo']['tmp_name'], '/var/www/html/images'.$new_file_name);
$message = $new_file_name;
exit("$message");
}
}
}
?>
I currently have the multiple image upload disabled, so the "Loop through selected files" only executes once.
The upload worked for a little bit on my PC, but then I tried uploading an image from my phone. When I did so, the entire server (and my browser) crashed, presumably due to an infinite loop somewhere. Every time I close my browser and log back in, or restart the server, or restart my computer, it hangs and eventually crashes again (on my PC or on my phone). I have been unable to find the script that is causing the issue. I get the feeling it's right under my nose. Does anyone see the problem? If you need the HTML form code then I can provide that, but I don't think it's necessary.
This is a sample javascript code from http://locationdetection.mobi to detect geo location using google API.
(Original zip file contains a php file, html, and this javascript code)
As you see in the code below, on the last part of this javascript code there is one line of code to render the result of location detection to html file.
How to generate result into a text file instead of render to browser?
// this is called when the browser has shown support of navigator.geolocation
function GEOprocess(position) {
// update the page to show we have the lat and long and explain what we do next
document.getElementById('geo').innerHTML = 'Latitude: ' + position.coords.latitude + ' Longitude: ' + position.coords.longitude;
// now we send this data to the php script behind the scenes with the GEOajax function
GEOajax("geo.php?accuracy=" + position.coords.accuracy + "&latlng=" + position.coords.latitude + "," + position.coords.longitude +"&altitude="+position.coords.altitude+"&altitude_accuracy="+position.coords.altitudeAccuracy+"&heading="+position.coords.heading+"&speed="+position.coords.speed+"");
}
// this is used when the visitor bottles it and hits the "Don't Share" option
function GEOdeclined(error) {
document.getElementById('geo').innerHTML = 'Error: ' + error.message;
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(GEOprocess, GEOdeclined);
}else{
document.getElementById('geo').innerHTML = 'Your browser sucks. Upgrade it.';
}
// this checks if the browser supports XML HTTP Requests and if so which method
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}else if(window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// this calls the php script with the data we have collected from the geolocation lookup
function GEOajax(url) {
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = updatePage;
xmlHttp.send(null);
}
// this reads the response from the php script and updates the page with it's output
function updatePage() {
if (xmlHttp.readyState == 4) {
var response = xmlHttp.responseText;
document.getElementById("geo").innerHTML = '' + response;
}
}
You can't create text files from the frontend, well at least not without configuring some flags in the browser, so you need to send the data to your backend language, create the file and then download it
So I have this HTML file that tests the user's screen resolution, and plugins installed using Javascript. So when the user accesses the page it sees: (e.g.) Your current screen resolution is 1024x768 and you have the following plugins installed: Plug-in No.2- Java Deployment Toolkit 7.0.10.8 [Location: npdeployJava1.dll], Plug-in No.3- Java(TM) Platform SE 7 U1 [Location: npjp2.dll], Plug-in No.4- Microsoft Office 2003 [Location: NPOFFICE.DLL]... I also need to save this information in a file on the server. All users are having firefox or chrome. How do I do this using AJAX?
<html>
<body>
<script language="JavaScript1.2">
document.write("Your current resolution is "+screen.width+"*"+screen.height+"")
</script>
<BR><BR>
<SCRIPT LANGUAGE="JavaScript">
var num_of_plugins = navigator.plugins.length;
for (var i=0; i < num_of_plugins; i++) {
var list_number=i+1;
document.write("<font color=red>Plug-in No." + list_number + "- </font>"+navigator.plugins[i].name+" <br>[Location: " + navigator.plugins[i].filename + "]<p>");
}
</script>
</body>
</html>
Thanks
Without jQuery (raw JavaScript):
var data = "...";// this is your data that you want to pass to the server (could be json)
//next you would initiate a XMLHTTPRequest as following (could be more advanced):
var url = "get_data.php";//your url to the server side file that will receive the data.
var http = new XMLHttpRequest();
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", data.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);//check if the data was received successfully.
}
}
http.send(data);
Using jQuery:
$.ajax({
type: 'POST',
url: url,//url of receiver file on server
data: data, //your data
success: success, //callback when ajax request finishes
dataType: dataType //text/json...
});
I hope this helps :)
More info:
https://www.google.co.il/search?q=js+ajax+post&oq=js+ajax+post
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
Do you know jQuery? It will be much easier with jQuery.
var data = "";
for (var i=0; i < num_of_plugins; i++) {
var list_number=i+1;
document.write("<font color=red>Plug-in No." + list_number + "- </font>"+navigator.plugins[i].name+" <br>[Location: " + navigator.plugins[i].filename + "]<p>");
data += "<font color=red>Plug-in No." + list_number + "- </font>"+navigator.plugins[i].name+" <br>[Location: " + navigator.plugins[i].filename + "]<p>";
}
$.post('savedata.php', {data=data}, function(){//Save complete});
Then in savedata.php you can write something like the following:
$data = $_POST['data'];
$f = fopen('file', 'w+');
fwrite(f, $data);
fclose($f);
Do a request from javascript to a page which runs server side code.
Send post request with ajax http://www.javascriptkit.com/dhtmltutors/ajaxgetpost.shtml to for example an apsx page. From aspx you could save it to a text file or database.