Sending Ajax Request with PhantomJS to a local ColdFusion server - javascript

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.

Related

Electron browser window not updating when using jquery

I have been looking at converting a web app to an Electron desktop app. I am starting an http server in main.js to handle ajax requests from my app. I've created a button and defined its onclick function to call an ajax function and then update another element when the response arrives, e.g. $('#message').text('whatever'). This all works but the element ('#message') is not completely refreshed - I see the new text on top of the old text. If I click somewhere in the window the element is refreshed properly. I've tried calling blur() on the element and setting the focus to another element, but none of that helps.
Why does the BrowserWindow not erase the element's old text when I update it via jQuery, and how can I fix it?
Thanks in advance for your help!
Additional details
Here is the code that is called when the "Test" button is clicked.
function test_webapi() {
var url = 'http://localhost:8888/time';
console.log("Sending request: " + url);
$.ajax({
cache: false,
method: 'GET',
url: url,
error: function(xhr, status, err) { console.log("Ajax error from " + url + ": " + err); },
success: function(data) {
console.log("Have response from " + url, data);
$('#message').text(data.Data.Time);
}
})
}
And the code that sets up the http server and handles the ajax request.
var port = 8888;
var server = http.createServer(handle_time_request);
server.listen(port, function() {
console.log("API server listening on port " + port);
});
function handle_time_request(req, res) {
var tval = moment(new Date()).format('YYYY-MM-DD hh:mm:ss');
var reply = {
Success: true,
Message: "whatever",
Data: { Time: tval }
};
res.writeHead(200, {"Content-Type": "application/json"});
res.end(JSON.stringify(reply, null, 4));
}

Dynamic html elements show only when going through debugger

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!

Read local file text (tab separated values) with d3 or ajax cause syntax error in firefox development console

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>

In .net, how can I download this remote file

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.

asp.net mvc how to save data from jquery control

I am using the TinyMCE control in a MVC page, and now I want to save the content of the control (hopefully with ajax so the page is not rendered again)... I have some javascript that looks like this:
mysave = function() {
var ed = tinyMCE.get('content');
// Do you ajax call here, window.setTimeout fakes ajax call
ed.setProgressState(1); // Show progress
window.setTimeout(function() {
ed.setProgressState(0); // Hide progress
alert(ed.getContent());
}, 3000);
};
What is the best way to pass the content back to the controller, save it, and return back to the same page?
well, use jQuery.ajax. http://docs.jquery.com/Ajax. I suggest you to use POST request so you can transfer arbitrary long texts.
How do you plan to save the text? Do you use any database engine? we need more information.
$.ajax({
url: "/controller/savetext",
cache: false,
type: "POST",
data: { text: ed.getContent() },
success: function(msg) {
alert("text saved!");
},
error: function(request, status, error) {
alert("an error occurred: " + error);
}
})
and on server side something like this:
string text = Request.Form["text"]

Categories