PhantomJs- Call WebService & Get data from that - web-services

I use by PhantomJs for connect to my WebService and Post data to WebService's Function for special computing. But i can't get result from WebService's Function.
bin.js:
var page = require('webpage').create();
var data = {
'str': 'sample string'
};
page.open('http://127.0.0.1/Service.asmx/HelloWorld', 'POST', data, function(status) {
// Get status
console.log('Status: ' + status);
// I want to get result
phantom.exit();
});
webService.asmx:
[WebMethod]
public string HelloWorld(string str)
{
return str;
}
I want something look like this in PhantomJs:
$.ajax({
type: "POST",
url: 'http://127.0.0.1/Service.asmx/HelloWorld',
data: {data: 'somethings'},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
var result= data.d;
}
});

var webPage = require('webpage');
var page = webPage.create();
var postBody = 'param1=value1&param2=value2';
page.open('http:www.myservice.com/service', 'POST', postBody, function(status) {
console.log('Status: ' + status);
console.log('HTML Content: ' + page.content); // in case of an HTML response
console.log('JSON: ' + JSON.parse(page.plainText)); // in case of a JSON response
});

I solved my problem with search about "phantomjs in c#".
My solution is use of NReco.PhantomJS library in c#.

Related

JQuery-File-Upload using Signed_URL Google Storage, how to call super class function data.submit() within ajax callback?

