Write javascript output to file on server - javascript

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.

Related

POST JSON from HTML form to PHP API and download the received file in the browser

I have an existing API that only accepts JSON values via a POST, it responds with a downloadable zip file that is only session based, not on a server. I wanted to create an HTML form that could be filled out and POST the JSON values to the API then receive the download. Once the API receives the JSON it will respond with a Zip file that should be downloaded through the browser. I spent a lot of time searching for how to do this and eventually pulled together the components to make it happen. I wanted to share it here because I saw many other people searching for the same thing but with no clear answers or script that worked, lost of GET examples but no POST with in memory server data. In fact may folks said it just couldn't be done with POST.
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (event) {
//Function montiors for the form submit event
event.preventDefault(); // Prevents the default action of the form submit button
var jsonData = '{"PONumber":"' + form1.PONumber.value //JSON data being submitted to the API from the HTML form
+ '","CompanyName":"' + form1.CompanyName.value
+ '","CompanyID":"' + form1.CompanyID.value
+ '","ProductName":"' + form1.ProductName.value
+ '","Quantity":"' + form1.quantity.value
+ '","Manufacturer":"' + form1.Manufacturer.value + '"}';
var xhr = new XMLHttpRequest();
xhr.open('POST', 'api_page.php', true); //The POST to the API page where the JSON will be submitted
xhr.responseType = 'blob';
xhr.setRequestHeader('Content-type', 'application/json'); //Additional header fields as necessary
xhr.setRequestHeader('Authorization', 'Bearer ' + 'eyJ0eXAiOiJKV1QiLCJhbGciO----< SNIP >---547OWZr9ZMEvZBiQpVvU0K0U');
xhr.onload = function(e) {
if (this.status == 200) {
var blob = new Blob([this.response], {type: 'application/zip'}); //We're downloading a Zip file
var downloadUrl = URL.createObjectURL(blob);
var a = document.createElement("a");
a.href = downloadUrl;
a.download = "download_file.zip"; //The name for the downloaded file that will be saved
document.body.appendChild(a);
a.click(); //Automatically starts the download
} else {
alert('Unable to download file.')
}
};
xhr.send(jsonData); //Sends the JSON data to the destination POST page
});
});
</script>
<form method="post" name="form1" id="form1" action="" >
<td><center><input name="submit" type="submit" value="submit"></center></td>
<td ><strong>ENTER QUANTITY OF UNITS: </strong></td><td> </td>
<td><input name="quantity" type="text" size="17" value="<?php echo $row['value'];?>"></td>
</form>
Here is the code for the PHP server side of the application. The first part is to receive the request.
//Receive the incoming JSON data from the form POST
$jsonRequest = trim(file_get_contents("php://input"));
//Attempt to decode the incoming RAW post data.
$requestDecoded = json_decode($jsonRequest, true);
//Do something with the data and then respond with a zip file.
Here is the PHP code that sends the Zip file back to the original requesting page for download.
$fp = fopen('php://output', 'w'); //Creates output buffer
$mfiles = $yourZipFile
if($fp && $mfiles) {
header("Cache-Control: no-cache");
header("Content-Type: application/zip");
header("Content-Disposition: attachment;
filename=\"".basename($zipName)."\";");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " .strlen($mfiles));
header("Response-Data: ".$responseData);
ob_end_clean();
if (fputs($fp, $mfiles, strlen($mfiles))===FALSE){
throw new Exception($e);
}
}
else {
throw new Exception($e);
}
Place the javascript code in the body of your HTML page and it should work just fine. I hope this helps someone else out there in the same position. I've tried to describe each component as best I can and include all of the pieces to make it work.
Request: Browser --> HTML form --> JSON --> POST --> PHP
Response: PHP --> zip file --> Browser Download --> Local PC

Cant retrieve an XML list from a web service

I have a server running OTRS 5 and I would like to retrieve a list in XML format. I'm running a JavaScript code that should display the list, but instead I get an error.
My local server is https://labcentos3/otrs/mds.pl?Action=ServiceList.
I think its a Perl script that runs on the server side and then displays a list in XML format.
This is what I get if I browse the local link: it gives me the list I want
I wrote HTML and JavaScript to try to do the same for working with the retrieved data later, but I can't get past an error.
HTML
<html>
<head>
<title>XML read</title>
<script src="reader.js" type="text/javascript"></script>
</head>
<body>
<h1>XML File</h1><br/>
</body>
</html>
reader.js
var user = "bla bla bla";
var pass = "bla bla bla"
var getXMLFile = function(path, callback) {
var request = new XMLHttpRequest();
request.open("POST", path);
request.setRequestHeader("Content-Type", "text/plain");
//request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRequestHeader('Authorization', 'Basic ' + btoa(user + ":" + pass));
request.onreadystatechange = function() {
if(request.readyState === 4 && request.status === 200) {
callback(request.responseXML);
}
};
request.send();
};
getXMLFile("https://labcentos3/otrs/mds.pl?Action=ServiceList", function(xml) {
console.log(xml);
});
The error I get in the Chrome console is this:
XMLHttpRequest cannot load https://labcentos3/otrs/mds.pl?Action=ServiceList. The request was redirected to 'https://labcentos3/otrs/index.pl', which is disallowed for cross-origin requests that require preflight.

CGI File Writing File w/only Read Permissions

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()

