How do I write a POST variable to a text file within SharePoint 2010 - ajax

I’m working on a project that uses SharePoint 2010. I need to write a POST variable to a file using an ajax call.
If I were using PHP I would use the fwrite() function to write the POST to a file.
Here is how I envision my solution working. When you go to notarealwebsite.com and submit the form, I envision using an ajax call to write the file. The ajax on the index.php would look like:
$.ajax({
type: 'POST',
url: 'save-text.php',
data: {json: JSON.stringify(strJson)}
});
In PHP I would pass the POST variable into the save-text.php file and its code would look like this:
<? php
$file = fopen("file.txt","w");
fwrite($file, $_POST['json']);
fclose($file);
?>
Does SharePoint have an equivalent function I can use to save the POST to a file?

You don't give us too much here...
You can develop something in JavaScript using a third library like SharepointPlus with the createFile function
You'll do:
$SP().createFile({
content: JSON.stringify(strJson),
destination: "http://mysite/Shared Documents/file.txt",
url:"http://mysite/",
after:function() {
alert("File saved");
}
});
The createFile of SharepointPlus uses the CopyIntoItems web service of Sharepoint.

In SharePoint environment, you would most probably write these strings to list instead of file system. This is especially true if its some kind of configuration value because you want it accessible from all the frond end machines. A file on a filesystem will be created on just a single node where the code runs ultimately after the load balancer.
See:
How to: Create, Update, and Delete List Items
http://msdn.microsoft.com/en-us/library/office/ee539976(v=office.14).aspx

Related

Is a view required to use ajax?

I'm migrating a site to django, and part of that is some ajax calls to php scripts. All I keep getting back from my ajax calls are the contents of the php file, not the results of the script being executed.
Not sure if this is because I'm only using the django dev server (project not in a folder processed by apache) or if I need url.py and views.py entries for the ajax call...
My ajax call from my js file:
function getLab(labId) {
let data = new Object();
data['ID'] = labId;
$.ajax({
url: "/static/php/fetchLab.php",
type: "get",
data: data,
success: getLabFinish
});
}
And the response is the contents of the php file:
<?php
require('/static/php/log.php');
require('/static/php/config.php');
$log = new Log();
...
For this to work, something must take this PHP script(s) and pass them to an PHP interpreter. Otherwise you receive the script as text, as the server threats them like that. You might have encountered the same effect when you serve PHP files with a webserver that is not configured with PHP properly.
Your guess regarding apache isn't that wrong. You might configure a local apache with the PHP module enabled to receive their desired output.
This approach might be sufficient while migrating, but it is definitely not recommended as a result of your migration.
As a workaround you might also replace the PHP script with dummy output and provide them in the static folder. This way you can already prepare other parts of your application and migrate them later.
As already mentioned you want to end up with corresponding views in your django project.
I agree with what dahrens and Jerin Peter George have said. It definitely sounds like you do not have PHP installed on the server, which wouldn't be needed in a python/django environment. Therefore the ajax request is getting back text from the php file.
I will add some context for you to get an idea of what an ajax request and response would look like in django 2.x
in your javascript (frontend)
$.ajax({
url: '/save/json/',
method: 'POST',
data: {"data":"content"}
})
in your views.py
def save_json(request):
if request.is_ajax():
if request.method == 'POST':
incoming_json_data = json.loads(request.body)
# DO STUFF WITH THE JSON DATA
HttpResponse("OK")
in your urls.py
urlpatterns = [
path('save/json/', views.save_json),
]

How to get json data from Server with jquery mobile?

I am trying to get the Bitcoin course from a web server.
Then we try it with a JSON from local, it works.
In Firebug, I can see the get request to bitcoincharts.com, but there is no answer.
What's wrong with my code?
$('#LitecoinMenue').append('<p><b>Litecoin: 42</b></p>');
$.getJSON('http://api.bitcoincharts.com/v1/weighted_prices.json',
function(data){
$.each(data.USD, function(index,item){
$('#BitcoinMenue').append('<p><b>Bitcoin:'+ item+'</b></p>');
});
});
The reason your code doesn't work is because of a rule called Same-origin policy. This rule requires that all AJAX requests are made to a file on the same domain name. It is not possible to use $.getJSON, or any other AJAX function to load a file from an external domain.
There are only a few options available, the most common is to create a PHP file to act as a proxy, and store it on the same domain. For example:
proxy.php
<?php
$url = base64_decode($_GET['url']);
return file_get_contents($url);
?>
Your page above
$('#LitecoinMenue').append('<p><b>Litecoin: 42</b></p>');
$.getJSON('proxy.php?url=aHR0cDovL2FwaS5iaXRjb2luY2hhcnRzLmNvbS92MS93ZWlnaHRlZF9wcmljZXMuanNvbg==',
function(data){
$.each(data.USD, function(index,item){
$('#BitcoinMenue').append('<p><b>Bitcoin:'+ item+'</b></p>');
});
});
Important Notes:
This is just an example. In a real life situation you would probably want to use cURL to get your file. You should also ensure that it is secured so that someone cannot use Firebug to send an AJAX request to fetch a big file (like a movie) or your server could crash.
As you can see, the URL is base64 encoded. This is to ensure that it gets processed correctly as sometimes there are issues when passing an unencoded URL as a GET parameter. You can encode and decode base64 strings with these online converters: http://base64encode.org and http://base64decode.org, or you can use the built in PHP functions base64_encode() and base64_decode().

