Ajax is undefined and throws runtime exception - javascript

ajax.postJson(
"/foo/GetFoo",
{ fooName: fooName },
function (data) {
},
function (error) { });
};
My Rest api call is GetAsync()
It throws ajax is undefined : JavaScript runtime error: Unable to get property 'exceptionStart' of undefined or null reference. The custom code to make ajax call is below. The api call Getfoo is GetAsync method using attribute HttpGet. Can someone point me to the cause of this failure
var ajax = {
defaultAjaxTimeout: 600000,
exceptionStart: '<!--',
exceptionEnd: '-->',
postJson: function (url, data, success, error) {
$.ajax(
{
type: "POST",
dateType: "json",
url: url,
data: data,
timeout: ajax.defaultAjaxTimeout,
success: function (result) {
if (success) success(result);
},
error: function (jqXhr, textStatus, errorThrown) {
if (error && jqXhr) {
var responseText = jqXhr.responseText;
var index = responseText.indexOf(ajax.exceptionStart);
if (index > 0) {
var exception = responseText.substr(index + ajax.exceptionStart.length + 1);
index = exception.lastIndexOf(ajax.exceptionEnd);
if (index > 0) {
exception = exception.substr(0, index);
}
error(exception);
} else {
error(errorThrown);
}
}
}
});
},
}

The issue you're having here is that you're attempting to access the variable ajax from a closure before it's created:
var myVariable = {
myProperty: "Hello",
myFunction: function () {
//... access myVariable.myProperty -> error
}
};
There are two options here. The cleaner one, and the one I'd use is this:
var ajaxOptions = {
defaultAjaxTimeout: 600000,
exceptionStart: '<!--',
exceptionEnd: '-->'
};
var ajax = {
postJson: function (url, data, success, error) {
... ajaxOptions.exceptionStart.length
}
};
The reason this works is because ajaxOptions exists already in the scope where you declare the function ajax.postJson so it's able to reference it correctly from its closure.
The variation on this option is this:
var ajax = {
defaultAjaxTimeout: 600000,
exceptionStart: '<!--',
exceptionEnd: '-->'
};
ajax.postJson = function (url, data, success, error) {
... ajax.exceptionStart.length
};
The reason this works is because ajax is already declared, and is just attached to the closure of the function.
A second, less-clean option is to put the ajax variable as a child of the window object:
window.ajax = {
defaultAjaxTimeout: 600000,
exceptionStart: '<!--',
exceptionEnd: '-->',
postJson: function (url, data, success, error) {
... window.ajax.exceptionStart.length
}
};
The reason this works is because window always exists in all lexical scopes, so it'll have no problem referencing it. The reason it's less clean is because it pollutes the window object and any JavaScript anywhere on your page can access and change it, potentially causing unknown behavior. I'm not recommending it, I'm just providing it as an example.

The following steps helped me resolve similar problem, I used IE11
the solution to it in IE 11 can be:
under internet settings select 'Compatibility View settings',
in 'Add this website' enter server name for your website (for example: localhost ), click 'Add' btn.
Tick 'Display intranet steps in Compatibility View' box.

Related

TypeError: this.abc is not a function | javascript

Not a fronted or JavaScript so not able to understand why it's not able to find the defined function in the file. I am integrating Apple Pay and I am trying to call the back-end API based on certain event. Here is my code.
ACC.payDirect = {
_autoload: ['payDirect'],
session: null,
payDirect: function () {
let button = $('#mbutton');
if (button.length === 0) {
return;
}
$('#mbutton').on('click', this.onButtonClicked.bind());
},
onButtonClicked: function () {
if (!Session) {
return;
}
var request = getCartPaymentRequest();
this.requestSession("1234"); //getting error while calling this function
session.begin();
},
requestSession: function (validationURL) {
return new Promise(function (resolve, reject) {
$.ajax({
type: 'POST',
url: ACC.config.encodedContextPath + '/checkout/request_session',
data: JSON.stringify({ validationURL: validationURL }),
dataType: 'json',
contentType: 'application/json',
success: resolve,
error: reject
});
});
},
},
function getCartPaymentRequest() {
var result = "";
$.ajax({
type: 'GET',
url: ACC.config.encodedContextPath + '/checkout/payment-request',
dataType: 'json',
async: false,
success: function (response) {
result = response;
},
});
return result;
}
While calling the requestSession I am getting the following error
TypeError: this.requestSession is not a function. (In 'this.requestSession("1234")', 'this.abc' is undefined)
I am sure doing some basic mistake but not able to find out the root cause as why it's not able to find the second function while the first one seems to be working without any issue.
The problem is with the .bind method you called without any parameters.
Take the following example:
const obj2 = {
b: function (callback) {
callback()
}
};
const obj = {
a: function () {
obj2.b(this.c.bind())
},
c: function () {
console.log(this)
}
};
obj.a()
What will happen here is that the Window object will appear in the console.
This happens because the window is somewhat of the global context, and when running in the browser JavaScript's bind's parameter will default to the only context it can: the window.
What you need to do is call the .bind method using the ACC.payDirect as parameter as it will then bind it to the object and use the proper context, you could use a this but if the methodm was called with a different context would cause problems. An even better solution (provided you can use new ES features) is using arrow functions. They are much, much better to work with and won't give you headaches such as this.