JavaScript Ajax request not working in Firefox and Google Chrome, but it is okay in Safari

I'm using some JavaScript to send an Ajax request to an Arduino webserver and change the HTML on a webpage.
In Safari this has been working great, but when I try to load it in Firefox and Google Chrome the document elements never update. In the debugger consoles I can see the requests and responses coming back so I'm guessing that there is an issue with parsing the response to an array?
Here is the code:
function GetSwitchState()
{
nocache = "&nocache=" + Math.random() * 1000000;
var request = new XMLHttpRequest();
request.onreadystatechange = function()
{
if (this.readyState == 4) {
if (this.status == 200) {
if (this.responseText != null) {
var response = this.responseText;
var comma = ",";
var inputArray = response.split(comma);
var green = inputArray[0];
var red = inputArray[1];
var fault = inputArray[2];
var counter = inputArray[3];
document.getElementById('green').innerHTML = green;
document.getElementById("red").innerHTML = red;
document.getElementById("status").innerHTML = fault;
document.getElementById("cars").innerHTML = counter;
}
}
}
}
request.open("GET", "url" + nocache, true);
request.send(null);
setTimeout('GetSwitchState()', 1000);
}
The response from the Arduino webserver is four comma-separated values.
Okay it looks like the issue was actually getting past the
{
if (this.readyState == 4) {
if (this.status == 200) {
arguments. When I changed it to:
{
if(response.readState == 4) {
I was able to move past that statement in firefox. To get the status to 200 instead of 0 I needed to modify the response header on the arduino side to include:
Access-Control-Allow-Origin: *
To allow Cross Origin Domain Requests in FireFox. Once I made these changes the code works great, I guess I was barking up the wrong tree with my array assumption.
Thanks for the help!
What I did today was pretty much the same!
When I ran an Ajax request to a PHP file and wanted to return an array I needed to specify the return-datatype as "json". In my PHP file I then returned my values like this:
return json_encode(array(
'success' => false,
'error' => $_POST['password_hashed']
));
I was acctually using jQuery to run the request. That looks like this:
$.ajax({
type: 'POST',
url: 'script.php',
data: 'password_hashed=' + hex_sha512(str_password) + '&email=' + str_email, //Clientside password hashing
cache: false,
dataType: 'json',
success: function(value){
//Ajax successfully ran
alert(value.success + '_' + value.error); //=false_[hash]
},
error: function(){
//Ajax error occured -> Display error message in specified element
alert('error with request');
}
});
I just started with Ajax two days ago, and this may not help a lot, but it is worth trying.

Sending URL as a parameter using javascript

I have to send a name and a link from client side to the server. I thought of using AJAX called by Javascript to do this.
This is what I mean. I wished to make an ajax request to a file called abc.php with parameters :-
1. http://thumbs2.ebaystatic.com/m/m7dFgOtLUUUSpktHRspjhXw/140.jpg
2. Apple iPod touch, 3rd generation, 32GB
To begin with, I encoded the URL and tried to send it. But the server says status Forbidden
Any solution to this ?
UPDATE ::
It end up calling to
http://abc.com/addToWishlist.php?rand=506075547542422&image=http://thumbs1.ebaystatic.com/m/mO64jQrMqam2jde9aKiXC9A/140.jpg&prod=Flat%20USB%20Data%20Sync%20Charging%20Charger%20Cable%20Apple%20iPhone%204G%204S%20iPod%20Touch%20Nano
Javascript Code ::
function addToWishlist(num) {
var myurl = "addToWishlist.php";
var myurl1 = myurl;
myRand = parseInt(Math.random()*999999999999999);
var rand = "?rand="+myRand ;
var modurl = myurl1+ rand + "&image=" + encodeURI(storeArray[num][1]) + "&prod=" + encodeURI(storeArray[num][0]);
httpq2.open("GET", modurl, true);
httpq2.onreadystatechange = useHttpResponseq2;
httpq2.send(null);
}
function useHttpResponseq2() {
if (httpq2.readyState == 4) {
if(httpq2.status == 200) {
var mytext = httpq2.responseText;
document.getElementById('wish' + num).innerHTML = "Added to your wishlist.";
}
}
}
Server Code
<?php
include('/home/ankit/public_html/connect_db.php');
$image = $_GET['image'];
$prod = $_GET['prod'];
$id = $_GET['id'];
echo $prod;
echo $image;
?>
As I mentioned, its pretty basics
More Updates :
On trying to send a POST request via AJAX to the server, it says :-
Refused to set unsafe header "Content-length"
Refused to set unsafe header "Connection"
2 things.
Use encodeURIComponent() instead of encodeURI().
Here is a detailed discussion on this: When are you supposed to use escape instead of encodeURI / encodeURIComponent?
If you are new to JavaScript, use some lib to help you do the AJAX work. Like mootools, jQuery, etc.
Using a POST request solved my issue :)
function addToWishlist(num) {
var url = "trial.php";
var parameters = "prod=" + encodeURIComponent(storeArray[num][0]) + "&image=" + encodeURIComponent(storeArray[num][1]);
httpq2.open("POST", url, true);
httpq2.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpq2.onreadystatechange = function(){
if (httpq2.readyState == 4) {
if(httpq2.status == 200) {
var mytext = httpq2.responseText;
document.getElementById('wish' + num).innerHTML = "Added to your wishlist.";
}
}
};
httpq2.send(parameters);
}

Categories