How to get web service data with javascript? - javascript

I have token value in a URL like http://example.com/api.php?action=token
I need to consume this URL data which is a random string, I'm trying with following code:
var jqxhr = $.get("http://example.com/api.php?action=token", function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function() {
alert( "second finished" );
});
Using $.get()
While trying to load, it's showing an error. I'm just stuck with it, how to get the data?

Cross domain calls are restricted by the browser so some solutions are,
1.Cross-Origin Resource Sharing (CORS) or jsonp, but you will require to have access to the server you are calling and configure that (many examples online e.g. How to make cross domain request)
2.server side proxy - create simple server side code e.g. php page that you will call form js and place code in php that calls the targeted cross domain server and return the results to your js. e.g. AJAX cross domain call

try this
$.ajax({
url:"http://example.com/api.php?action=token",
type: "GET",
success: function (data) {
alert(data)
}
});

try this
$.ajax({
url:"http://example.com/api.php?action=token",
type: "POST", //try this
success: function (data) {
alert(data)
}
});

Related

getting the list of files inside a folder using ajax

I have an url that is listing the files inside a folder:
Using javascript I need to obtain that list of files.
My code:
$.ajax({
url: 'http://webtests02/pruebas/',
success: function (data) {
console.log(data);
}
});
The thing is I am getting nothing as the return of the ajax GET call.
I tried other formats like using $.get but the result is the same so I cloncluded that or as it is not a .html, .aspx I can't get the code and scrape the content or the IIS is blocking these requests so I can't get it using jquery...
The website is mine so I can configure whatever needed in the IIS...
EDIT: I created an asp website that lists the files in the folder:
But I am still getting an empty response when I make the ajax call:
EDIT: THREAD CLOSED. It was due to a CORS authorization error.
Newer implementations of jQuery use the .done() method on the Ajax object to deal with completion and data of the AJAX call.
$.ajax({
url: "http://fiddle.jshell.net/favicon.png",
beforeSend: function( xhr ) {
xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
}
}).done(function( data ) {
if ( console && console.log ) {
console.log( "Sample of data:", data.slice( 0, 100 ) );
}
});
http://api.jquery.com/jQuery.ajax/#jqXHR

Simple HTTP GET not working with https to get JSON

I have this working PhoneGap application built with AngularJS and Onsen UI, that accesses a PHP file where it gets some data in the response. The php file was on a domain with simple http, but now that I moved it to one that supports https , I keep bumping into some weird problems.
I tried the AngularJS async way of getting data, and also an ajax call.
$http.get('https://blablabla.com/file.php?parameters').then(function(response) {
//SUCCESS
alert(response);
var z = response;
},function(response) {
alert("Failed");
});
It goes to the SUCCESS part, but the data that I have in it is incorrect. It should be a string (a plain JSON string, that I will stringify and convert to a json object)
The ajax call is the following:
function httpGet(theUrl) {
var dataToReturn;
$.ajax({
type: 'GET',
url: theUrl,
cache: false,
async: false,
data: "",
success: function(data, textStatus, result) {
dataToReturn = data;
},
error: function (result, textStatus, errorThrown) {
alert("Failed to get response from server!");
}
});
return dataToReturn;
//var xmlHttp = new XMLHttpRequest();
//xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
//xmlHttp.send( null );
//return xmlHttp.responseText;
};
I'm basically calling a php script that is in https, from a PhoneGap app.
If I change the address to http, it works flawlessly...
I also want you to note, that PhoneGap basically creates some sort of local proxy. I'm not really sure how to elaborate on this, though...
Any ideas on how to solve this, to get the same data as I would when the addresses are simple "http"?
Angular automatically converts json, better if you set the proper header from your PHP serverside:
header('Content-Type: application/json');
just before the echo.
Second your get seems to be missing a parenthesis
$http.get('https://blablabla.com/file.php?parameters')
.then(function(response) {
//SUCCESS
alert(response);
var z = response;
},function(response) {
alert("Failed");
});
Third, the response doesn't go straight on response anymore but response.data
so you might want to try
alert(response.data);
var z = response.data;
Warning! this varies a lot depending on your Angular.js version
there are several different syntaxes to use for the $http object depending on the angular version you're on.

retrieving json data in cross domain

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 :)

JQuery ajax query fails very silently

I have read similar questions with similar problems but every advice I read seems to be inefficient for me. Here is the ajax call (I am using Jquery 1.9.1):
$( document ).ajaxError(function() {
alert( "AJAX ERROR" );
});
$.post( "/lists/complete", { itemID:id }, function(answer) {
alert("SUCCESS");
}, "text" ).fail( function() {
alert("ERROR");
}).always( function() {
alert("DONE");
});
On the server side the request is received as expected. If I monitor the server response on the client side (using Firebug), I can see that the server sends the 200 response along with the correct data in the body. However, no alert is never triggered !
What can I do to understand the issue ? I must add that I have very little experience with JS and with Jquery...
I'm also not a fan of jquery post. I prefer using $.ajax. However it is recommended to chain done, fail and always.
$.ajax({
url: ' yoururl ',
type: 'POST',
// dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
data: {param1: 'value1'},
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
http://api.jquery.com/jQuery.ajax/
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and
jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare
your code for their eventual removal, use jqXHR.done(), jqXHR.fail(),
and jqXHR.always() instead.
I v never been a fan of the $.post i rather use the full ajax call :
$.ajax({
type: 'POST',
url: '/lists/complete',
data: data,
success: function(data){
alert("SUCCESS");
},
error: function(xhr, type, exception) {
// if ajax fails display error alert
alert("ajax error response type "+type);
}
});
Give this a shot and let me know if the alerts go off.
If this doesn't work out, open up the console (firebug...) and go to the network tab, clear it and send your request.
Click on the request and check the headers and response if they are normal.

jQuery $.getJSON not working

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' }
});

Categories

Resources