Transferring text data to MVC Controller using AJAX

I am currently working on an AJAX feature that sends data to an MVC Controller method for a booking system app. I am trying to verify user input against an Entity Model. Although the parameters are being passed to the controller method through Ajax, I am not receiving any response.

Below is the AJAX call in the View:

   var check = document.getElementById('check');
        //starttime.onchange = checkvalidate(startdate, starttime);
        $(check).click(function (datevalue, timevalue) {
            var startdate = document.getElementById('startdate');
            var starttime = document.getElementById('starttime');
            var log = document.getElementById('log');
            var datevalue = startdate.value;
            var timevalue = starttime.value;
            $.ajax({
                type: "POST",
                url: "/Home/CheckValidate",
                data: { 'start': datevalue, 'time': timevalue },
                dataType: "Boolean",
                success: function (response) {
                    console.log = response;
                    if (response == true) {
                        log.value = "YES";
                    } else
                    {
                        log.value = "NO";
                    }
                }
            })
        })

And here is the controller method:

public bool CheckValidate(string start, string time)
        {
            string datastart =  start + " " + time;
            DateTime startDate = Convert.ToDateTime(datastart);
            EventsEntities dc = new EventsEntities();
            var MatchedElements = dc.Events.Where(x => x.start <= startDate && startDate < x.end).FirstOrDefault();
            if (MatchedElements == null)
            {
                return true;
            } else
            {
                return false;
            }

        }

I am attempting to send string inputs and receive data in order to display a message indicating whether it is possible to book a room. Can you help me identify where I may have made a mistake?

Answer №1

In order to achieve this, follow these steps.

let newObj = {};
    newObj.startDate = document.getElementById('startDate');
    newObj.startTime = document.getElementById('startTime');
    
        $.ajax({
            type: "POST",
            url: "/Home/CheckValidity",
            data: JSON.stringify(newObj),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: handleSuccess,
            failure: function (response) {
                //display error message
            }
        });
        function handleSuccess(response) {
            //perform actions after successful response
        }
    

Answer №2

Your ajax call is missing some important details. It's essential to format the data you're sending as JSON and ensure it is sent correctly. To achieve this, you should stringify your JavaScript JSON object and specify that you are sending JSON data. Below is your click event handler code with necessary modifications:

$(check).click(function () {
    var data = {
        start: datevalue,
        time: timevalue
    };
    $.ajax({
        type: "POST",
        url: "/Home/CheckValidate",
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        dataType: "boolean",
        success: function (response) {
            if (response) {
                log.val = "YES";
            } else {
                log.val = "NO";
            }
        }
    })
});

For further information, refer to jquery ajax documentation

You may also find solutions to similar queries in posts like this one.

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

"Transmitting a message with socket.io upon establishing connection

Currently getting the hang of socket.io and giving it a try. I have a straightforward app where clicking the display button shows an image on the screen in real time. I have a couple of questions. Firstly, my main concern is regarding the synchronization ...

Passing values from child components to parent components in React Native for display

Within my application, I have a child component and a parent component. The purpose of the child component is to handle star ratings. I am now looking to pass the rating value from the child component to the parent component and utilize this data within th ...

Using the shift() method in Javascript to manipulate Objects

My goal is to take my list and combine the first two items (0 & 1) together. I attempted the following code: total=foo.shift(); foo[0]=total However, I encountered this error: Uncaught TypeError: Object [object Array] has no method &ap ...

The `$refs` variable in Vue can be used to reference a specific Vue component within a class-st

Would it be possible to access this.$refs.label? I am using the package vue-property-decorator. Below is the content of the component: <template> <div> <label ref="label">asd</label> </div> </template> <scr ...

Finding the file in a separate directory within the src path

In my projects directory, I have a folder named projects which contains both a game folder and an engine folder. Inside the engine folder, there is an engine.js file. My issue is that I want to access this engine.js file from my game.html file located in a ...

What is the best way to populate empty dates within an array of objects using TypeScript or JavaScript?

