I have a webservice which returns Jsonobject and I call it in JS using Ajax like here :
$scope.init = function () {
$.ajax({
type: 'GET',
timeout: 1000000000,
url: serverName.replace('services', 'servicesV2') + '/getTreasuryResults',
data: { data: 'None' }, // the data in form-encoded format, ie as it would appear on a querystring
dataType: "text", // the data type we want back, so text. The data will come wrapped in xml
success: function (data) {
var dataAngularTreasury = JSON.parse(data);
alert(dataAngularTreasury);
//FillDefaultTreasuryValues(data.split(";"));
CallTreasuryDetailValuesWS(934);
},
error: function (data) {
alert(errServiceCall); // show the string that was returned, this will be the data inside the xml wrapper
$('#loading').hide();
}
});
};
If I call that init() function in ng-click like
<button id="btnGetDefaultValues" type="button" class="button" ng-click="init()">Fill</button>
It runs with no problem.
but if I call this webservice in page load like
angular.module('termDeposite', []).controller('userCtrl', function ($scope) {
$scope.treasuryValues = [];
angular.element(document).ready(function () {
$.ajax({
type: 'GET',
timeout: 1000000000,
url: serverName.replace('services', 'servicesV2') + '/getTreasuryResults',
data: { data: 'None' }, // the data in form-encoded format, ie as it would appear on a querystring
dataType: "text", // the data type we want back, so text. The data will come wrapped in xml
success: function (data) {
var dataAngularTreasury = JSON.parse(data);
alert(dataAngularTreasury);
//FillDefaultTreasuryValues(data.split(";"));
CallTreasuryDetailValuesWS(934);
},
error: function (data) {
alert(errServiceCall); // show the string that was returned, this will be the data inside the xml wrapper
$('#loading').hide();
}
});
});
});
or
if I call this webservice in ng-init trigger like
<body id="body" ng-app="termDeposite" ng-controller="userCtrl" ng-init="init()" >
webservice goes to error step and throws that error :
"\n\n\nError 404--Not
Found\n\n\n\n\n\nError 404--Not
Found\n\n\nFrom RFC
2068 Hypertext Transfer Protocol --
HTTP/1.1:\n10.4.5 404 Not Found\nThe server has not found anything matching the
Request-URI. No indication is given of whether the condition is
temporary or permanent.If the server does not wish to make this
information available to the client, the status code 403 (Forbidden)
can be used instead. The 410 (Gone) status code SHOULD be used if the
server knows, through some internally configurable mechanism, that an
old resource is permanently unavailable and has no forwarding
address.\n\n\n\n\n\n"
Finally, I can call a webservice with using ng-click but I can't call same webservice using ng-init or pageload. So how can I call a webservice using ajax in page init or page load in angular framework scope ?
Assuming you have serverName as a global and it is readable then the ng-init version or creating a custom directive and sticking the code in the link function should work.
Check the URL that is actually being called in the network tab in the Chrome dev tools (built into chrome) - cmd+alt+j on mac f12 on PC.
Related
I'm trying to make a wikipedia search bar. The idea is to send a new AJAX request every time search input is changed. I'm using https://www.mediawiki.org/wiki/API:Search_and_discovery as a guideline.
var search = $('#search');
search.keyup(function() {
if (search.val() === '') {
result.html('');
}
$.ajax({
url: '//en.wikipedia.org/w/api.php',
data: {
action: 'query',
list: 'search',
format: 'json',
srsearch: search.val()
},
dataType: 'jsonp',
success: function(response) {
console.log("success!");
}
});
});
However, success function is not even triggered.
On any keypress the error I get is this ("d" pressed):
jquery-2.1.1.min.js:4 GET file://en.wikipedia.org/w/api.php?>callback=jQuery21107844703783826772_1484403407494&action=query&list=search&srse>arch=d&format=json&_=1484403407495 net::ERR_FILE_NOT_FOUND
Thank you in advance for any help or guidance!
Well, you're probably trying to do a AJAX request without a local server (opening your file directly in the browser).
First of all, your url options starts with //en... (without the protocol). It indicates that it'll construct your full url using the same protocol you're using. In this case: file://. That's because your browser is trying to reach file://en.wikipedia.org/....
So, you can set your url to https://en.wikipedia.org/w/api.php to make it work.
Just replace:
url: '//en.wikipedia.org/w/api.php',
with:
url: 'https://en.wikipedia.org/w/api.php',
Looks like you're running it from a simple html file located in your filesystem, in other words not running it from a web server (even local).
Try calling the api with
url: 'https://en.wikipedia.org/w/api.php'
or run the file from a web server (can be a local one).
I am new to angular, and I'm trying to make a call to a Rest API and get its response. My issue is that my JavaScript keeps getting stuck on the Ajax call. I'm not sure if it's the data I am sending or the syntax of the Ajax call. I tried to alert 'Hello world' and that worked, then I alerted the JSON array and that was formatted correctly, but when I do the Ajax post, I don't get any response at all.
Any insight would be nice, thank you.
test.html
<button onclick="myFunction()">Post it</button>
test.js
function myFunction() {
var postData = [{"logintype":"1","user":"Administrator","password":"12345","controlid":"999","host":"192.168.2.164"}
];
$.ajax({
url: '192.168.2.164/isapi/rip.dll/rest/session',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify( postData ),
success: function(){
alert('hello');
},
error: function(){
alert('error');
}
});
};
You have specified a relative URL, where I think you intended to specify an absolute URL. If the current page URL is http://localhost/myapp/, and you request 192.168.2.164/isapi/rip.dll/rest/session, that URL is resolved as http://localhost/myapp/192.168.2.164/isapi/rip.dll/rest/session.
If 192.168.2.164 is the ip address of the server you are trying to hit (and not a directory relative to your current path on your server), you will need to add // to the beginning of the URL to make it absolute (well, schema-relative at least):
$.ajax({
url: '//192.168.2.164/isapi/rip.dll/rest/session',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify( postData ),
success: function(){
alert('hello');
},
error: function(){
alert('error');
}
});
Your issue has nothing to do with angular. What I will refer you to is the angular docs description of how to do a POST request and a small example of the syntax taken from the docs.
Learn to use $http or something similar if you want to develop with angular. https://docs.angularjs.org/api/ng/service/$http
Small example:
// Simple POST request example (passing data) :
$http.post('/someUrl', {msg:'hello word!'}).
then(function(response) {
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
I need to make a ajax call to retrieve data(json) from the RESTfull Web Service which is running in the different domain(KARAF using cxf) and the client from which the ajax call is being made, is on different domain(Apache Tomcat).
The Web Service is returning the data in the form of MediaType.APPLICATION_JSON but due to cross domain call I am receiving the data in the form of jsonp object.
$.ajax({
url: "http://localhost:8181/cxf/view/ID_123",
type: "GET",
crossDomain : true,
contentType: "applicaion/json",
dataType : "jsonp",
jsonpCallback : 'myJsonCallBack',
sucess : function(json) {
alert("Success Called");
},
error : function(xhr) {
alert("Error");
}
});
and the myJsonCallBack funcation is as below..
function myJsonCallBack(data) {
alert("Callback Called");
}
The web service method is as below..
#GET
#Path("/view/{userid}")
public ViewPreference getViewPreference(#PathParam("userid") String userId) {
ViewPreference viewPreference = new ViewPreference("GRID VIEW");
return viewPreference;
}
which is returning json object as below..
{
"viewPreference": {
"preference": "GRID VIEW"
}
}
The problem is when ever I make a ajax call neither the success callback runs nor the myJsonCallBack only error is run.
while checking in firebug it is showing some syntax error telling SyntaxError: missing ; before statement {"viewPreference":{"preference":"GRID VIEW"}}.
How to resolve this problem..?
here's what you should do:
you should return this from the server:
'myJsonCallBack({"viewPreference": {"preference": "GRID VIEW"}})'
rather than this: {"viewPreference": {"preference": "GRID VIEW"}}
this will call the myJsonCallback function and others without syntax errors
hope this helps :)
I'm trying to operate two servers.
MVC Web API service.
MVC Web application.
The idea is that the web application renders a page filled with javascript requests, which populate the actual data from the remote API service. The web application will never itself touch the database, or the API service (besides setting up authorisation tokens initially).
What is the best way to achieve this?
So far I've been using JQuery AJAX requests, attempting to use JSONP. However I always get "x was not called" exceptions.
$.ajax({
url: '#(ViewBag.API)api/customer',
type: 'get',
dataType: 'jsonp',
jsonp: false,
jsonpCallback: function (data) {
debugger;
// code to load to ko
},
error: function (xhr, status, error) {
alert(error.message);
}
});
Also the jsonpCallback function is called before the request is sent, so I assume its actually trying to call a function to generate a string? If I reform this request:
window.success = function (data) {
debugger;
// code to load to ko
};
... with jsonpCallback being "success", I still get the same error (but the success method is never called.
Any ideas? Thanks.
Edit: I've gotten started on the right course from this:
http://www.codeproject.com/Tips/631685/JSONP-in-ASP-NET-Web-API-Quick-Get-Started
Added the formatter, and replaced jsonCallback with success, like a normal ajax. However this only seems to work for get. I cannot delete or update. :(
Can you get it to work using the $.getJSON method?
$.getJSON( "ajax/test.json", function( data ) {
//handle response
});
Have you fired up developer tools in IE and watched the network traffic to see precisely what is being sent and returned?
I am try to get a URL from a one server and using that URL to get contents of another server.
$.ajax({url : 'http://localhost:8080/geturl.jsp?A=1&B=2,C=3',
success : function (data)
{
alert(data);
$.getJSON(data, function (mydata)
{
alert(mydata);
});
},
error : function (data, status, xhr)
{
}
});
I know that we cannot make cross-domain requests in through ajax call, thats why i am using getJSON, i have the following problems
When i simply pass the data to the url part of getJSON (as shown in the code), the alert-box show the correct URL but no get request is being performed ( get requests were monitored from FireBug).
When a hard-code the data to be "http://www.google.com" then the get request is being performed but the no response comes, although the response headers comes and response code is 200 (but it was marked as RED in the Firebug (Dont know why :( )
When I tries to fetch a webpage host in localhost domain, then it is fetched correctly although the response was not JSON.
I have the following doubts
If the getJSON function accecpts only JSON objects as reponse then why no error came when perform above 3.
Whats the correct code to perform my the required functionality.
Suggestions to what happened in each case
Thanks in advance for the answers :)
The getJSON function can only be used across domains to fetch JSONP.
It does not magically evade any security restrictions.
http://api.jquery.com/jQuery.ajax/
This should be a working example for jsonp:
var request = jQuery.ajax(
{
url: "http://Your url",
success: function (data) { console.log('success!'); console.log(data); },
error: function (data) { console.log('error!'); console.log(data); },
dataType: "jsonp",
type: "GET",
data: { key: 'value' }
});