For some reason the script does not run, or return answer.
The console is nothing.
Trying to get an answer to yandex.transtale site (https://tech.yandex.com/translate/doc/dg/reference/translate-docpage/)
Code: http://jsbin.com/jolijep/edit?html,js,console,output
var app = angular.module('jsbin', []);
app.controller('DemoCtrl', function($scope, $http) {
var url = "https://translate.yandex.net/api/v1.5/tr.json/translate";
keyAPI = "trnsl.1.1.20130922T110455Z.4a9208e68c61a760.f819c1db302ba637c2bea1befa4db9f784e9fbb8";
var vm = this;
$scope.SendData = function() {
// тут данные
var textApi = 'Hello';
var langApi = 'en-ru';
var text1 = 'Hello';
var data = "key=" + keyAPI + "&text=" + textApi + "&lang=" + langApi;
$http.post(url, data)
.success(function(data, status, headers, config) {
vm.data = response.data;
$scope.PostDataResponse = data;
console.log(data);
})
.error(function(data, status, header, config) {
$scope.ResponseDetails = "Data: " + data +
"<hr />status: " + status +
"<hr />headers: " + header +
"<hr />config: " + config;
});
};
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Angular JS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="weather.js"></script>
</head>
<body ng-app="jsbin">
<div ng-controller="DemoCtrl as vm">
<script src="weather.js"></script>
<button ng-click="SendData()">Send</button>
<br>Data: {{PostDataResponse}}
<br>{{vm.data}} {{vm.PostDataResponse}} Data: {{scope.PostDataResponse}} {{vm.data}}
</div>
</body>
</html>
If you look at the Yandex translate API reference, it has asked you to pass the information for the request you are making in the form of the params(parameter). These parameters are to be appended to the request URL.
Other ways of getting information from an API with a POST request is to pass information in the form of the body of that request.
But the Yandex translate API with the POST request is asking for the information attached to the url.
var data = "key="+keyAPI+"&text="+textApi+"&lang="+langApi
this data variable should be getting appended to the url variable when the POST request is made to the API. But,
$http.post(url, data)
Invoking $http method makes the data interpreted as the body of the post request instead of appending the data variable to url while making the call.
A much cleaner and proper implementation for $http API of the AngularJS would be to put all you parameters inside an object where the keys are the parameter type and values are the parameter values.
var params = {
key: keyAPI,
text:textApi,
lang:langApi
}
Now in the params object, you are hold all the information you wanted to pass while making the request.
Secondly, you need to the modify the $http request so that it knows what params are to be appended to the url. I am using more basic $http method instead of $http.post method,I will clearly mention what should be the base url, type of method for the HTTP request and lastly, the params that are to passed with the request to the API.
$http({
url: url,
method: 'POST',
params: params
})
.success(function(data,headers,status,config){
$scope.PostDataResponse = data;
vm.data = data;
console.log(data);
})
.error(function(data,headers,status,config){
$scope.ResponseDetails = "Data: " + data +
"<hr />status: " + status +
"<hr />headers: " + header +
"<hr />config: " + config;
});
Another thing which was wrong in your code was the initialization of $scope.PostDataResponse
$scope.PostDataResponse = response.data; //You are not getting any argument named response by the success function call
Correct way to do it will be
$scope.PostDataResponse = data;
Now if you run the code with the modification it should run pretty fine.
If everything is done correctly, then in the developer console you would find an object logged after the success of the request.
Object with the success of the call
In your webpage also, you would see the same object.
Related
Im new to protractor and have a registration page, So i wanted to post the api directly so that the user profile is directly created
My controller
<script>
var app = angular.module("app", []);
app.controller("HttpGetController", function($scope, $http) {
$scope.SendData = function() {
var data = {"firstName":"check","lastName":"raq","roles":["PATIENT"],"contactInfo":{"email":"test1#123.com","primaryPhone":"+918598598547","secondaryPhone":null}}
$http.post('/ServerRequest/PostDataResponse', data)
.success(function(data, status, headers) {
$scope.PostDataResponse = data;
})
.error(function(data, status, header) {
$scope.ResponseDetails = "Data: " + data +
"<hr />status: " + status
});
};
});
</script>
How should i write a api call for the test case directly.......
Any help is appreciated.........Thanks in advance
I currently have the following angular script in a page:
var app = angular.module('doorman', []);
app.controller('formCtrl', function($scope, $http) {
$scope.create = function() {
var msg = '{' +
'"id":"id",' +
'"building":"' + $scope.building + '",' +
'"unit":"' + $scope.unit + '",' +
'"firstName":"' + $scope.firstName + '",' +
'"name":"' + $scope.name + '",' +
'"carrier":"' + $scope.carrier + '",' +
'"tracker":"' + $scope.tracker + '"' +
'"delivered":"0",' +
'"added":"NOW()"' +
'}';
$http.put("104.131.166.246:8080/doorman/rest/pilot", msg).
success(function(data, status, headers, config) {
//empty the fields
$scope.building = "";
$scope.unit = "";
$scope.firstName = "";
$scope.name = "";
$scope.carrier = "";
$scope.tracker = "";
}).
error(function(data, status, headers, config) {
//TODO temporary, remove
alert("ERROR " + status + ": " + data);
});
};
$scope.search = function() {
}
});
I have a backend RESTful java servlet handling requests.
When I call the 'create()' function, the output always ends up on the error function, showing the alert 'ERROR undefined: undefined'. While monitoring http requests on chrome, I see no request being made at all. What could the problem be?
From angular side, your code looks ok. Further when you say the call ends up in the error section, it suggest that something is going wrong on the outbound call or on the server side. Can you use browser tools or if you are in windows use a tool like fiddler to see the network traffic to see what’s going on. One
other thing, see whether you have to enable Cross-origin Resource Sharing (CORS) on server side.
Cheers
Found the error. Apparently, appending "http://" to the beginning of the url is necessary. Thanks anyway!
I am trying to send a form thru POST to my REST Resource (Java) and I am not able to, as my request gets sent as OPTIONS instead. I Know that the REST Resource is fine since it works perfectly while I test it with Poster Firefox.
jQuery/Ajax call:
function loadTwitter(){
arrayTweets = new Array();
var urlTwitter = "http://localhost:8081/streamingvideoservice/services/twitter/retrieveTweets";
$.ajax({
type: "POST",
url: urlTwitter,
contentType: "application/x-www-form-urlencoded",
//accept: "application/json",
data: $("form#mapForm").serialize(),
dataType: "json",
async: false,
success: function (resp, status, xhr) {
$("#message").html("STATUS: " + xhr.status + " " + xhr.statusText + "\n" + resp);
$("#message").hide();
$.each(resp, function() {
$.each(this, function(i, item) {
arrayTweets.push(item);
});
});
displayTweets();
},
error: function(resp, status, xhr){
$("#message").html("ERROR: " + xhr.status + " " + xhr.statusText + "\n" + resp.e);
$("#message").show();
}
});
}
REST Resource:
#POST
#Path("/retrieveTweets")
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
#Produces("application/json")
public List<Tweet> retrieve(#FormParam("lat") Double Latitude, #FormParam("lon") Double Longitude, #FormParam("rad") Integer Radius, #FormParam("from") String From, #FormParam("to") String To) {
ArrayList<Tweet> lTweets = new ArrayList<Tweet>();
boolean status = false;
Twitter twitter = new TwitterFactory().getInstance();
AccessToken accessToken = new AccessToken(TwitterInterface.ACCESS_TOKEN, TwitterInterface.ACCESS_TOKEN_SECRET);
twitter.setOAuthConsumer(TwitterInterface.CONSUMER_KEY, TwitterInterface.CONSUMER_SECRET);
twitter.setOAuthAccessToken(accessToken);
try {
Query query = new Query("");
GeoLocation geo = new GeoLocation(Latitude, Longitude);
query.setGeoCode(geo, Radius, Query.KILOMETERS);
query.setCount(100);
query.setSince(From);
query.setUntil(To);
QueryResult result;
result = twitter.search(query);
List<Status> tweets = result.getTweets();
for (Status tweet : tweets) {
System.out.println("#" + tweet.getUser().getScreenName() + " - " + tweet.getText() + " - " + tweet.getCreatedAt());
Tweet t = new Tweet();
t.setUser(tweet.getUser().getScreenName());
t.setText(tweet.getText());
lTweets.add(t);
}
}
catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to search tweets: " + te.getMessage());
System.exit(-1);
}
return lTweets;
}
I am using jQuery 1.9.1 and hosting the Resource on Tomcat 6.
Any help is appreciated.
Thanks in advance.
You appear to be making a cross origin Ajax request. This requires that the server provides an Access-Control-Allow-Origin header to grant permission to the site hosting the page containing the JS to read the data.
Something about the request (probably the X-Requested-With header that jQuery adds to Ajax requests) is triggering a preflight request which uses an OPTIONS request to ask the server for permission before making the main request.
You will need to configure the server to provide an OPTIONS response with suitable Access Control headers as per the CORS specification (linked above).
Solved it with a GET instead and passing the parameters in the URI.
I am developing a browser extension using crossrider.
I have added a context menu (background.js)
var ContextData;
appAPI.contextMenu.add("key1", "Send Data To Server", function (data) {
var ContextData = 'pageUrl: ' + data.pageUrl + '\r\n' +
'linkUrl: ' + data.linkUrl + '\r\n' +
'selectedText:' + data.selectedText + '\r\n' +
'srcUrl:' + data.srcUrl;
}, ["all"]);
On user click I want to send ContextData to extension.js. At extension.js some function will receive the data and send it to my server (A Rest API which will accept the data).
To send data to the server I have tested this and it works fine (code sample in extension.js)
appAPI.ready(function($) {
var dataToSend =="test data";
appAPI.request.post({
url: 'REST API URL',
postData: dataToSend,
onSuccess: function(response, additionalInfo) {
var details = {};
details.response = response;
},
onFailure: function(httpCode) {
// alert('POST:: Request failed. HTTP Code: ' + httpCode);
}
});
});
How can I write a function to accept ContextData from background.js and assign it to dataToSend in extension.js?
#Neel If I understand your requirements correctly, #Rob is essentially correct though a little clarification may help
By design/architecture, the extension.js code runs on each HTML page i.e. a separate extension.js instance is run for each URL that loads. In contrast, the context menu runs at the browser level (not HTML page) and is hence correctly coded in background.js file. However, the background.js code does not have direct access to the extension.js instance code running on the HTML page in the active tab and must therefore communicate the data via messaging. (For more information about scopes, see Scopes Overview)
Obviously, a user clicks the context menu item on the active tab (i.e. the page showing the HTML page being viewed); hence, once the ContextData string is created, you can use appAPI.message.toActiveTab to send the string to the extension.js instance running on the page/tab where the the context menu item was clicked.
This being the case, using your code example you can achieve this goal as follows:
background.js:
appAPI.ready(function($) {
var ContextData;
appAPI.contextMenu.add("key1", "Send Data To Server", function (data) {
var ContextData = 'pageUrl: ' + data.pageUrl + '\r\n' +
'linkUrl: ' + data.linkUrl + '\r\n' +
'selectedText:' + data.selectedText + '\r\n' +
'srcUrl:' + data.srcUrl;
appAPI.message.toActiveTab({type:'dataToSend', data: ContextData});
}, ["all"]);
});
extension.js:
appAPI.ready(function($) {
var dataToSend =="test data";
appAPI.message.addListener(function(msg) {
if (msg.type === 'dataToSend') {
appAPI.request.post({
url: 'REST API URL',
postData: dataToSend,
onSuccess: function(response, additionalInfo) {
var details = {};
details.response = response;
},
onFailure: function(httpCode) {
// alert('POST:: Request failed. HTTP Code: ' + httpCode);
}
});
}
});
});
[Disclaimer: I am a Crossrider employee]
I am attempting to access Google Books in order to an ISBN Code to get details of a book, I have a number of problem, which are:
A) I am trying to assemble a script request e.g. with the ISBN code concatenated into the URL. I have not managed to do this successfully - and I don't know why.
B) I then want to update a div in the DOM with this generated script dynamically, such that it will then execute.
C) I am finding it a bit of a puzzle as to the format of the returned data and the argument name of the function call contained in the Google response.
Has anyone else encountered the same problem and can offer guidance re A thru C above.
I enclose JavaScript code below.
$(document).ready(function() {
$('#viewbook-button').live('click', function() {
isbnCode = this.text;
alert("ISBN is : " + isbnCode + " " + this.text + " as well");
alert("Getting JSONP Google Books data");
isbnCode = "0451526538";
JSONPstr = '<' + 'script ' + 'src="' + 'https://www.googleapis.com/books/v1/volumes?q=ISBN' + isbnCode;
JSONPstr = JSONPstr + '&callback=handleJSONPResponse">' + '</script>';
alert("un-Escaped JSONP string" + JSONPstr);
escJSONPstr = escape( escJSONPstr );
alert("Escaped JSONP string");
//divstr = "";
//divstr = divstr + escape(<script src=");
//divstr = divstr + encodeURIComponent(https://www.googleapis.com/books/v1/volumes?q=ISBN);
//divstr = divstr + escape(isbnCode);
//divstr = divstr + encodeURIComponent(&callback=handleJSONPResponse);
//divstr = divstr + escape("></);
//divstr = divstr + escape(script);
//divstr = divstr + escape(>);
$('#jsonp-call').html(escJSONPstr);
// This will cause the handleJSONPResponse function to execute when the script is dynamically loadedinto div.
// The data wrapped in a function call will be returned from the Google Books server.
// This will cause the handleJSONPResponse function to execute below.
}); // end viewbook-button
}); // end document.ready
function handleJSONPResponse(response) {
var tmp = response;
alert(tmp);
};
</script>
</head>
<body>
<h2>Show Details of Books Ordered by a Customer</h2>
Get Customer Details
<br/><br/>
<div id="tablist">Tables will be Listed Here</div>
<br/><br/>
<div id="Google-call">The JSONP generated src= statement will go here and execute</div>
</body>
</html>
EDIT:
Problem solved - thanks everyone.
You're reinventing the wheel: jQuery has built-in JSONP support, so you don't need to faff about implementing it yourself. Use the $.ajax method:
$.ajax({
url: 'https://www.googleapis.com/books/v1/volumes?q=ISBN' + isbnCode,
dataType: 'jsonp',
success: function(response) {
console.log(response); // log the response object to the console
}
});
That should be all you need to do.