How to get the response after a POST request in CasperJS - phantomjs

I have this very simple code to read the response from a server endpoint after a post request. Actually I'm saving a data to a database and wait for a response before going to next step
casper.open('http://example.com/ajax.php, {
method: 'POST',
data: {
'title': '<title>',
'unique_id': '<unique_id>'
}
});
on ajax.php file I'm trying to echo the POST request in a simple way.
this will let me know easily if I'm getting the right response from the server.
echo json_encode($_POST);
I tried these snippets but I'm unable to get the response.
casper.on('page.resource.received', function(resp){
this.echo(JSON.stringify(resp, null, 4));
});
casper.on('http.status.200', function(resp){
this.echo(JSON.stringify(resp, null, 4));
});
casper.on('resource.received', function(resp) {
this.echo(JSON.stringify(resp, null, 4));
});

I've been facing the same problem POSTing a query to ElasticSearch and I could not retrieve the results.
As far as I can understand if you want to retrieve the data echoed by your script the solution could be this:
this.echo(this.page.content);
or
this.echo(this.page.plainText);
in your function.
For example (my case with ElasticSearch):
/*
* SOME VAR DEFINITIONS HERE
*/
casper.start();
casper.then( function() {
// the next var is very specific to ElasticSearch
var elasticQuery = JSON.stringify (
{
'size' : 20,
'query' : {
'filtered' : {
'filter' : { 'term' : { 'locked' : false } }
}
},
'sort': { 'lastScrapeTime': { 'order': 'asc' } }
}
);
var elasticRequest = {
method: 'POST',
data: elasticQuery
}
this.thenOpen( <<YOUR URL>>, elasticRequest, function (response) {
// dump response header
require('utils').dump(response);
// echo response body
this.echo(this.page.content);
// echo response body with no tags added (useful for JSON)
this.echo(this.page.plainText);
});
}
);
casper.run();

As Roberto points out. You can use this.page.content to show the response. But you need to add the function(response) in your script. For example:
casper.open('http://example.com/ajax.php', {
method: 'POST',
data: {
'title': '<title>',
'unique_id': '<unique_id>'
}
}, function(response){
if(response.status == 200){
require('utils').dump(this.page.content);
}
});

If you want to unit test a REST API, CasperJS is not necessarily the right tool.
CasperJS allows to observe a web browser which is running a web page.
So a more typical approach would be to use CasperJS to load a page that would call your REST API and you would assert the page behavior is correct (assuming the page would make something observable according the AJAX call response).

Related

Calling POST as URL ASP.NET web api

