Ian Wood
Ian Wood

Reputation: 6573

ajax response from node

I'm calling a node'js process to scrape twitter and create a graph from the data...

here's the code.

var http  = require('http');
var url   = require('url');
var exec  = require('child_process').exec;
var fs    = require('fs');

var filepath = 'filenamegraph.png';

http.createServer(function(req,res){
    var urlstr = url.parse(req.url,true);
    var twit = exec("php -f twitter-scraper.php "+urlstr.query.term ,function(error, stdout, stderr){
        var graphstring = stdout;
        var stream = fs.createWriteStream("graph.txt");
        stream.once('open', function(fd){  
            stream.write(graphstring, function(){
                exec('dot -T png -o filenamegraph.png graph.txt', function(){
                    fs.stat(filepath,function(err,stat){
                        res.writeHead(200,{'Content-Type':'image/png', 'Content-Length': stat.size });
                        fs.readFile(filepath,function(err,file_conts){
                            res.write(file_conts);
                            res.end();
                        });
                    });
                });
            });
        });
    });
}).listen(1337);

all thats is hunky dory...

now I call this with:

$.ajax({
    url: 'http://eavesdropper.dev:1337',
    data: { term : $.url.parse().params.term },
    success: function(data) {
        var res = $.parseJSON(data);
        console.log(res);
        $("body").append('<img src="filenamegraph.png" />');
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.log(jqXHR,'errror - ' + textStatus + " - " + errorThrown + ' ||');
    },
    complete: function(jqXHR, textStatus){
        console.log(jqXHR, textStatus)
    }
});

the work behind the scenes is fine BUT i get this...

Object { readyState=0, status=0, statusText="error"} error - error - ||

Not sure what next step is so any tips muchly appreciated.

PS: running directly in the browser the script correctly procues the graph so this is sure around the data being returned to the ajax call that is getting upset.

Upvotes: 0

Views: 489

Answers (1)

ebohlman
ebohlman

Reputation: 15003

Your server is delivering the contents of the newly-created graphic file, but all your client is doing is trying to parse the contents as if it were JSON (which it obviously isn't, causing your error messages) and then inserting an <img> element that will cause the browser to request "filenamegraph.png" from whatever server delivered the original HTML.

It looks to me like you don't need to do an AJAX request at all; just append <img src='http://eavesdropper.dev:1337/?your_params' /> and the browser will automatically get and display the generated image from your server.

Upvotes: 1

Related Questions