I have a fileupload HTML element in my DOM and it currently gets multiple files and calls "add" function for each file. For each file, a signed url is received from an ajax call to the related api. After the succesful ajax call to api, I want to call the data.submit() method of the parent function which is the function in fileupload method as first argument.
How may I be able to access that just after "xhr.setRequestHeader('Content-Type', file.type);" ?
The primary inspiration is from this link :http://kevindhawkins.com/blog/django-javascript-uploading-to-google-cloud-storage/
$("#fileupload").fileupload({
dataType: 'json',
sequentialUploads: true,
add: function(e, data) {
$.each(data.files, function(index, file) {
// pack our data to get signature url
var formData = new FormData();
formData.append('filename', file.name);
formData.append('type', file.type);
formData.append('size', file.size);
// Step 3: get our signature URL
$.ajax({
url: '/api/getsignedurl/',
type: 'POST',
processData: false,
contentType: false,
dataType: 'json',
headers: {
'X-CSRFToken': Cookies.get('csrftoken'),
},
context: 'hello',
data: formData,
}).done(function (data) {
// Step 5: got our url, push to GCS
const xhr = new XMLHttpRequest();
if ('withCredentials' in xhr) {
xhr.open("PUT", data.signed_url, true);
}
else if (typeof XDomainRequest !== 'undefined') {
xhr = new XDomainRequest();
xhr.open("PUT", data.signed_url);
}
else {
xhr = null;
}
xhr.onload = () => {
const status = xhr.status;
if (status === 200) {
//alert("File is uploaded");
} else {
}
};
xhr.onerror = () => {
};
xhr.setRequestHeader('Content-Type', file.type);
//data.submit();
});
});
},
If the $this = $(this) is defined prior to the $.each loop :
submit: function(e, data) {
var $this = $(this);
$.each(data.files, function(index, file) { ...
Then the following can be used to access the data in the parent function
this.primary_data.headers={'Content-Type': file.type};
this.primary_data.jqXHR = $this.fileupload('send', this.primary_data);

How can I get list items by view name, using REST API ajax?

I tried to get a list of items from the Sharepoint library by view name. I had ajax rest API URL:
url: webapp + "_api/web/list/getbytitle" + "('" + LibraryName + "')/View/getbytitle" +"('" + viewName + "')"
method:"GET"
header:"Accept":"application/json;odata=verbose
How can I get all the items in view name?
please refer the following code snippet to get items from specific view, Rest API not provider items endpoint return from a view directly.
So please do the following:
perform the first request to get CAML Query for List View using SP.View.viewQuery property
perform the second request to retrieve List Items by specifying CAML Query:
getListItemsForView(_spPageContextInfo.webAbsoluteUrl,'MyList12','View1')
.done(function(data)
{
var items = data.d.results;
for(var i = 0; i < items.length;i++) {
console.log(items[i].Title);
}
})
.fail(
function(error){
console.log(JSON.stringify(error));
});
function getListItemsForView(webUrl,listTitle,viewTitle)
{
var viewQueryUrl = webUrl + "/_api/web/lists/getByTitle('" + listTitle + "')/Views/getbytitle('" + viewTitle + "')/ViewQuery";
return getJson(viewQueryUrl).then(
function(data){
var viewQuery = data.d.ViewQuery;
return getListItems(webUrl,listTitle,viewQuery);
});
}
function getJson(url)
{
return $.ajax({
url: url,
type: "GET",
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json;odata=verbose"
}
});
}
function getListItems(webUrl,listTitle, queryText)
{
var viewXml = '<View><Query>' + queryText + '</Query></View>';
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getitems";
var queryPayload = {
'query' : {
'__metadata': { 'type': 'SP.CamlQuery' },
'ViewXml' : viewXml
}
};
return $.ajax({
url: url,
method: "POST",
data: JSON.stringify(queryPayload),
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"Accept": "application/json; odata=verbose",
"content-type": "application/json; odata=verbose"
}
});
}
Same question has been answered here:
Using REST to fetch SharePoint View Items

jsZip - execute generateAsync after Ajax post success

I have number if files to be added in the zip file. some are optional (user choice). I like to execute the generateAsync once all required files Ajax post is successful.
I tried to place a check but its not working.
SAMPLE CODES:
var requestCSS;
var StyleFileData;
var requestAnimatedJS;
var AnimatedScriptData;
function getAllFiles(complileComplete){
requestCSS = $.ajax({
url: 'css/styles.css',
type: "GET",
contentType: "text/css",
mimeType:'text/plain; charset=x-user-defined',
success: function (data){
StyleFileData = data;
}
});
if(animatedBG){
requestAnimatedJS = $.ajax({
url: 'js/animated.js',
type: "GET",
contentType: "text/javascript",
mimeType:'text/plain; charset=x-user-defined',
//async: false,
success: function (data){
AnimatedScriptData = data;
}
});
} else {
requestAnimatedJS = '';
}
}
$('#saveProject').on('click', function(){
getAllFiles(complileComplete);
if(complileComplete === true) {
var zip = new JSZip();
var jsFiles;
var cssFiles;
zip.file("index.html", fullHTML);
jsFiles = zip.folder("js");
cssFiles = zip.folder("css");
requestCSS.done( function( data ) {
cssFiles.file("styles.css", data, { binary: true });
});
if(animatedBG){
requestAnimatedJS.done( function( data ) {
jsFiles.file("particles.js", data, { binary: true });
});
}
zip.generateAsync({type:"blob"})
.then(function(content) {
saveAs(content, "Sample.zip");
});
}
});
No server side or node.js is involved.

Getting oauth2 token with Angularjs returns me No 'grant_type' included in the request

i try to get a token from my django-rest-framework api and an angularjs client.
This is how i use the get token access:
var payload = {
username: 'seb',
password: 'aa',
grant_type: 'password',
client_id: consumerKey,
client_secret: consumerSecret
};
var r = $http.post('http://localhost:8000/oauth2/access_token',
payload);
r.success(function(response){
console.log(response.token);
});
I've updated my headers like this:
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
unfortunately it returns me {"error_description": "No 'grant_type' included in the request.", "error": "invalid_request"}
playing with curl returns me the desired token :(
One would expect the payload to be able to exist as a Json object... but alas it requires formData type content. The clue was in your line
'application/x-www-form-urlencoded';
Hence OAuth provider is expecting the data as form based. So your payload would need to be this:
payload = "grant_type=password" + "&username=seb" + "&password=aa" +
"&client_id=" + consumerKey +
"&client_secret=" + consumerSecret;
This is a simple HttpService implementation I put together.
angular.module("services").factory("HttpService", ["$q", "$http", function ($q, $http) {
var httpSvc = {};
httpSvc.Url = "";
httpSvc.ContentType = "application/x-www-form-urlencoded";
httpSvc.JsonPayload = {};
//execute login
httpSvc.HttpPost = function () {
var deferred = $q.defer();
appLogger.conlog(httpSvc.JsonPayload);
//Http Post method
$http({
method: "POST",
url: httpSvc.Url,
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
headers: {
"Content-Type": httpSvc.ContentType
},
data: httpSvc.JsonPayload //post data
}).success(function (data, status, headers, config) {
deferred.resolve({ data: data, status: status, headers: headers, config: config }); //result
}).error(function (data, status, headers, config) {
deferred.reject({ data: data, status: status, headers: headers, config: config }); //result
});
appLogger.conlog(deferred.promise);
//return the callback promise
return deferred.promise;
};
return httpSvc;
}]);
Just inject it into a module and use it like so
var oauth2Payload = {
grant_type: "password",
username: userName,
password: password,
client_id: appConfig.clientId
};
httpSvc.JsonPayload = oauth2Payload;
httpSvc.Url = sysConfig.tokenUrl;
httpSvc.HttpPost().then(function (response) {
var data = response.data;
appLogger.conlog("access_token:\r\n" + data.access_token);
appLogger.conlog("refresh_token:\r\n" + data.refresh_token);
$cookies.refresh_token = data.refresh_token;
appLogger.conlog(data);
deferred.resolve("ok");
}, function (errResponse) {
var data = errResponse.data;
appLogger.conlog(data);
deferred.resolve("error");
});

Invalid JSON primitive: id

I cannot get the following function to work properly. It seems to be serializing it wrong. This is about the 5th iteration of different data variants. I was originally just doing data: {'id': id} like I do at work with WCF, but with the ASMX it just isn't working. It looks like it's serializing teh data as id=1234 instead of id:1234, but I'm fairly new to this. Any help would be appreciated. Oh, and I can call the service directly in the browser and it returns the data properly so I know it's not the service.
function getVentID(id) {
//look up id in database and get VentID
alert('id: ' + id);
var jsdata = { "id": + id}
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'services/UserService.asmx/getVentID',
data: jsdata,
dataType: 'json',
success: function (msg) {
alert(msg.d);
},
error: function (a, b, c) {
alert('Error: ' + a.toString() + ' ' + b.toString() + " " + c.toString());
}
});
}
p.s. I know there are like 10 identical questions but none of them have answers that I could find or that worked for me.
The simplest possible fix would be to change the line beginning var jsdata to:
var jsdata = '{id:' + id + '}';
The problem is that jQuery is encoding jsdata as form data, not as json. The dataType parameter influences how the response is parsed, not how the POST data is encoded.
There's not actually any JSON serialization code in jQuery to the best of my knowledge. Apparently John Resig suggests using Douglas Crockford's json2.js.
To use it, add a script reference to json.js and then:
var jstext = JSON.stringify(jsdata, null, 2);
i solved this problem right now.
You need pass the url in this format:
http://domain.com.br/service.asmx/method?objParam={q : "search"}
And in your service.asmx file, you need declare this method:
Public Function method(objParam As Dictionary(Of String, String))
End Function
In your code, looks like:
function getVentID(id) {
var jsdata = {
"id": +id
}
var sData = JSON.stringify(jsdata); //convert your json in string
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'services/UserService.asmx/getVentID',
data: {
id: sData
},
dataType: 'json',
success: function(msg) {
alert(msg.d);
},
error: function(a, b, c) {
alert('Error: ' + a.toString() + ' ' + b.toString() + " " + c.toString());
}
});
}