I want to know how to test POST by typing in the url.
Here's my route Config
config.Routes.MapHttpRoute(
name: "myWebApi",
routeTemplate: "api/mywebapi/{action}/{ID}/{DeptID}",
defaults: new { Controller = "mywebapi", ID = #"\d+", DeptID = #"\d+" }
);
programmatically this is how I call POST
I have 3 text boxes and a button. When user clicks on the button the below program gets called
function parseform(button) {
var id = $("#ID").val();
var deptid = $("#DeptID").val();
var name = $("#Name").val();
var inputdata = {
id: id,
deptid: deptid,
name: name
}
if (button.attr('value') === "POST") {
postdata(inputdata);
} else {
console.log("ERROR");
}
}
function postdata(inputdata) {
$("#response").text("Posted");
$.ajax({
type: "POST",
dataType: "json",
url: "api/mywebapi/Post/",
contentType: "application/json",
data: JSON.stringify(inputdata),
xhrFields: {
withCredentials: true
},
success: function (data, status, xhr) {
$("#response").text(status+" - "+data)
},
error: function (xhr, status, error) {
var json = jQuery.parseJSON(xhr.responseText);
$("#response").text(status)
}
});
}
In the controller
[System.Web.Http.AcceptVerbs("POST")]
public void Post([FromBody]mywebapi value)
{
saves to database
}
Here's what I tested
http://localhost:222/api/mywebapi/Post/new newwebapi ({"id":"1","deptid":"2","name":"testing"})
I get error. How to test this?
thanks
R
Since it's a POST request, you can't test it in your browser by typing in an address (those are GET requests, which contain no body).
To test these types of things you can use something like Postman
or Rest Console (if you're using chrome), there's tons of these types of things in whatever your browsers extension store is called.
Some tools you can use are something like Fiddler
this will let you see what the requests and responses look like, and you can change/modify them as well, though it's probably a bit harder to use than something like PostMan or Rest Console (also more powerful)

how to submit json file in sencha touch in http post multipart?

I want to submit json file form sencha touch to my tomcat server using http post multipart but i don't know how to do ?
can any one give me some idea or example.
Thanks
you can do this using jQuery.
var request = new FormData();
$.each(context.prototype.fileData, function(i, obj) { request.append(i, obj.value.files[0]); });
request.append('action', 'upload');
request.append('id', response.obj.id);
$.ajax({
type : 'POST',
url : context.controller,
data : request,
processData : false,
contentType : false,
success : function(r) {
console.log(r);
//if (errors != null) { } else context.close();
},
error : function(r) { alert('jQuery Error'); }
});

Getting no records when making Ajax request

I am trying to make a request to a server but im getting no records. When i run the code I am getting no error messages so I assume my code is working but when the callback function is executed on store load I just get a blank message.
var proxy = Ext.data.proxy.Ajax.create({
type:'ajax',
url:loginHostUri,
method:'POST',
headers:{
'Accept':'application/x-www-form-urlencoded'
},
extraParams:{
grant_type:'password',
username:username,
password:psswd,
client_id: consumerKey,
client_secret: consumerSecret
},
reader:{
type:'json',
root:''
}
});
var store = Ext.getStore('instance');
store.setProxy(proxy);
store.load({
callback:function(records,operation,success){
Ext.Msg.alert('INFO',records,Ext.emptyFn);
},
scope:this
});
The message is just blank but I know the Json response looks like this:
{
"":{
"id":"2332123",
"issued_at":"090342",
" instance_url":"instance",
"signature":"sig",
"access_token":"access"
}
}
define a fields or a model for the store
store.setFields({name: 'id', name: 'issued_id' ...});(put this before store.load())
Try that and console.log(records) under callback and reply back what you get...

Get JavaScript Variable Value in a PHP Variable?

I have this JavaScript function which is getting a value from a select option in HTML:
<script type="text/javascript">
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var str=xmlhttp.responseText;
var splitstr=str.split('||');
document.getElementById("txtHint").innerHTML=splitstr[0];
document.getElementById("txtval").innerHTML=splitstr[1];
}
}
xmlhttp.open("GET","getdetails.php?q="+str,true);
xmlhttp.send();
}
</script>
Now, str is the JavaScript variable I want to take its value and put it into a PHP variable.
I am using this, but it is not working:
$grade = "<script language=javascript>document.write(str);</script>";
echo $grade;
What is the correct way to do this?
PHP runs on a web server, so it will only execute when the page loads. So the above statement will not work as it runs within the function which is called after page load.
To achieve what you want, you can send str to a php file via ajax call and store it in a session variable. & then whenever you need the variable call another ajax function which will retrieve the session value.
You can use jQuery to handle AJAX calls.
Make sure you include this line in your html page.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
Use the javascript to make your call to PHP and sent your str data.
function uploaddata(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
var fd = new FormData();
fd.append('data1', str);
try {
$.ajax({
url: 'dosomething.php',
data:fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
var response = $.parseJSON(data);
if (response.code !== '0'){
alert(response.description);
}
else {
alert(response.description);
};
},
error: function(jqXHR, error, errorThrown) {
alert(jqXHR.responseText);}
});
}
catch (ex) {
}
}
At server side create the dosomething.php will make the process you need.
<?php
// get your data at server side
str = $_POST['data1'];
// do processing
// return answer to browser
$ans = ['code' => '0', 'description' => 'Everything are ok'];
echo json_encode($ans);
return;
?>
At your javascript the success portion will be activated and you can use the code and description to build your logic.

Consuming an OData request in Sencha Touch with JSONP

I'm working on a Sencha Touch app and I want to use OData so I have been playing around with the netflix Odata service. When I send my request with JSONP in Sencha I can see the request come back when I trace it, however my callback function is never getting called. Can anyone help? Here is my code.
var blah = function () {
Ext.util.JSONP.request({
url: 'http://odata.netflix.com/catalog/Titles()',
callbackKey: 'callback',
params: {
$format: 'json',
$top: '10',
$filter: "startswith(Name,'C')",
$select: "ShortName"
},
callback: function (result) {
alert('asdf');
var data = result;
if (data) {
alert('data');
} else {
alert('There was an error during retrieving data.');
}
}
});
}
var button = new Ext.Button({
text: 'Ajax',
listeners: {
'tap': blah
}
});
Thanks in advance
If you're getting a syntax error on the server response quotes, this is a known issue described here for which there is an available update.
The server is returning XML, not JSON data.