Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting remote data for a page using AJAX in CasperJS

In the course of executing a CasperJS script I need to fetch and parse JSON data from another site so that I can use that data to fill in a form on the site I'm actively working on.

How can I do this?

like image 673
eComEvo Avatar asked Nov 09 '12 01:11

eComEvo


1 Answers

You can use __utils__.sendAJAX():

var casper = require('casper').create();
var wsurl = 'https://raw.github.com/n1k0/casperjs/master/package.json';
var word;

casper.start('http://google.com/', function() {
    word = this.evaluate(function(wsurl) {
        try {
            return JSON.parse(__utils__.sendAJAX(wsurl, 'GET', null, false)).name;
        } catch (e) {
        }
    }, {wsurl: wsurl});
});

casper.then(function() {
    if (!word) {
        this.die('unable to retrieve word');
    }
    this.echo('searching for ' + word);
    this.fill('form[action="/search"]', {q: word}, true);
});

casper.run(function() {
    this.echo(this.getCurrentUrl());
    this.exit();
});

Sample execution (don't forget to pass --web-security=no):

$ casperjs test.js --web-security=no
searching for casperjs
http://www.google.fr/search?hl=fr&source=hp&q=casperjs&gbv=2&oq=&gs_l=

Hope it helps.

like image 143
NiKo Avatar answered Nov 15 '22 10:11

NiKo