Obtain information from an ajax request

I am working on a website where I need to implement a button that checks if the user has specific permissions before opening a new web page in a popup window. In my JavaScript code, I have the following function:

function sendAjax(methodName, dataArray, success, error, category) {
    var error2 = error || function () { };
    $.ajax({
        type: 'POST',
        url: '/PermissionChecker' + methodName,
        data: JSON.stringify(dataArray),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (r, s, x) { 
            if (!success || success(r, s, x) != false) {
                if (typeof (window.ChangeLogAdd) == 'function') { 
                    ChangeLogAdd(category); 
                } 
            }
        },
        error: error2
    });
}

function CheckPermissions() {
    sendAjax("CheckPermission", null, function (data) { 
        var permission = eval('(' + data + ')'); 
        if (permission == true) { 
            alert('yay'); 
        } else { 
            alert('nay'); 
        } 
    }, null, 'Check Permission');
}

On the C# side, there is a simple function that performs a check and returns a boolean value. The function call works correctly, but when it returns the boolean value, I encounter a JavaScript error stating "Expected ']'." This seems to be related to the success function in my code:

    function (data) { 
        var permission = eval('(' + data + ')'); 
        if (permission == true) { 
            alert('yay'); 
        } else { 
            alert('nay'); 
        } 
    }

I did not face this error before implementing the mentioned block of code, which makes me wonder about the correct way to retrieve the data from the AJAX call and pass it for the permission == true conditional check.

Answer №1

Avoid using eval in this scenario as it poses a security risk and can lead to numerous errors. Instead, have the server return JSON data and utilize $.getJSON method for safer handling.

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

Connect a responsive div to a main div

I'm relatively new to the world of Javascript, CSS, and HTML. Currently, I'm attempting to anchor a div to the center and bottom of its parent div. The parent div contains a responsive background image and my fa fa-arrow icon is correctly positi ...

Converting a collection of model objects into an array

Currently, I am in the process of transitioning from PHP to C# and dotnet core for my web applications. Despite my efforts to learn, I have encountered a specific issue that I cannot seem to solve. Although I am able to fetch a table from an SQL database ...

What is the best way to alter something based on the current date?

My goal is to dynamically change a message based on how close a specific date is. The objective is to update an element of a webpage to display "Renewal Unnecessary" when the date is more than 3 months away, "Renewal upcoming" when the date is less than 3 ...

Creating a regular expression variable in Mongoose: A step-by-step guide

I am looking for a solution to incorporate a variable pattern in mongoose: router.get('/search/:name', async(req, res) => { name = req.params.name; const products = await Product.find({ name: /.*name*/i }).limit(10); res.send(prod ...

What is the correct way to execute a jQuery trigger on a checkbox or radio button to simulate a user clicking on it?

My current page utilizes can.js, making it challenging to replicate the issue on jsfiddle.net. The result I am experiencing is as follows: When I click on a checkbox (or even a radio button), an input text box should update accordingly (for example, displ ...

Displaying interactive charts in a pop-up window using Highcharts within a Bootstrap

I am looking to display a highchart inside a popover. Check out my code in this jsfiddle http://jsfiddle.net/hfiddle/abpvnys5/47/. Here is the HTML: <ul class="stat_list" style="float: left;"> <a data-toggle="popover" data-trigger="hover ...

Creating a promise in an AngularJS factory function to perform an operation

When working within an Angular factory, I am tasked with creating a function that must return a promise. Once the promise is returned, additional functionality will be added. SPApp.factory('processing', ['$http', '$rootScope&a ...

The AJAX request is not functioning properly, even on a basic form like this one

Here is the current code I am testing. Due to some issues with AJAX calls, I am unable to make it work. Can someone please help me identify what might be wrong? test.php <html> <body> <form id="myform"> <input type="text" id="fname" ...

Displaying an array of JSON objects in ReactJS by parsing them

Recently, I've encountered an odd issue with my React App. I am attempting to parse a JSON object that includes arrays of data. The structure of the data looks something like this: {"Place":"San Francisco","Country":"USA", "Author":{"Name":"xyz", "Ti ...

We are creating a table in JavaScript and mistakenly adding an unnecessary tbody

I am currently utilizing a combination of plain JavaScript and Jquery in order to dynamically generate a table. The issue arises when I attempt to use a for loop to iterate through the data obtained from an Ajax request, as it fails to create new rows. To ...

Trigger functions when the window is scrolled, resized, or when the document is fully loaded

I have a few functions that need to be executed under specific conditions: window.scroll window.resize document.ready For example: <script> function myFunction1(data){ /*code*/ } function myFunction2(data){ /*code*/ } ...

Avoid the expansion of line decorations in Monaco editor

I am looking to create a Monaco editor line decoration that remains contained within its original position when I press enter after the decoration. For instance, in a React environment, if I set up a Monaco editor and add a line decoration using the code ...

AngularJS: Modifying directive according to service value update

In my current application, I have a basic sidebar that displays a list of names fetched from a JSON call to the server. When a user clicks on a name in the sidebar, it updates the 'nameService' with the selected name. Once the 'nameService& ...

What does {``} denote in react-native programming?

During my participation in a collaborative project, I noticed that there is a significant amount of {' '} being used. For instance: <Text> {' '} {constant.Messages.PointText.hey} {this._user.first_name || this._user ...

React is unable to identify the `activeStyle` property on a DOM element

Is there anyone who can help with this error message? The warning states: React does not recognize the activeStyle prop on a DOM element. If you want it to be a custom attribute in the DOM, use activestyle in lowercase instead. If it was accidentally pas ...

Is it appropriate to delete the comma in the Ghost Handlebars Template?

While navigating through the tags, I unexpectedly encountered a comma. This could potentially have an unwanted impact. I attempted to remove the comma, but is there a specific method to eliminate it completely? I referred to the Ghost blog Document for gui ...

When located at the bottom of a page, the Div element fails to display

I need some help with my javascript code. I am working on creating a scrollable panel that closes when scrolled and reveals a #toTop div when the bottom of the page is reached. Below is the function code I have written, but for some reason, the #toTop div ...

What purpose does the additional symbol "$()" serve in the selector "$($())"?

Currently, I am looking to incorporate a jQuery scrollspy feature into one of my ongoing projects. Upon coming across this jsfiddle (https://jsfiddle.net/mekwall/up4nu/), I successfully integrated it into my project. However, I have hit a roadblock while ...

Tips for asynchronously modifying data array elements by adding and slicing

I am facing an issue in my vuejs application where I need to modify an array of items after the app has finished loading. My current setup looks like this: var n = 100; var myData = []; function loadMovies(n){ // async ajax requests // add items to ...

Methods for removing and iterating through images?

I successfully programmed the image to move from right to left, but now I want to add a function where the image is deleted once it reaches x: 50 and redrawn on the left. I attempted to use control statements like "if," but unfortunately it did not work a ...