Kan
Kan

Reputation: 45

CasperJS POST AJAX is not working

I'm working on sending data through ajax. The code is working, but the AJAX request is not working. The data sent is not saved.

I have tried using webSecurityEnabled: false, but it still doesn't work.

This is how I'm trying to do it:

var casper = require("casper").create({
    logLevel:   "error", //debug
    verbose:    true,

    pageSettings: {
        loadImages:  true,          // do not load images
        loadPlugins: false,         // do not load NPAPI plugins (Flash, Silverlight, ...)
        webSecurityEnabled: false // ajax 
    }
});

........................

var save_file="http://aaa.com/js_save.php";

for(var ii=0; ii<title_link.length; ii++)
{
    this.echo(title_link[ii]);

    //var save_data = tlink.serialize();
    var save_data = {"title":"title", "link":title_link[ii]};

    jsonObject_fields = this.evaluate(function(save_file) {
        params = save_data;

        try {
            return JSON.parse(__utils__.sendAJAX(save_file, 'POST', params, false));
        } catch (e) {
            console.log("Error in fetching json object");
        }
    }, {save_file : save_file});

    try{
        //require("utils").dump(JSON.stringify(jsonObject_fields.name));
    }
    catch(e)
    {
        console.log("Error is: "+e);
    }

} // for

Upvotes: 0

Views: 1077

Answers (2)

Siddhartha Dimania
Siddhartha Dimania

Reputation: 31

casper.then(function () {
    var wsurl = "http://siddimaniaajax.esy.es/ajaxCall.php";
    var params = {name:"siddhartha"};

    var jsonObject_fields = casper.evaluate(function(wsurl, params) {
        try {
            return JSON.parse(__utils__.sendAJAX(wsurl, 'POST', params, false));
        } catch (e) {
            console.log("Error in fetching json object");
        }
    }, wsurl, params);

    console.log(JSON.stringify(jsonObject_fields));
});

<?php

if(isset($_POST['name']) && !empty($_POST['name']))
{

 $arr = array('name' => $_POST['name']);
  echo json_encode($arr);
}

?>

Upvotes: 0

Artjom B.
Artjom B.

Reputation: 61892

I don't fully understand your question, but code-wise you need to explicitly pass variables into the page context. casper.evaluate is sandboxed and the only way to pass data between the casper context and the page context is using the arguments and the return value. Variables defined outside cannot be used inside of casper.evaluate.

You need to pass save_data explicitly to the page context:

var save_data = {"title":"title", "link":title_link[ii]};

jsonObject_fields = this.evaluate(function(save_file, save_data) {
    try {
        return JSON.parse(__utils__.sendAJAX(save_file, 'POST', save_data, false));
    } catch (e) {
        console.log("Error in fetching json object");
    }
}, save_file, save_data);

Upvotes: 1

Related Questions