The Ajax function is not defined and results in a runtime error being thrown

    customAjax.postJson(
                "/foo/GetFoo",
                { fooName: fooName },
                function (data) {

                },
                function (error) {  });
        };

My Rest api call is GetAsync()

It throws customAjax 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 customAjax = {

    defaultAjaxTimeout: 600000,
    exceptionStart: '<!--',
    exceptionEnd: '-->',

    postJson: function (url, data, success, error) {
        $.ajax(
            {
                type: "POST",
                dateType: "json",
                url: url,
                data: data,
                timeout: customAjax.defaultAjaxTimeout,
                success: function (result) {
                    if (success) success(result);
                },
                error: function (jqXhr, textStatus, errorThrown) {
                    if (error && jqXhr) {
                        var responseText = jqXhr.responseText;
                        var index = responseText.indexOf(customAjax.exceptionStart);
                        if (index > 0) {
                            var exception = responseText.substr(index + customAjax.exceptionStart.length + 1);
                            index = exception.lastIndexOf(customAjax.exceptionEnd);
                            if (index > 0) {
                                exception = exception.substr(0, index);
                            }
                            error(exception);
                        } else {
                            error(errorThrown);
                        }
                    }
                }
            });
    },
}

Answer №1

The issue that you are encountering is related to accessing the variable ajax from a closure before it has been created:

var myVariable = {
    myProperty: "Hello",
    myFunction: function () {
        //... access myVariable.myProperty -> error
    }
};

There are two possible solutions in this scenario. The more organized approach, which I personally prefer, involves:

var ajaxOptions = {
    defaultAjaxTimeout: 600000,
    exceptionStart: '<!--',
    exceptionEnd: '-->'
};
var ajax = {
    postJson: function (url, data, success, error) {
        ... ajaxOptions.exceptionStart.length
    }
};

This solution works because ajaxOptions already exists in the scope where you define the function ajax.postJson, allowing for proper referencing within its closure.

An alternative to this option is:

var ajax = {
    defaultAjaxTimeout: 600000,
    exceptionStart: '<!--',
    exceptionEnd: '-->'
};
ajax.postJson = function (url, data, success, error) {
    ... ajax.exceptionStart.length
};

This alternative functions because ajax is declared beforehand and then linked to the closure of the function.

A less tidy option is to place the ajax variable under the window object:

window.ajax = {

    defaultAjaxTimeout: 600000,
    exceptionStart: '<!--',
    exceptionEnd: '-->',

    postJson: function (url, data, success, error) {
        ... window.ajax.exceptionStart.length
    }
};

This method operates effectively as window is consistently present in all lexical scopes, permitting seamless referencing. However, it is considered less ideal due to polluting the window object, enabling any JavaScript code on your page to access and modify it, leading to potential unpredictable behavior. Although presented as an example, I do not recommend this practice.

Answer №2

I encountered a similar issue, and after trying various steps, I found a solution using IE11.

  1. Go to the internet settings and select 'Compatibility View settings'.
  2. In the 'Add this website' section, enter the server name for your website (e.g., localhost) and click the 'Add' button.
  3. Make sure to check the 'Display intranet sites in Compatibility View' box.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The internal style and script specified within the <head> section are not being rendered