I am trying to populate this object with dates from today until the next 7 days. Below is my initial object: let obj = { "sessions": [{ "date": "15-05-2021" }, { "date": "16-05-2021" }, { "date": "18-05-2021" }] } The desired ...

Unauthorized Access with Ajax jQuery

While working on an ajax request using Jquery, I encountered a dilemma. Even though the page is only accessible to logged in users, my cookies are not being sent along with the request. This results in a 401 error. I am already logged in, so why aren' ...

Identifying fluctuations in unprocessed data

Currently in the process of developing a web application that serves as a dashboard for monitoring storage tank levels. It gathers data from various sensors inside tanks and saves this information in a database. The tool is created using express / node.js. ...

Unable to extract data from my xml reply

I've been trying to extract a value from an XML response, but I keep getting null. What am I missing? $.ajax({ method: "GET", url: "fphub01-prd.tc.workstreaminc.com/hub/custLookup/", data: { emailAddress: email } }).done(function(msg) { ...

Issue with Vue and Firebase: New users are being created successfully, but are being logged into existing user accounts

I've encountered a strange issue in Firebase. When I create a new user with the same password as an existing user, the new user is logged in under the previous user's account and displays all their information. However, upon logging out and signi ...

Securing a WebSocket Server with Node.js: Step-by-Step Guide

My WebSocket server, running on node.js, is functional for ws:// but not for wss:// This server is operating on my Raspberry Pi B 3+. After changing ws:// to wss:// in the JavaScript file, it stopped functioning. The node.js server: const WebSocket = re ...

Troubleshooting the Ineffective Replace Method in React Component

When working in my React component, I have implemented the use of the replace method to substitute a word. However, it seems that this functionality is not generating the expected outcome: const myComponent = () => { const [textVal, setTextVal] = ...

Rearranging anchor tag order with the power of JQuery

Imagine I have five anchor tags <a id = "A" class = "Home">Home</a> <a id = "B" class = "Maps">Maps</a> <a id = "C" class = "Plans">Plans</a> <a id = "D" class = "Community">Community</a> <a id = "E" clas ...

Tips for inserting text to the left rather than the right using Jquery

I recently came across this code snippet shared by some helpful users on stackoverflow and it has been working perfectly for me. However, I do have a couple of queries regarding its functionality. Firstly, how can I ensure that the current selected option ...

What is the correct way to assign a property to a function's scope?

Lately, I've been delving into Typescript Decorators to address a specific issue in my application. Using a JS bridge to communicate TS code between Android and iOS, we currently define functions as follows: index.js import foo from './bar' ...

Obtain the index of the selected item from a dropdown menu

Is there a way for the selectedIndex to return -1 if no item is selected, instead of the element's text at position 0? It seems that the selectedIndex always returns 0 even when nothing is selected. <select id="abc" name="abc"> <option& ...

Slider Volume with jQuery

Struggling to find a solution for this issue. Seeking some assistance. My goal is to create a basic volume slider. So, the orange section represents my volume slider. This is the jQuery code I am using: var mouseIsDown = false; $("#volSlider").on("mou ...

Using the AJAX post method to generate a JSON object from database results and send it back to a jQuery UI Dialog

I wrote a script that loads sample images from the database based on the relevant category when the page loads. Here's a simplified version of the PHP script: <?php $category = 'granite'; $samples = 'SELECT * FROM material WHERE ma ...

In order to select a checkbox within an alert popup using Selenium C# without an xpath, you may encounter the issue of disabled right-click for inspection

Is there a way to select a checkbox within an alert popup using Selenium C# when the checkbox does not have a specified xpath? It seems that inspection is disabled, preventing right-clicking. https://i.stack.imgur.com/HoCiK.png ...

Identify the current slide or div within a jQuery slideshow

I am currently facing an issue with my slide show that is composed of divs, each containing a picture and some html controls. The problem arises when clicking on a control in a slide other than the first one - it only updates the first slide. The only thin ...