Error handling with Javascript-enabled WCF? - javascript

Is there documentation on how to use the callback functions in a WCF Service that is exposed to Javascript? I'm interested in getting information from the FailureCallback as to why my method isn't firing.
In other words I have the follwoing JavaScript code:
function getWCF_RowNumber(parentID) {
logEvent("<strong>Busy</strong>: Please wait while lower grid is refreshed...");
var service = new ajaxTest();
service.Vendor_GetParentRowNumber(parentID, moveBottomGridToRow, wcfFailCallback, null);
}
How do I implement wcfFailCallback?

I'm assuming you're using ASP.NET AJAX and not jQuery or some other 3rd party JavaScript library.
The ASP.NET AJAX failure callback takes a single parameter. From MSDN, a sample failure callback would look like this:
function wcfFailCallback(error)
{
var stackTrace = error.get_stackTrace();
var message = error.get_message();
var statusCode = error.get_statusCode();
var exceptionType = error.get_exceptionType();
var timedout = error.get_timedOut();
// Display the error.
var RsltElem =
document.getElementById("Results");
RsltElem.innerHTML =
"Stack Trace: " + stackTrace + "<br/>" +
"Service Error: " + message + "<br/>" +
"Status Code: " + statusCode + "<br/>" +
"Exception Type: " + exceptionType + "<br/>" +
"Timedout: " + timedout;
}
So the wcfFailCallback function takes an error parameter, which has a number of properties that provide you information about what failed.
The full article on MSDN is here. It goes into some decent amount of details about how to hook up WCF services to ASP.NET AJAX clients.
I hope this helps!! If there are other questions or if I didn't fully understand your question, let me know and I'll update my answer accordingly.

Related

Cordova app has internet connection via emulator, but not on device [update: ajax problem]

I am trying to build a small app via cordova that sends data to a PERL-Script on a server. The debug and release build work fine on the genymotion emulator, however sending the data from Android phones does not work. There is no error message from the app (either, which is supposed to show up when the connection fails).
Running USB debugging, I do get the follwoing invoke error message (the savedataLastpage funtion is supposed to send the data):
Uncaught TypeError: Illegal invocation
at e (jquery-2.1.3.min.js:4)
at Ac (jquery-2.1.3.min.js:4)
at Function.n.param (jquery-2.1.3.min.js:4)
at Function.ajax (jquery-2.1.3.min.js:4)
at Object.saveDataLastPage (index.js:631)
at Object.renderLastPage (index.js:461)
at Object.recordResponse (index.js:597)
at HTMLButtonElement.<anonymous> (index.js:357)
at HTMLButtonElement.dispatch (jquery-2.1.3.min.js:3)
at HTMLButtonElement.r.handle (jquery-2.1.3.min.js:3)
The pertaining code is the following:
index.js:631
saveDataLastPage:function() {
$.ajax({
type: 'post',
url: '/URL/',
data: localStore,
crossDomain: true,
success: function (result) {
var pid = localStore.participant_id, snoozed = localStore.snoozed, uniqueKey = localStore.uniqueKey, pause_time=localStore.pause_time;
localStore.clear();
localStore.participant_id = pid;
localStore.snoozed = snoozed;
localStore.uniqueKey = uniqueKey;
localStore.pause_time=pause_time;
$("#question").html("<h3>Thank you, your responses have been sent.</h3>");
},
error: function (request, error) {
console.log(error);
$("#question").html("<h3>Error: Please check your internet connection.</h3><br><button>Send again</button>");
$("#question button").click(function () {app.saveDataLastPage();});
}
});
},
index.js:461
else {
var datestamp = new Date();
var year = datestamp.getFullYear(), month = datestamp.getMonth(), day=datestamp.getDate(), hours=datestamp.getHours(), minutes=datestamp.getMinutes(), seconds=datestamp.getSeconds(), milliseconds=datestamp.getMilliseconds();
localStore[uniqueKey + '.' + "completed" + "_" + "completedSurvey" + "_" + year + "_" + month + "_" + day + "_" + hours + "_" + minutes + "_" + seconds + "_" + milliseconds] = 1;
app.saveDataLastPage();
}
As stated before, on the genymotion emulator the ajax script works fine without the error and sends the data to the script.
I'm not sure why the emulator would work just fine but the error Uncaught TypeError: Illegal invocation suggests that it is a problem with the ajax post call. Specifically, the default setting of processing the data into a query string likely fails.
From the ajax documentation:
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
That means you can either turn off the processing processData: false which will post the data in the body of the request or you have to transform the localStore data into a proper object (from whatever it was before).
If it is like an object you can do the following:
var data = {};
for (var elem in localStore) {
data[elem] = localStore[elem];
}
or possibly in brief:
var data = {};
localStore.each(function(elem) { data[elem.name] = elem.value; });

