Call WCF rest service with Javascript (JQuery) do not receive any response - javascript

The WCF service gets called for sure (the debug kicks in).
No response back to javasript callbacks.
If i configure the call with dataType:JSON the error callback is called.
If i configure dataType:JSONP no error occurs and no response is received (no callback happens neither error or sucess or done).
$.ajax({
type: "GET",
dataType: "jsonp",
contentType: "application/json;charset-uf8",
crossDomain: false,
async: true,
url: "http://myurl",
done: function (results) {
// Uhm, maybe I don't even need this?
var parsed = JSON.parse(results);
alert(parsed);
return results;
},
success: function (data, text) {
alert(text);
alert(data);
},
error: function (request, status, error) {
alert(request);
alert(status);
alert(error);
}
});
I'm running this on localhost.
I have no clue at all, i don't even know how to get more in depth error details.
Any help appreciated.

Directly sending an HTTP request to call the WCF service applies the Restful style service. Thereby we should ensure that WCF service is restful style whereas mostly WCF service based on the SOAP web service, and the invocation is completed by using client proxy class.
From the description, I suggest you add a breakpoint on the JS statement then debug it in the browser. Besides, Success event is deprecated in Jquery, I suggest you use the Done event callback after the AJAX method.
$.ajax({
method:"Get",
url: "http://10.157.13.69:11000/Service1.svc/GetData?value=34",
contentType:"application/json"
}).done(function(data){
console.log(data);
})
I would like that you could post the code details on the server-side so that I try to make an example as much as possible.
At last, please refer to my previous demo on this topic, wish it is useful to you.
How to fix "ERR_ABORTED 400 (Bad Request)" error with Jquery call to C# WCF service?
Feel free to let me know if there is anything I can help with.

Related

Make $.ajax call to url without knowing dataType

I'm trying to set up a generic call to webservices using jquery $.ajax. I'd like to be able to get raw data back and bind it to a grid.
I have calls working correctly when I know the dataType, but I want to try and make an ajax call without knowing the datatype, specifically to find what the dataType is.
For example, my ajax call knowing the datatype could be:
$.ajax({
type: 'GET',
crossDomain: true,
dataType: "jsonp",
url: 'http://itunes.apple.com/search?term=coldplay',
success: function (res, status, xhr) {
//DoStuff;
},
error: function (jqXHR, textStatus, errorThrown) {
//DoStuff
}
});
But any time I make a request without knowing the datatype I simply get a response status of "Error"?
What I would eventually like to be able to do with this is ping a url (webservice) that returns json, xml, or perhaps odata(unlikely). Since I won't know which, I want to be able to simply make a call to the url once to find out what kind of data I might get back, along with what content-type there is.
I've tried simply getting back the content type in the header in the error, but so far nothing I've tried has worked or returned anything at all.
$.ajax({
type: 'GET',
crossDomain: true,
url: 'http://itunes.apple.com/search?term=coldplay',
success: function (res, status, xhr) {
//DoStuff
},
error: function (jqXHR, textStatus, errorThrown) {
$("#results").html(textStatus + jqXHR.getResponseHeader('Content-Type'));
}
});
Can this even be done with Jquery?
Edit
I am aware that this can (and in most cases should) be done server side, and in all likelihood this is what will end up happening. But for the purposes of seeing how far I can go binding a grid to a datasource clientside without knowing my dataType the above question is born.
Thanks to all for the time.
Your approach is reasonable, but you are asking the user's browser to fetch information from a third party web server.
XMLHttpRequest cannot load http://itunes.apple.com/search?term=coldplay. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access.
Unless the third party grants you permission, the Same Origin Policy will prevent your JavaScript from accessing any information about the response.
You should move your logic server side.

Jquery Ajax Call to WEB API

I'm trying to make a simple jquery ajax call to a WEB API method.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'POST',
url: 'http://redrock.com:6606/api/values/get',
dataType: "jsonp",
crossDomain: true,
success: function (msg) {
alert("success");
},
error: function (request, status, error) {
alert(error);
}
});
});
</script>
WEB API action:
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
ajax call does not hitting the WEB API. I get the below error in browser console.
GET http://redrock.com:6606/api/values/get?callback=jQuery18207315279033500701_1383300951840&_=1383300951850 400 (Bad Request)
Unless you are doing a cross domain call, there is no need to use jsonp (jsonp also requires a custom formatter in Web API).
$.getJSON('http://redrock.com:6606/api/values', function(data){
console.log(data);
});
EDIT:
To install a jsonp media type formatter, have a look at this project: https://github.com/WebApiContrib/WebApiContrib.Formatting.Jsonp
Download the formatter using nuget
Register the formatter
Update your routeconfig
You haven't included the code for the route setup, but assuming it is correct, the problem is probably caused by the fact that you have named you WebApi method 'Get' while you are trying to hit it using a POST request. This happens because WebApi tries to figure out the HTTP verb from the action name.
I would suggest either renaming the action or adding the [HttpPost] attribute to your action method. You may also try the WebApiRouteDebugger package.

