I am trying to build a marquee that reads from a remote rss feed. The ajax request was failing due to what I can only assume are cross domain restrictions. Here is my code:
$(function () {
$.ajax({
url: 'http://www.theleafchronicle.com/section/news01&template=rss_weblogs&mime=xml',
dataType: 'xml',
type: 'GET',
success: function (xml) {
$(xml).each(function () {
var title = $(this).find("title").text();
var des = $(this).find("description").text() + ' - ';
var wrapper = "<span class='single-feed'></span>";
$(".feed-container").append($(wrapper).html(des));
});
},
error: function (err) { }
});
});
This code failed, so I instead tried downloading the xml locally and it worked. My only concern now is how can I download this code via batch file or possibly a .net executable? I have tried the System.Net.WebClient.DownloadFile method and it brings back a page instead of the intended xml.
class Program
{
static void Main(string[] args)
{
System.Net.WebClient wc = new System.Net.WebClient();
wc.DownloadFile("http://www.theleafchronicle.com/section/", "theleafchronicle.xml");
}
}
You can use wc.DownloadString(url) or wc.DownloadData(url) depending how you prefer the response.
Related
I have a simple web api controller which I can navigate to through the url and it will download the .csv file. Now I am trying to write some jQuery where if you click the button it will download it but I am missing something.
public HttpStatusCode Get(string id)
{
var reportString = AskWebBusiness.Reports.GenerationQuestionReport(id);
var response = HttpContext.Current.Response;
response.ContentType = "text/csv";
response.AppendHeader("Content-Disposition", "attachment;filename=" + "Questions Report.csv");
response.Write(reportString);
return HttpStatusCode.OK;
}
This code definitely works and I can go to the URL to prompt the download.
$('.js-btn-download-content').click(function (event) {
var currentLanguage = getCulture();
var url = baseUrl + 'report/get/' + currentLanguage;
event.preventDefault();
$('.loadingContent-download').fadeIn(200);
$.ajax({
headers: {
Accept : "text/csv; charset=utf-8",
"Content-Type": "text/csv; charset=utf-8"
},
url: url,
dataType: "text/csv",
success: function (data) {
$('.loadingContent-download').fadeOut(200);
// Not sure about code below
//var xmlDoc = $.parseXML(data);
//var $xml = $(xmlDoc);
//var $title = $xml.find("200");
//if ($title) {
//$('.contentDownloaded-download p').html('Content donwloaded!');
//$('.contentDownloaded-download').show();
//} else {
//$('.contentDownloaded-download p').html('Download failed! Please try again.');
//$('.contentDownloaded-download').show();
//
}
});
$('.js-btn-confirm').click(function () {
$('.contentDownloaded-download').fadeOut(200);
});
});
As you can see, here is some javaScript that I've been using in the app to handle an OK being returned. However the browser won't download the file when this script fires. Any ideas?
In your Get(string id) method, return the HttpResponseMessage instead of just the HttpStatusCode. Also, ASP.net Web API does not ensure the state of HttpContext.Current.Response (without some wizardry code). You can do something like, change the signature to Get(HttpRequestMessage request, string id) and then call request.CreateResponse(statusCode, data).
I would like use PhantomJS with highcharts for generate a report. But for my chart, my data are in SQL database. Normally, for generating my chart I use ajax request with a file query.cfc (coldfusion) and my chart works. But with PhantomJS, if I add a function with my ajax request, I have an error in callback - error 404 but I don't no why. It's the same function what I use for my simple chart.
I launch PhantomJS with: phantomjs --web-security=no test.js
var system = require('system');
var page = require('webpage').create();
var fs = require('fs');
// load JS libraries
page.injectJs("jquery-2.1.1.js");
page.injectJs("highcharts.js");
page.injectJs("exporting.js");
// chart demo
var args = {
width: 600,
height: 500
};
page.onConsoleMessage = function(msg) {
console.log(msg);
};
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
var svg = page.evaluate(function(opt) {
$('body').prepend('<div id="container"></div>');
function test() {
$.ajax({
type: "POST",
async: false,
url: "query3.cfc?method=test",
data: {
'arg1': 'aee',
'arg2': 'ss'
},
success: function(year) {
var lim_annee = jQuery.parseJSON(year);
console.log('success');
},
error: function(jqXHR, exception) {
console.log('erreur ' + jqXHR.status);
console.log('erreur2 ' + exception);
}
});
};
//chart Code
return chart.getSVG();
}, args);
page.render('img.jpeg', {
format: 'jpeg',
quality: '100'
});
phantom.exit()
});
If you don't open a page in PhantomJS, it will stay at "about:blank" and "about:blank/query3.cfc?method=test" doesn't seem like a correct URL. Either use a correct URL to your ColdFusion server:
url: "http://localhost:port/query3.cfc?method=test",
or initialize the base domain in PhantomJS before doing anything else:
page.setContent("", "http://localhost:port/");
Remember that if you were to open simple local HTML files, you would need to use the "file://" protocol and remove any query string.
Also, loading multiple jQuery versions might break your script.
I have created a webmethod and the method just send a Excel file as webresponse.When i run only the webmethod it works fine as want
My webmethod is following:
public void Export_ex(string elem)
{
string elements = elem;
HttpContext.Current.Response.ContentType = "data:application/vnd.ms-excel";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=Print.xls");
HttpContext.Current.Response.Write("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
HttpContext.Current.Response.Write("<head>");
HttpContext.Current.Response.Write("<div>");
HttpContext.Current.Response.Write("<META http-equiv=\"Content-Type\" content=\"text/html; charset=utf- 8\">");
HttpContext.Current.Response.Write("<!--[if gte mso 9]><xml>");
HttpContext.Current.Response.Write("<x:ExcelWorkbook>");
HttpContext.Current.Response.Write("<x:ExcelWorksheets>");
HttpContext.Current.Response.Write("<x:ExcelWorksheet>");
HttpContext.Current.Response.Write("<x:Name>Report Data</x:Name>");
HttpContext.Current.Response.Write("<x:WorksheetOptions>");
HttpContext.Current.Response.Write("<x:ValidPrinterInfo/>");
HttpContext.Current.Response.Write("</x:Print>");
HttpContext.Current.Response.Write("</x:WorksheetOptions>");
HttpContext.Current.Response.Write("</x:ExcelWorksheet>");
HttpContext.Current.Response.Write("</x:ExcelWorksheets>");
HttpContext.Current.Response.Write("</x:ExcelWorkbook>");
HttpContext.Current.Response.Write("</xml>");
HttpContext.Current.Response.Write("<![endif]--> ");
HttpContext.Current.Response.Write("</head>");
HttpContext.Current.Response.Write(elements);
HttpContext.Current.Response.Flush();
// HttpContext.Current.Response.End();
}
but when i call it from javascript function by ajax calling nothing happened. My ajax method is following :
var str = "something"
var data = { elem: str };
$.ajax({
type: 'POST',
url: "ImageSaving.asmx/Export_ex",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
mimeType: 'application/vnd.ms-excel',
success: function (response) {
var show = response.d;
},
failure: function (msg) {
alert("Error occur, could not load the service.");
}
});
I could not understand where i am getting wrong?? Any suggestion regarding this?
For security reasons, you cannot download file from client side. I advice to use a hidden button server side and simulate the click from another button client side.
Regards.
I'm working on project that simulates Twitter and I'm using HTML + JS on client and WCF services on server side (ajax calls), and Neo4J as database.
For example:
in $(document).ready(function ()
there is DisplayTweets service call -> DisplayTweets(username)
function DisplayTweets(userName) {
$.ajax(
{
type: "GET", //GET or POST or PUT or DELETE verb
url: "Service.svc/DisplayTweets", // Location of the service
data: { userName: userName },
contentType: "application/json; charset=utf-8", // content type sent to server
dataType: "json",
processdata: true, //True or False
success: function (msg) //On Successfull service call
{
DisplayTweetsSucceeded(msg);
},
error: function () // When Service call fails
{
alert("DISPLAY TWEETS ERROR");
}
}
);
}
and then DisplayTweetsSucceeded(msg) where msg would be json array of users tweets
function DisplayTweetsSucceeded(result)
{
for (var i = 0; i < result.length; i++)
{
var tweet = JSON.parse(result[i]);
var id_tweet = tweet.id;
var content_tweet = tweet.content;
var r_count_tweet = tweet.r_count;
NewTweet(null, id_tweet, content_tweet, r_count_tweet);
}
}
Function NewTweet is used for dynamic generating of tweets.
Problem is when I first load html page, nothing shows up, neither when I load it multiple times again. It only shows when I go through Firebug, line by line.
I'm presuming that maybe getting data from database is slower, but I'm not sure and also have no idea how to solve this. Any help will be very much appreciated, thank you in advance!
The reading works.
However I got a syntax error in the firefox console (which is tiresome when I read 30 files).
The files are annotation files like (time \t value) with no headers like :
0.0 5.2
0.5 5.6
1.0 6.3
...
This is the ajax code :
function getdatafromfile(filename) {
// Read annotation file. Example : %timeinstant \t %value \n
// Return an array of string
var arraydata
$.ajax({
type: "GET",
url: filename,
dataType: "text",
async: false,
success: function(csv) {arraydata = $.csv.toArrays(csv,{separator:'\t'}); }
});
return arraydata}
And with d3:
d3.text(filename, function(text) {
var data = d3.tsv.parseRows(text).map(function(row) {
return row.map(function(value) {
return +value;
});
});
console.log(data);
});
}
It seems that I could use one of those code, but I got a syntax error in both cases (with firefox 33.1).
A file reader could work like the code below.
In the example I've added a flag to use the content of the variable instead of a file. That's just for the demo and can be removed. The same code is here as jsFiddle.
Maybe you could add some validation before or after the $.csv method. So you know that the file was a csv/tsv file.
If you need to open the file with-out user interaction, you have to look for something different because JS is not allowed to open a file with-out the user choosing the file (security concerns, see this SO question).
You could add your data to a database and read it from there. e.g. Firebase or MongoDB or use a JSON file. The code of my other answer should work for a JSON file that you host with your webpage.
var demoTxt = "0.0 5.2\
0.5 5.6\
1.0 6.3";
var flag_usedemofile = true; //if true var demoTxt will be used
function doOpen(evt) {
var files = evt.target.files,
reader = new FileReader();
reader.onload = function() {
if ( !flag_usedemofile) {
var arraydata = $.csv.toArrays(this.result,{separator:' '});
showout.value = arraydata; //this.result;
} else {
var arraydata = $.csv.toArrays(demoTxt,{separator:' '});
showout.value = arraydata;
console.log(arraydata);
}
};
reader.readAsText(files[0]);
}
var openbtn = document.getElementById("openselect"),
showout = document.getElementById("showresult");
openselect.addEventListener("change", doOpen, false);
#showresult {
width:98%;
height: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
<input type="file" id="openselect" />
<textarea id="showresult"></textarea>
I'm not exactly sure what syntax error you are getting. But I think the error have something to do with the mime type of your json request.
I think the best way is to wrap your data in json and then use JSONP. (I have also tried to get it working with text/plain, but with-out success.)
Please check the following example for details. You can also find the same example on
jsFiddle.
(function ($) {
var url = 'http://www.mocky.io/v2/547c5e31501c337b019a63b0'; // dummy url
var jsonCallback = function (csv) {
var arraydata;
console.log(data);
$('#data').html(JSON.stringify(csv, null, 2));
arraydata = $.csv.toArrays(csv.data,{separator:'\t'});
console.log(arraydata);
};
$.ajax({
type: 'GET',
url: url,
contentType: "application/json",
dataType: 'jsonp'
}).done(jsonCallback)
.fail(function (xhr) {
alert("error" + xhr.responseText);
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id='data'></pre>