Calling a webservice using JQuery - javascript

I am using this code from http://www.joe-stevens.com/2010/01/04/using-jquery-to-make-ajax-calls-to-an-asmx-web-service-using-asp-net/
function callWebService(address) {
var result;
$("#result").addClass("loading");
$.ajax({
type: "POST",
url: address,
data: "{}",contentType: "application/json; charset=utf-8",
dataType: "json",
success: Success,
error: Error
});
}
function Success(data, status) {
$("#result").removeClass("loading");
$("#result").html(data.d);
alert("Success");
}
function Error(request, status, error) {
$("#result").removeClass("loading");
$("#result").html(request.statusText);
alert("Error");
}
I don't understand what is wrong with this code. It keeps returning "Error"

Also make sure that the service URL that you're trying to access is in the same domain as your site. AJAX calls won't succeed if you cross domains, since browsers subject AJAX calls to the same domain policy. Can you also include the URL you're trying to access?
If you're trying to access a resource at a different domain, you may want to consider a JSONP request instead. See the jQuery AJAX documentation for a discussion of how to use JSONP.
I think if you combine knowing the URL you're trying to access along with Justin and mohlsen's suggestions, I think we can help.

Your code looks fine at first glance.
I recommend you use FireBug to attempt to isolate the problem further, as it will allow you to see the actual HTTP requests, POSTed data, etc...

A few suggestions based on some code I have doing this. But as others have said, make sure to manually look at the data going out and coming back. Your link references asp.net webservice, is that what you are calling since you didn't mention it.
Make sure the "address" url is of the form /location/page.asmx/methodname
You might need to pass the data to the success method in the call
success: function(msg) {
//msg is a json object, .d is the data field returned by asp.net
if (msg.d.length > 0)
ProcessData(msg.d);
else
HandleError('No data was returned.');
},
error: function() {
HandleError('There was a problem calling the webservice.');
}

Related

How to get a json response from yaler

I create an account with yaler, to comunicate with my arduino yun. It works fine, and i'm able to switch on and off my leds.
Then i created a web page, with a button that calls an ajax function with GET method to yaler (yaler web server accept REST style on the URL)
$.ajax({
url: "http://RELAY_DOMAIN.try.yaler.net/arduino/digital/13/1",
dataType: "json",
success: function(msg){
var jsonStr = msg;
},
error: function(err){
alert(err.responseText);
}
});
This code seem to work fine, infact the led switches off and on, but i expect a json response in success function (msg) like this:
{
"command":"digital",
"pin":13,
"value":1,
"action":"write"
}
But i get an error (error function). I also tried to alert the err.responseText, but it is undefined....
How could i solve the issue? Any suggestions???
Thanks in advance....
If the Web page containing the above Ajax request is served from a different origin, you'll have to work around the same origin policy of your Web browser.
There are two ways to do this (based on http://forum.arduino.cc/index.php?topic=304804):
CORS, i.e. adding the header Access-Control-Allow-Origin: * to the Yun Web service
JSONP, i.e. getting the Yun to serve an additional JS function if requested by the Ajax call with a query parameter ?callback=?
CORS can probably be configured in the OpenWRT part of the Yun, while JSONP could be added to the Brige.ino code (which you seem to be using).
I had the same problem. I used JSONP to solve it. JSONP is JSON with padding. Basically means you send the JSON data with a sort of wrapper.
Instead of just the data you have to send a Java Script function and this is allowed by the internet.
So instead of your response being :
{"command":"digital","pin":13,"value":0,"action":"write"}
It should be:
showResult({command:"analog",pin:13,value:0,action:"write"});
I changed the yunYaler.ino to do this.
So for the html :
var url = 'http://try.yaler.net/realy-domain/analog/13/210';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'showResult',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.dir(json.action);
},
error: function(e) {
console.log(e.message);
}
});
};
function showResult(show)
{
var str = "command = "+show.command;// you can do the others the same way.
alert (str);
}
My JSON is wrapped with a showResult() so its made JSONP and its the function I called in the callback.
Hope this helps. If CORS worked for you. Could you please put up how it worked here.

Ajax response with JSONP, can see result cannot use it