Getting 'data is null' on a Twitter API call but displays data in browser

I'm trying to display the follow count of a twitter account, but when I hook into the API using this code:
$.getJSON("https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true", function(data) {
console.log(data);
if (!data.error) {
$("#followers").html(data.followers_count);
}
});
I get a 200 ok report but with Data is null message.
But if I download the json file to my local machine and change the getJSON call accordingly, it works straight away.
Has anyone got any ideas on what could be causing this?
Thanks
Also just to add, if I put the Twitter API url into my browser it displays all the data, which makes it even weirder.
Maybe the problem lies with jsonP, since you are calling a remote server and you must specify you should use jsonP. Have you tried adding callback=? as a parameter
$.getJSON("https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true&callback=?", function(data) {
if (!data.error) {
$("#followers").html(data.followers_count);
}
});
Taken from jQuery docs
JSONP
If the URL includes the string "callback=?" (or similar, as
defined by the server-side API), the request is treated as JSONP
instead. See the discussion of the jsonp data type in $.ajax() for
more details.
$.ajax({
url: 'https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true',
dataType: 'jsonp',
success: function(data){
console.log(data.followers_count);
}
});

JQuery server side method call internal

i often call my aspx server side method with the help of jquery....like
$.ajax({
type: "POST",
url: "login.aspx/Authenticate",
data: JSON.stringify(DTO),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
sHtml = data.d;
if (sHtml != "") {
alert(sHtml);
location.href = sHtml;
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
but the funny things is that i dont know how jquery call my static method from outside.
i saw that when i call my server side method then page_load does not fire but in case of updatepanel partial postback page_load execute first.
so i want to know the internal logic of jquery that how it can call server side method directly........looking for good explanation. thanks
so i want to know the internal logic of jquery that how it can call server side method directly
It can't.
jQuery can cause the browser to make an HTTP request to a URI.
The server can run code in response to a URI being requested in order to decide what content and headers to return.
What happens in jquery case is that the method is marked as webmethod which means that it works as an endpoint for an httprequest as if it is a webservice and when you do that, then the jquery make a httprequest to this method as if he is calling a webservice.
this URL will give you a deep view on what happen when you are making any ajax call http://msdn.microsoft.com/en-us/magazine/cc163499.aspx
your server side methods are marked with the [WebMethod] attribute, right? this attribute exposes the method as an xml web service.
http://msdn.microsoft.com/en-us/library/byxd99hx(v=vs.71).aspx
since this autogenerated "webservice" has nothing to do with the page, page_load is not called.

What/when does a call to the jQuery AJAX method return?

A little background:
I am trying to implement and AJAX powered SlickGrid. There isn't much documentation so I used this example as a base.
In this example there is the following code that hits the desired web service to get the data:
req = $.jsonp({
url: url,
callbackParameter: "callback",
cache: true, // Digg doesn't accept the autogenerated cachebuster param
success: onSuccess,
error: function(){
onError(fromPage, toPage)
}
});
req.fromPage = fromPage;
req.toPage = toPage;
I'm not exactly sure what jsonp does but from what i've read it appears to be very similar to the ajax method in jQuery except it returns json and allows cross domain requests. The webservice that I happen to be calling only returns XML so I changed this chunk of code to:
req = $.ajax({
url: "/_vti_bin/lists.asmx",
type: "POST",
dataType: "xml",
data: xmlData,
complete: onSuccess,
error: function (xhr, ajaxOptions, thrownError) {
alert("error: " + xhr.statusText);
alert(thrownError);
},
contentType: "text/xml; charset=\"utf-8\""
});
req.fromPage = fromPage;
req.toPage = toPage;
My issue is that my page errors out at req.fromPage = fromPage; because req is null.
Am I wrong to think that I can just replace my jsonp call with a call to the ajax method? Is req just not set because my ajax call hasn't finished by the time that code is executed? How can I get around either of these issues?
If I comment out the last two lines and hard-code those values elsewhere everything runs fine.
Am I wrong to think that I can just replace my jsonp call with a call to the ajax method?
No, that should work just fine.
Is req just not set because my ajax call hasn't finished by the time that code is executed?
Yes, that is correct.
The ajax methods starts the request and returns immediately. If you want to do something after the response has arrived you should do that in the success event handler.
You might actually want to use the success event instead of the complete event, as the complete event happens even if there is an error.
You could specify async: false, in your settings to make the ajax call wait for the response, but that means that the browser freezes while it's waiting.
As Guffa stated, $.ajax() works asynchronically. Thus, you have to specify a callback that will be called when the request has returned a response, rather than to just use whatever $.ajax() returns.
There are a couple of different callback methods you can specify:
complete - runs when you recieve a response, regardless of its status.
success - runs when you recieve a response with a successful status code (usually 200).
error - runs when you recieve a response with an error code (for example 404 or 500).
To do something with the response body after a successful request, you should do something like
$.ajax({
...
success: function(body) {
alert('This is the method body:' + body);
}
});
Read up in the documentation on the different methods to see what more parameters you can use.

Categories