JQuery autocomplete function causing reference error - javascript

I am using jquery auto complete functionality. But occasionally I get Reference error:function is undefined in IE but works in Chrome.
This is my code which calls a backend Java function.
jQuery('autocomplete').focus(function() {
var f = jQuery(this);
f.autocomplete({
minLength: 3,
source: function(request, response) {
var etype = jQuery("#type").val();
Util.getId(
function(data) {
if (!isUserSessionValid(data[0])) {
return;
}
response(exportRespToArray(data));
},
etype,
f.val(),
getLang()
);
}
});
});
Util.getId() is a backend java function that returns data back. On success, the code checks if user session is still valid, if not forward to login screen.
But occasionally IE displays reference error that exportRespToArray is undefined. Both the functions are clearly defined in the external js file which is imported into the jsp. The autocomplete function is initialized through document.ready function.
It's legacy code and I am no jQuery expert. I guess the success keyword inside the Util.getId() function is optional? Why do I get the reference error only in IE if the call was success?
Ok. Did some research and function(data) is a DWR callback function.I could probably add an errorHandler block to find out if any error is returned from server.
Util.getId(
etype,
f.val(),
getLang(), {
callback:function(data) {
if (!isUserSessionValid(data[0])) {
return; }
response(exportRespToArray(data));
},
errorHandler:function(message) {
alert("Error returned: " + message);
}
});

Related

Word Office JS Addin - GET Request - Object doesn't support property or method 'apply'

I'm trying to get some data from a Web API through a Word Office JavaScript addin using an ajax request. However, I am getting the following error when I make the call:
0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'apply'
Here is my code:
Office.onReady(function () {
// Office is ready
$(document).ready(function () {
// The document is ready
// Use this to check whether the API is supported in the Word client.
if (Office.context.requirements.isSetSupported('WordApi', '1.1')) {
$('#rooms').click(Word.run(function (context) {
$.ajax({
url: "http://localhost/soundtestingsoftware/public/api/projects/27/rooms",
type: "GET",
success: function (result) {
var doc = context.document.getSelection();
doc.insertText(JSON.stringify(result), Word.InsertLocation.start);
return context.sync();
},
error: function (err) {
console.log(err);
}
});
}));
$('#supportedVersion').html('This code is using Word 2016 or later.');
}
else {
// Just letting you know that this code will not work with your version of Word.
$('#supportedVersion').html('This code requires Word 2016 or later.');
}
});
});
I've added my AppDomain into the manifest file. Could someone tell me why this error is happening please? Thanks

AJAX silently failing when loading script