Loading a JSON file in Firefox Addon Page Script, everything locally within the package

I have been developing a Firefox extension using the Addon SDK and need to load some data that is stored in the same package, as a separate file: "data.json". It needs to be loaded from a page script, i.e. "loader.js" which is included in the "panel.html" using the script src tags.
The structure is like this:
+data
panel.html
panel.js
loader.js
data.json
...
+lib
main.js
...
panel.html has:
<script type="text/javascript" src="loader.js"></script>
Initially we stored the data simply into a js file as "data.js" and included from the "panel.html" using script src tags and it worked without any problems. However when we submitted the add-on to the Mozilla Addon site, this was addressed as one of the issues to fix, saying that we need to use a non-executable format, such as a JSON file to make it more safe.
Now the problem seems like "loader.js" is not allowed to make a AJAX request to "data.json". (Using the JQuery $.ajax() call returns with no success, giving the error code 0) So the solution I have been thinking of is to load "data.json" from "main.js" using the SDK's request() function and somehow pass it to the "loader.js", the page script. But that seems to be complicated since, as far as I understand, the data needs to be first sent to a content script, and then from there to the page script. And this needs to be happen when the page script is loading! I am confused about this since I am not sure if I am missing a much more practical solution, or is it really something complicated what I am trying to do, simply loading local JSON data in the package into a local page script?
Here's an example on the Add-on Builder that explores and approach to this.
First off, you can load the json file from data and parse it using self.data.load:
let data = require('self').data;
let taps_data = JSON.parse(data.load('taps.json'));
This loads synchronously, so it isn't something you want to do often, in the example it would only happen when the add-on firsst becomes active in a browsing session.
Next, you would use content scripts and message passing to pass the data in to the panel.
In the main.js script:
panel.on('show', function() {
if (!loaded)
panel.port.emit('taps-data', taps_data);
});
In the content script:
self.port.on('taps-data', function(data) {
$('#list').html('');
data.forEach(function(item) {
$('#list').append('<div>'+ item.name +'</div>');
});
self.port.emit('taps-loaded');
});
I do a bit of extra work to make sure I'm only emitting the data once. The data, FYI, is saved from the live beer keg data api from my local pub.

Screen scraping and proxies using Ruby

I know there are several screen scraping threads on here but none of the answers quite satisfied me.
I am trying to scrape the HTML from an external web page using javascript. I am using $.ajax and everything should work fine. Here is my code:
$.ajax({
url: "my.url/path",
dataType: 'text',
success: function(data) {
var myVar = $.get(url);
alert(myVar);
}
});
The only problem is that it is looking for the specified url within my web server. How do I use a proxy to get to an external web page?
Due to Cross Site Scripting restrictions, you're going to have to pass the desired URL to a page on your server that will query the URL in question from serverside, and then return the results to you. Take a look at the thread below and the incorporate that into your application and have it return the source when that page is hit by your AJAX function.
How to get the HTML source of a webpage in Ruby
Using a GET request is going to the be easiest way to transfer the URL of the page you want to fetch your server so you'll be able to call something like:
$.ajax("fetchPage.rb" + encodeURI(http://www.google.com))
Because you can't access the side in question directly from the server, you're going to have to pipe the serverside script through a proxy for the request to work, which really kind of depends on your setup. Taking a look at the Proxy class in Ruby:
http://ruby-doc.org/stdlib-1.9.3/libdoc/net/http/rdoc/Net/HTTP.html#method-c-Proxy

Ajax requests ignore virtual application sub-folder name in URL for ASP.NET MVC application

My application is located on the server under a separate virtual directory. To access my ASP.NET MVC application users have to go to:
http://server-dev/superApp
I have a problem with Ajax/Json server requests ignoring the "superApp" directory part. Whenever an Ajax request is made Fiddler shows 404 because instead of http://server-dev/superApp/User/GetUsersJson for example, http://server-dev/User/GetUsersJson is called (note the missing superApp name).
Example of an Ajax request:
function GetUsers(id) {
$.ajax({
url: "/User/GetUsersJson/",
data:{ id: id},
datatype: 'json',
type:'post',
success: function (result) {
////Do stuff with returned result
}
});
}
Registered route:
r.Match("User/GetUsersJson", "User", "GetUsersJson");
Where should I look and what can I change to make sure that my application virtual folder is ALWAYS included in all URL requests ?
p.s. Please note that all Javascript/Ajax logic is kept in separate .js files so no RAZOR syntax is available.
Did you try using the HTML helper method ?
url: "#Url.ACtion("GetUsersJson","User)"
EDIT : As per the comment
You may get the Path name using the HTML Helper method and Keep that in a Global variable and access that in the external javascript file
In the view
<script type="text/javascript>
var globalGetJSONPath='#Url.ACtion("GetUsersJson","User)';
</script>
And now you can use it in the external file like this
$.ajax({
url: globalGetJSONPath,
data:{ id: id},
//remaining items....
});
I solved this stuff by passing variable to js that contains hostname+vdir. Because of heavy js url generation.
In other cases Shyju's answer is best way to solve this.
No way to do it without some server-side code generation. Easiest thing would be defining global variable (sorry) holding you application root and initializing it somewhere in master page.
Javascript generation of route urls always was one of the messiest parts of asp.net mvc.

Resources