I have the following javascript:
jQuery(document).ready( function($) {
var id = "123";
var api = "example.com:8999/".concat(id)
$.ajax({
url : api,
type: 'GET',
dataType: 'jsonp',
// jsonpCallback: "localcallback",
success: function (data) { alert('success'); }
})
});
I can see the response in chrome dev tools, but the alert isn't getting called. Ultimately I need to work with this response to set the value of a div.
Image of chrome tools:
Thanks
EDIT: Put 'POST', was using 'GET', still not working. Also, I think I'd prefer "mom and pop" json, but due to CORS and the fact I'm not good with the web and am just trying to hack this together.
Your server is not returning JSONP. It's returning plain JSON. If you specify JSONP, then the server must explicitly create a JSONP formatted response or the ajax response will not be received and processed properly.
FYI, a JSONP request is sent via a script tag (that's how it gets around the same-origin limitation for cross domain requests) and the response has to be formatted as a script that calls a function and passed the requested data to that function. You can read about how JSONP works here.
Just make your ajax call without specifying the 'dataType' attribute, then control should come back to your success callback if your ajax call completes successfully.
FYI: jQuery will try to find the response data type based on the MIME type of that response.
Example:
$( function() {
$.ajax({
url :"http://example.com:8999/123",
type: 'GET',
success: function (data) {
console.log(data); // Prints the response on console
alert('success');
}
})
});
If you want to make this call only with JSONP then it would be better to share the reason with us, so that we can suggest a better solution if possible.

Feeding webpage data via remote Web API

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?

Calling a web service in JQuery and assign returned Json to JS variable

This is my first time attempting working with JQuery, Json AND calling a web service.. So please bear with me here.
I need to call a webserivce using JQuery, that then returns a Json object that I then want to save to a javascript variable. I've attempted writing a little something. I just need someone to confirm that this is indeed how you do it. Before I instantiate it and potentially mess up something on my company's servers. Anyways, here it is:
var returnedJson = $.ajax({
type: 'Get',
url: 'http://172.16.2.45:8080/Auth/login?n=dean&p=hello'
});
So there it is, calling a webservice with JQuery and assigning the returned jsonObject to a javascript variable. Can anyone confirm this is correct?
Thanks in advance!
var returnedJson = $.ajax({
type: 'Get',
url: 'http://172.16.2.45:8080/Auth/login?n=dean&p=hello'
});
If you do it like this returnedJson would be an XHR object, and not the json that youre after. You want to handle it in the success callback. Something like this:
$.ajax({
// GET is the default type, no need to specify it
url: 'http://172.16.2.45:8080/Auth/login',
data: { n: 'dean', p: 'hello' },
success: function(data) {
//data is the object that youre after, handle it here
}
});
The jQuery ajax function does not return the data, it returns a jQuery jqHXR object.
You need to use the success callback to handle the data, and also deal with the same origin policy as Darin mentions.
Can anyone confirm this is correct?
It will depend on which domain you stored this script. Due to the same origin policy restriction that's built into browsers you cannot send cross domain AJAX requests. This means that if the page serving this script is not hosted on http://172.16.2.45:8080 this query won't work. The best way to ensure that you are not violating this policy is to use relative urls:
$.ajax({
type: 'Get',
url: '/Auth/login?n=dean&p=hello'
});
There are several workarounds to the same origin policy restriction but might require you modifying the service that you are trying to consume. Here's a nice guide which covers some of the possible workarounds if you need to perform cross domain AJAX calls.
Also there's another issue with your code. You have assigned the result of the $.ajax call to some returnedJson variable. But that's not how AJAX works. AJAX is asynchronous. This means that the $.ajax function will return immediately while the request continues to be executed in the background. Once the server has finished processing the request and returned a response the results will be available in the success callback that you need to subscribe to and which will be automatically invoked:
$.ajax({
type: 'Get',
url: '/Auth/login?n=dean&p=hello',
success: function(returnedJson) {
// use returnedJson here
}
});
And yet another remark about your code: it seems that you are calling a web service that performs authentication and sending a username and password. To avoid transmitting this information in clear text over the wire it is highly recommended to use SSL.

jQuery .getJSON vs .post which one is faster?

Using
$.getJSON();
or
$.post();
I'm trying to send some parameters through a page that is just for AJAX request
and get some results in JSON or html snippet.
What I want to know is that which one is faster?
Assume the HTML file would be simply plain boolean text (true or false)
As others said there is no real difference between the two functions, because both of them will be sent by XMLHttpRequest.
If the server is handling both of the requests with the same code then the handling times should be the same.
Therefore the question can be translated to which one is faster the HTTP GET request or the POST request?
Because the POST request needs two additional HTTP headers (Content-Type and Content-Length) comparing to the GET request the latter should be faster (because less data will be transferred).
But that's just the speed, I think it's better to follow the REST guidelines here. Use POST if you're modifying something, use GET if you want to fetch something.
And one another important thing, GET responses could be cached, but I was having problems caching POST ones.
i dont think it will make a difference both make use of ajax, .post loads the data using http post request where as getJSON uses a http get request more over you dont have to explicitly tell getJSON the dataType
If it is a HTTP action that is retrieving data from the server without persisting (updating) anything, GET is the correct semantic to use.
Both post and get use HTTP so performance difference will be negligible, especially considering the variables of WAN communication.
They are both wrappers/shorthand methods for jQuery.ajax, so there wont be a performance difference.
This is old but ...
We all have to remember about: CSRF/XSRF.
If you do it this way:
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: {
token : 'pass-some-security-token-here'
},
cache: false,
success: function(data) {
//do your stuff here
}
});
you can receive it then like this, nullifying most CSRF/XSRF
if (isset($_POST['token'])) { //you can also test token further
//do your stuff her and send back result
} else {
//error: sorry, invalid, or no security token
}
In many cases GET is an invitation for bad guys, as getJSON uses GET HTTP request.
$.getJSON(); is a shortcut to $.ajax(); which also calls $.post(); so you won't see much difference (but it will be easier to use $.getJSON() directly).
See the jquery doc
[EDIT] NimChimpsky was faster than me...
There are no difference, Because both are using XMLHttpRequest.
First, $.getJSON() is a shorthand Ajax function, which is equivalent to:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
https://api.jquery.com/jQuery.getJSON/
Second, $.post() is also a shorthand Ajax function, which is equivalent to:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
https://api.jquery.com/jquery.post/

Categories

Resources