I just notice a weird behavior when dynamically loading scripts with AJAX.
I intentionally have a misspelled code that throws an error when it is parsed. Even though the Chrome's console indeed shows the error, the AJAX fail handler is never called.
This is the function that I use to load files:
var load_source = function (path) {
/* Variable used to determine whether the request was successful */
var success = false,
failed;
$.ajax(
{
url: path,
async: false,
dataType: 'script',
method: 'GET'
}
).
done(function () {
success = true;
}).
fail(function (xhr, status, error) {
failed = error.stack ? error.stack : error;
});
if (failed)
{
throw new Error('Unable to load JS file {0}: {1}'.format(path, failed));
}
}
The only variable provided to the load_source function is "path", which value is a string with the location and name of such a file: "js/myFile.js".
The misspelled part (the part with a typo) of the script to load is this:
var f = function (arg) {
var param1 = 3,
param2, /* NOTICE the typo: there is a comma instead of a semicolon */
if (param1 > arg)
{
return true;
}
// And more code is coming next...
If I look at the Chrome's console, it shows the error:
Uncaught SyntaxError: Unexpected token if
So far the only way I can catch the error is with the window's onerror event.
So, if that is the only way to catch the error, could you tell me how to stop the "coding" flow, I mean, whenever I call load_source that throws an error (which is handled by the window's onerror function) I want the script to do nothing else:
load_source('js/myFile.js'); // This script will throw the "Uncaught SyntaxError: Unexpected token if" error.
// So I don't want the following code to be executed.
sum(4, 3);
mul(5, 5);
// ...
Can you guys tell me how make the fail event to be triggered?
I also tried with " $(document).ajaxError" but with the same results.
It's async stuff :) There is no way that the resource fetching (load_source(url)) is going to be finished before your sum() and mul() functions are executed.
The things you want to make dependable on the successful loading of your remote resource, should be placed in a callback, which is executed after success of the resource fetching.
UPDATE
Regarding the "aysnc: false" in your example, and mentioned in the
comments: this applies only to the $.ajax() function scope, not to
the parent function.
Also: is_empty is not part of the standard
library, I assume you have defined that function elsewhere?
The fail event is being triggered, it's just not stopping the rest of the JS from running. You'd be better off doing some thing like this:
if(load_source('js/myFile.js'))
{
sum(4, 3);
mul(5, 5);
}
Then removing your throw in your load_source() function and using return success;, like so:
var load_source = function (path) {
/* Variable used to determine whether the request was successful */
var success = false;
$.ajax(
{
url: path,
async: false,
dataType: 'script',
method: 'GET',
success: function(){
success = true;
},
error: function (xhr, status, error) {
console.log(error.stack ? error.stack : error);
}
}
);
return success;
}

Pass message from Controller to AJAX script in View

I'm using jQuery and AJAX in the View to send some data to the Controller that writes it to the database. On success I show a div tag with a green background with "OK" text. But what if I do a check first in the Controller if the data already exist in the database, then I would like to alert the user that the data could not be added. Is there a way to pass some kind of message back to the AJAX script?
I guess the success option is just a confirm of contact with the Controller and not a real confirm that everything is OK and the data has been added to the database!?
What action in the Controller would cause the error function in the AJAX code to run?
Finally I just wonder what kind of return I should use since I'm actually not returning anything?
My script in the View:
$.ajax({
url: "/Orders/AddOrder",
type: "GET",
cache: false,
data: { a: order, b: seller },
success: function () {
console.log('AJAX successful');
// Show confirm message
$(".messageOk").show();
$(".messageOk").text("OK").delay(2000).queue(function () {
location.reload();
});
},
error: function () {
????
},
complete: function () {
????
}
});
Controller:
// Add new Resource
public ActionResult AddOrder(int a, int b)
{
var order = new Order
{
OrderNumber = a,
Seller = b
};
db.Orders.Add(order);
db.SaveChanges();
//return new EmptyResult();
return RedirectToAction("Index", "Home"); // ??????
}
You could return the appropriate HTTP status code from your controller action: 409 Conflict.
if (the resource already exists in db) {
return new HttpStatusCodeResult(HttpStatusCode.Conflict);
}
which will trigger the error AJAX function in which you could check whether you are in this situation and act accordingly:
error: function(jqXHR) {
if (jqXHR.status == 409) {
alert('Sorry but this resource already exists');
}
}
As you can see this way it's up to the view to decide what error messages to display based on proper HTTP status codes returned from the server. This way you are not cluttering the server with view logic.
Along with the correct response status code, you can also pass in your response body error messages from the server may be as JSON string or plain string

Prototype validation not working correctly

I use Prototype.js to validate a form. For one of the fields, I have the prototype script ajax a request to a file. The file is a simple PHP file and will return '1' if the value is OK and '0' if the value is not OK. I have the script as below, which should work perfectly. The prototype validation is supposed to show a validation error message when a field does not pass validation, and not display / remove the message once the field passes validation. But in this case, even when the ajax file returns '1', the validation will display the error message anyway. Anyone able to help would be greatly appreciated!
['validate-number3', numessage3, function(v) {
new Ajax.Request('test.php?nr='+v, {
method:'get',
onSuccess: function(transport) {
var response = transport.responseText;
if(response == '1'){return true;}else{return false};
}
});
}],
the return value from Ajax.Request is the Ajax.Request object and returns as soon as the request is setup - the onsuccess callback is called after the request has been completed - so checking the results of Ajax.Request is not useful for what you want to accomplish.
The reason that this doesn't work as you expect, this is an asynchronous call which means it will start the call and then return control to the script while it is processing and then run the callbacks when it is completed.
Try it this way
new Ajax.Request('test.php?nr='+v, {
method:'get',
onSuccess: handleResponse
});
function handleResponse( transport ){
var response = transport.responseText;
if(response == '1'){
//everything is OK
}else{
//value is not OK
};
}
I was able to solve my question!
Thanks to this teriffic page: http://inchoo.net/ecommerce/magento/magento-frontend/magento-form-field-ajax-validation/ it was no problem. This is what I ended up with:
var ok = false;
new Ajax.Request('test.php?nr='+v, {
method:'get',
asynchronous: false,
onSuccess: function(transport) {
var response = transport.responseText;
if(response == '1'){ok = true;}else{ok = false;};
},
onComplete: function() {
if ($('advice-validate-number-pay_bank_no')) {
$('advice-validate-number-pay_bank_no').remove();
}
}
});
return ok;

Problem with jQuery Calls in a Javascript Class with Callbacks

I'm using JavaScript, jQuery, and JSONP to make asynchronous, cross-domain WCF service calls. I've gotten this functionality successfully working, so I know that the problem I'm experiencing is not on the service side.
I had my test client site set up to make inline jQuery calls using the getJSON method, and it was working fine. However, I then tried to take the jQuery calls and put them into a JavaScript class. Now I'm having trouble getting callbacks to fire.
This works fine (the functions in the working example are added in script tags on the page itself):
function handleResponse(result) {
if (result.Success) {
// do something
}
else {
// do something else
}
}
function validate(serviceURL, data) {
$.getJSON(serviceURL + "/Validate?data=" + data + "&callbackHandler=?", handleResponse);
}
When I attempted to create a class to wrap this functionality in a separate .js include file, the callbacks don't fire. Here is the class code from the .js include file:
function serviceProxy(myServiceURL) {
this.serviceURL = myServiceURL;
this.validate = function(data, successCallback, failureCallback) {
$.getJSON(this.serviceURL + "/Validate?data=" + data + "&callbackHandler=?", function(result) {
if (result.Success) {
successCallback();
}
else {
failureCallback(result.ErrorMessage);
}
});
};
And here is the JavaScript that's written in script tags directly on the page to make the calls:
function handleSuccess() {
// do something
}
function handleFailure(message) {
// do something else
}
function validate(serviceURL, data) {
var proxy = new serviceProxy(serviceURL);
proxy.validate(data, handleSuccess, handleFailure);
}
When debugging, the getJSON call is executed, but the handleSuccess and handleFailure callbacks are never reached. Any advice would be greatly appreciated.
Thanks in advance,
Ben
Have you tried replacing:
if (result.Success) {
successCallback();
}
with:
if (result.Success) {
successCallback(result);
}

Categories