beno_88 beno_88 - 6 months ago 43
Ajax Question

Sending Ajax Request with PhantomJS to a local ColdFusion server

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

Answer

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.

Comments