Within my Joomla website using the T3 template, I inserted the following "Custom Code" just before the closing </head> tag: <style type="text/stylesheet"> div.t3-sidebar.t3-sidebar-right{ background: #F8F8F8 none repeat scroll 0% 0%; ...

It is not possible to utilize a JavaScript function once the script has been loaded through

I am attempting to programmatically load a local JavaScript file - PapaParse library, and then utilize one of its functions: $.getScript("./Content/Scripts/papaparse.js", function () { console.log("Papaparse loaded successfully"); Papa.parse(file, ...

What is the best way to incorporate global variables within Vue JS components?

I am currently working on creating a web-app using Vue JS. I have come across the concept of Single File components(.vue files) which seems like a great way to create components. However, I am looking to avoid using any node modules. That's when I dis ...

Pressing a button triggers the highlighting of a tab in HTML through the use of Javascript

In the corner of my webpage, I have three tabs: info, question, order. When I click on one tab header, only that tab should highlight. The info section includes two buttons that link to the question and order tabs. When these buttons are pressed, the respe ...

Developing a two-dimensional JavaScript array using an AJAX PHP request

I've been working with a MySQL table that stores image data. My goal is to extract this image data and store it in a JavaScript array. The fields I need for the array are "image_ref" and "image_name." To achieve this, I understand that I'll nee ...

Insert a JSX element into the body of a webpage using React JSX

Is there a way to dynamically add elements to the end of the body using vanilla JavaScript? const newRecipe = <div id = "container"> <div className="recipe App" id="four" onClick={this.toggleRecipeList.bind(this)}>{this.state.recipeName} < ...

Issue with an Angular filter for formatting a lengthy JSON string onto separate lines within an HTML document

Just starting out with coding and working in Angular, I'm trying to display JSON data from Firebase in HTML. Here's the specific call I'm using: <p>{{workout[0].box.info.training.strength.exercise[1].movement.freetext }}</p> Th ...

Convert Ruby array into a hash using specific parameters

Here is an array I have: fruits = ["apple", "banana", "orange"] My goal is to convert it into a JSON format like this: '{"apple": {}, "banana": {}, "orange": {} }' I specifically want to avoid this format: '{"apple"=> {}, "banana"=& ...

Sending data through AJAX

I am currently working on a calendar project. I want to include a description box next to the calendar, where additional information about an event will be displayed when a user clicks on a specific date. Here is what I have so far in terms of HTML/PHP: ...

Error: Unable to convert object to TestAcceptanceCriteria due to unexpected format being passed as an array

Consider the JSON file provided below: [ {"name":"test_12345_54321", "acceptanceCriteria": [ { "given":"I am a developer", "and":"I have some test case ...

Improving JavaScript Functions: Minimize duplication of helper methods

I have a set of helper functions that check for the presence of specific strings in an array and certain steps before triggering other functions. The reason for keeping them separated is because arrTours must be associated with only those arrSteps. // Help ...

Performing real-time arithmetic calculations on dynamic text input fields using AngularJS

In the process of creating a dynamic form, the number of textboxes is determined by the situation at hand. Each textbox is assigned an arithmetic formula, which is obtained from a database table. The structure of my form will be as follows: <div ng-ap ...

ng-bind-html is functional, yet it is raising a TypeError

Below is the code snippet containing the ng-bind-html: <span ng-bind-html="text"></span> Here is the stack trace: angular.js:13236 TypeError: bindings.push is not a function at Function.$$addBindingInfo (http://localhost:9000/bower_component ...

At what point should I expect a promise in Protractor to be resolved?

Despite there being similar inquiries on this topic, I am struggling to comprehend them. Allow me to illustrate with an example, where my task is to click a button and verify the URL. Initially, I thought it should be coded as: element(by.id('butto ...

What is the best way to combine these two arrays in order to generate the desired JSON structure in a React

Is there a way to transform two arrays like these: const age = [31,53,62] const names = ['john', 'sam', 'kathy'] Into the structure shown below: const data = { "children": [ { "id": 1, "name": "john", "age ...

Passing a Scope to ES6 Template Literals: How to Ensure they are Interpreted Correctly?

I've recently started utilizing template literals to create an error generator. Although I have functional code, I find myself having to define the list of potential errors within the constructor scope, and this is not ideal for me. Is there a way t ...

What is the method for determining the numerical worth of the px containers?

https://i.stack.imgur.com/0K2TD.png Total width of the bar is set to 500px, with the red box at a width of 150px, the yellow box at 200px, and the green box at 50px. CSS Styles: .box { float:left; width:150px; box-shadow:3px 3p ...

Repeating the execution of Asp.net MVC ajax once again

When using the Ajax.BeginForm method for form submission, I encounter an issue where multiple processes are initiated if the submit button is clicked quickly more than once. This results in the RefreshPosts(); script resetting the form elements. In the co ...

Encountering an unforeseen change in the "buttonText" attribute

I've developed a simple Vue.js component for a button. When the button is clicked, it should display the text "I have been clicked." It does work as expected, but I'm also encountering an error that reads: 49:7 error Unexpected mutation of "but ...

Utilizing libraries in JavaScript

For a while now, I've been grappling with an issue related to importing modules into my main JavaScript script. I recently installed the lodash library via npm and I'm trying to import it into my main script so that I can utilize its functionali ...