Javascript Ajax Uncaught (in promise) undefined

I'm struggling with an ajax GET using a promise.
If the ajax runs into an error, such as the URL is incorrect, the 'error: function ()' is called and I get an error in the browser debug saying "Uncaught (in promise) undefined"
The first two parts of the ajax function works OK i.e. if the ajax returns a success, then both inner conditions for result.success true/false are working, I just don't know how to resolve the reject call in the ajax error function at the bottom:
var myVariable = "test";
let promise = myFunction(myVariable);
promise.then(function () {
// Do Something
}).catch(function (message) {
console.error(message);
});
function myFunction(myVariable) {
return new Promise(function (resolve, reject) {
$.ajax({
type: "GET", //send it through get method
url: "/myURL/Edit?handler=GetBlahBlah",
data: {
sourceType: myVariable
},
contentType: "json",
dataType: "json",
success: function (result) {
if (result.success == false) {
reject(result.responseText); // This works
} else {
resolve(); // This works
}
},
error: function () {
reject("Error while making Ajax call! Get Trigger"); // NOT WORKING!!
}
});
});
}
Turns out my original question does actually work correctly, I hadn't noticed at first that the calling method to this ajax GET request was coming from two different process in my javascript at different times and i hadn't included a catch block on the process that was actually calling this ajax the first time round.
Apologies if I caused any confusion to anyone, my bad!

How to optimize (minimize) jQuery AJAX calls

I have over 50 AJAX calls from different functions of my code. All these calls have a similar structure with different data/url/callback params:
var jqXHR = $.post('/dba/port.php', {
mode: "del_wallfunds",
pdata: cdata,
wname: wName
},
function (data) {}, "json")
.done(function (data) {
var msg = data.msg;
if (msg.indexOf("Error") == -1) {
alertify.success(msg);
delSelected(selGroup);
} else {
alertify.error(msg);
}
})
.fail(function () {
alertify.error("Error .....");
});
I am thinking how to write a function that would return that var jqXHR to minimize the total size of the code. It is not a problem to pass all static variables like URL, error strings etc. But the problem is that all callback functions on ".done" are different and I don't know how to pass these callback functions as variables.
One way would be to call a single "universal" function on .done and pass a "switch" variable to that function, but it doesn't seem to be an elegant solution.
Any suggestions how to it in some elegant way?
Thanks
Either pass the done callback function as an argument when calling your function:
function ajaxCall(url, data, doneCallback) {
return $.post(url, data, doneCallback, "json").fail(...);
// or
return $.post(url, data, function() {}, "json").done(doneCallback).fail(...);
}
var jqXhr = ajaxCall('yoururl.php', {key: 'value'}, function(data) {
// do something
});
Or return the jqXhr object from the function, and assign the done callback then:
function ajaxCall(url, data) {
return $.post(url, data, function() {}, "json").fail(...);
}
var jqXhr = ajaxCall('yoururl.php', {key: 'value'});
jqXhr.done(function(data) {
// do something
});
Alternatively switch to using jQuery.ajax() instead, and pass the entire options object in:
function ajaxCall(options) {
return $.ajax(options).fail(...);
}
var jqXhr = ajaxCall({
url: 'yoururl.php',
data: {key: 'value'},
dataType: 'json'
});
jqXhr.done(function(data) {
// do something
});
You can try to :
turn "request successfully returned a treatment error" into a "rejected request",
put the "alertify" processing in a common callback
Here is a sketch of what this could give :
function myAjaxApi(url, data){
var myAjaxCall = $.post(url, data, function (data) {}, "json")
.then(function (data) {
// using .then : change "request succesful with error state"
// to "rejected state"
var msg = data.msg;
if (msg !== undefined && msg.indexOf("Error") >= 0) {
var dfd = $.Deferred();
// try to match the same signature as the "error" option
dfd.reject(this, msg);
return dfd;
} else {
return data
}
});
myAjaxCall.done(function(data){
if (data.msg) {
alertify.success(data.msg);
}
}).fail(function (jqxhr, msg) {
if (!msg) { msg = "Error ....."; }
alertify.error(msg);
});
return myAjaxCall;
}
//usage
myAjaxApi('/dba/port.php', {mode: "del_wallfunds", pdata: cdata, wname: wName})
.done(function (data) {
// the ".done()" queue will not be executed if msg contains "Error" ...
delSelected(selGroup);
});
Some parts should be written with more care ; the above example is meant to illustrate how you can wrap your repeated ajax calls inside a common api.