window.onerror line number always 1

I want to get a mail if an error occurs in my program. This works fine:
window.onerror = function(msg, url, line, col, error) {
prog = "fehler";
var urlJ = server + prog + querystrJsonO + "&qu=" + qu + "&msg=" + msg + "&line=" + line + "&col=" + col;
$.getJSON(urlJ, function(data) {});
};
But I get only linenumber 1.
My code is not minified. What can I do to get the linenumber of the error?
Try creating a XMLHttpRequest inside the function and send a get request to your server with a phone script ready to receive the parameters. Then you can use mail() function to send yourself mail regarding problem. Am using it hope it sounds well to you

Unable to get property 'query' of undefined or null reference

I am using Yahoo Weather API.
Here is my code:
<script>
var callbackFunction = function (data) {
console.log(data);
var location = data.query.results.channel.location;
var condition = data.query.results.channel.item.condition;
var wind = data.query.results.channel.wind;
var units = data.query.results.channel.units;
document.getElementById('Weather-Info').innerHTML = 'The weather for ' + location.city + ', ' + location.region + ' is ' + condition.temp + units.temperature + ' with a wind speed of ' + wind.speed;
}
callbackFunction()
<script src="https://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20weather.forecast%20WHERE%20woeid%3D%222409681%22%20and%20u%3D%22f%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=callbackFunction"></script>
Everytime I go into the page I receive the following pop-up:
Unable to get property 'query' of undefined or null reference
But if I hit No, the data is still populated.. how is it populating data if it is telling me that a property is undefined? The YQL Weather API is a really complicated.
Why are you calling the callback function yourself? In any case, calling it without a parameter, means that data will be undefined and this is why you get the error.
I know nothing about Yahoo! weather API but this seems like a JSONP thing, so try removing this part:
callbackFunction()
since this will be called automatically once the script loads.

display a javascript function

I am creating an API and I want to show a code example in javascript that you can use to invoke the API.
I write a test function in javascript. I would like to be able to execute AND display the code for the javascript function(s) but I would rather only have one copy of the code to make maintenance easier.
Example, I have the following code:
function doauth_test(apikey,username,userpass)
{
$.ajax({
url: "/api/v1.2/user.php/doauth/" + username + "/" + userpass + "?apikey=" + apikey,
type: "GET",
success: function(data,textStatus,xhr) {
var obj = JSON.parse(data);
var authkey = obj.authkey; //store this somewhere for subsequent use
var user_id = obj.user_id; //store this somewhere for subsequent use
},
error: function(xhr, ajaxOptions, thrownError) {
alert("ERROR! Status code: " + xhr.status + " Response Text: " + xhr.responseText);
}
});
}
I want this code to be something I can EXECUTE and I want it to display the code in a DIV in my documentation example. But I do not want to (ideally) have two copies of this code.
You can call toString() on a function to get its source code.
Alternatively, you can use the DOM to get the text of the <script> tag.
Just use toString method for your function and it will return your function definition as a string.
alert(doauth_test.toString());
Hope it helps!

400 Bad Request from Yahoo Finance API

Here's my code in a javascript function in a HTML file
var url = 'http://query.yahooapis.com/v1/public/yql';
var startDate = '2012-01-01';
var endDate = '2012-01-08';
var jsonData = encodeURIComponent('select * from yahoo.finance.historicaldata where symbol in ("YHOO","AAPL","GOOG","MSFT") and startDate = "' + startDate + '" and endDate = "' + endDate + '"');
$.getJSON(url, 'q=' + data + "&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json", function(){alert("done!");});
When i open the file in the browser, my other functions work except the above as it produces:
GET http://query.yahooapis.com/v1/public/yql?q=[object%20Object]&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json 400 **(Bad Request)** jquery-1.8.3.min.js:2
send jquery-1.8.3.min.js:2
v.extend.ajax jquery-1.8.3.min.js:2
v.(anonymous function) jquery-1.8.3.min.js:2
v.extend.getJSON jquery-1.8.3.min.js:2
drawChart
Should this:
$.getJSON(url, 'q=' + data + "&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json", function(){alert("done!");});
be this?
$.getJSON(url, 'q=' + jsonData + "&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json", function(){alert("done!");});
Just a heads up - I have a couple of projects (Java and JavaScript) which call this API. They usually work but occasionally fail with a 400 without any change to the code then work a few hours/days later, again, without changing the code. I think if there is some problem with the server it may return this rather than a correct error in the 500 range (server error - It's me, not you)
Errors in the 400 range should be a message from the server along the lines of "it's you, not me - fix your request before you send it again" but I don't think this is the case with this API.
In short - it may be them not you!

Categories