Wait until Ext.Ajax.request responds with success before setting variable

Below you will see some code to set the currently logged in user for an extjs 4 application. If I have the alert uncommented, the code seems to wait until the alert is accepted before the code continues (it seems). That allows enough time for the asynchronous call to complete with a success. If I comment out the alert, the variable "employeeFilter" never gets set because the AJAX call didn't come back in time. In which case, it sets the "employeeFilter" to null instead. How can I fix this so it waits until the AJAX response comes back in success?
var loggedInUserId = null;
Ext.Ajax.request({
url: '/Controls/UserList/UserService.asmx/GetLoggedInUserId',
method: 'POST',
jsonData: { 'x': 'x' },
success: function (response, opt) {
loggedInUserId = Ext.decode(response.responseText).d;
},
failure: function (response) {
}
});
//alert(loggedInUserId);
var employeeFilter = loggedInUserId;
var projectFilter = '-1';
I would have done this.
var employeeFilter;
Ext.Ajax.request({
url: '/Controls/UserList/UserService.asmx/GetLoggedInUserId',
method: 'POST',
jsonData: { 'x': 'x' },
success: function (response, opt) {
employeeFilter = Ext.decode(response.responseText).d;
//Do here whatever you need to do once the employeeFilter is set. probably call a function and pass the employee filter as parameter.
},
failure: function (response) {
}
});
var projectFilter = '-1';

Extending jQuery ajax success globally

I'm trying to create a global handler that gets called before the ajax success callback. I do a lot of ajax calls with my app, and if it is an error I return a specific structure, so I need to something to run before success runs to check the response data to see if it contains an error code bit like 1/0
Sample response
{"code": "0", "message": "your code is broken"}
or
{"code": "1", "data": "return some data"}
I can't find a way to do this in jQuery out of the box, looked at prefilters, ajaxSetup and other available methods, but they don't quite pull it off, the bets I could come up with is hacking the ajax method itself a little bit:
var oFn = $.ajax;
$.ajax = function(options, a, b, c)
{
if(options.success)
{
var oFn2 = options.success;
options.success = function(response)
{
//check the response code and do some processing
ajaxPostProcess(response);
//if no error run the success function otherwise don't bother
if(response.code > 0) oFn2(response);
}
}
oFn(options, a, b, c);
};
I've been using this for a while and it works fine, but was wondering if there is a better way to do it, or something I missed in the jQuery docs.
You can build your own AJAX handler instead of using the default ajax:
var ns = {};
ns.ajax = function(options,callback){
var defaults = { //set the defaults
success: function(data){ //hijack the success handler
if(check(data)){ //checks
callback(data); //if pass, call the callback
}
}
};
$.extend(options,defaults); //merge passed options to defaults
return $.ajax(options); //send request
}
so your call, instead of $.ajax, you now use;
ns.ajax({options},function(data){
//do whatever you want with the success data
});
This solution transparently adds a custom success handler to every $.ajax() call using the duck punching technique
(function() {
var _oldAjax = $.ajax;
$.ajax = function(options) {
$.extend(options, {
success: function() {
// do your stuff
}
});
return _oldAjax(options);
};
})();
Here's a couple suggestions:
var MADE_UP_JSON_RESPONSE = {
code: 1,
message: 'my company still uses IE6'
};
function ajaxHandler(resp) {
if (resp.code == 0) ajaxSuccess(resp);
if (resp.code == 1) ajaxFail(resp);
}
function ajaxSuccess(data) {
console.log(data);
}
function ajaxFail(data) {
alert('fml...' + data.message);
}
$(function() {
//
// setup with ajaxSuccess() and call ajax as usual
//
$(document).ajaxSuccess(function() {
ajaxHandler(MADE_UP_JSON_RESPONSE);
});
$.post('/echo/json/');
// ----------------------------------------------------
// or
// ----------------------------------------------------
//
// declare the handler right in your ajax call
//
$.post('/echo/json/', function() {
ajaxHandler(MADE_UP_JSON_RESPONSE);
});
});​
Working: http://jsfiddle.net/pF5cb/3/
Here is the most basic example:
$.ajaxSetup({
success: function(data){
//default code here
}
});
Feel free to look up the documentation on $.ajaxSetup()
this is your call to ajax method
function getData(newUrl, newData, callBack) {
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: newUrl,
data: newData,
dataType: "json",
ajaxSuccess: function () { alert('ajaxSuccess'); },
success: function (response) {
callBack(true, response);
if (callBack == null || callBack == undefined) {
callBack(false, null);
}
},
error: function () {
callBack(false, null);
}
});
}
and after that callback success or method success
$(document).ajaxStart(function () {
alert('ajax ajaxStart called');
});
$(document).ajaxSuccess(function () {
alert('ajax gvPerson ajaxSuccess called');
});

Categories

Resources