0

I am trying to send data via AJAX to MVC Controller method. I am trying to make booking system app. I want to check that user input exists in Entity Model. Ajax is pushing parameters to method controller but i don't get response.

Here is my AJAX call in 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 method in controller:

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 want to send string inputs and get back data to show message that is possible to book that room. Where did I mistake?

Wiktor
  • 7
  • 3
  • What seems to be the error? I.e.: what's not working? How does it behave and how do you want it to behave? – Stefan Sep 21 '20 at 06:00
  • 1
    Here's [a shot in the dark](https://dictionary.cambridge.org/dictionary/english/a-shot-in-the-dark): You probably forgot to put a [`HttpPost`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.httppostattribute?view=aspnetcore-3.1) attribute, meaning your C# endpoint doesn't accept `Post` requests – MindSwipe Sep 21 '20 at 06:04
  • @Stefan I did breakpoint at AJAX Call and seems like "onchange" doesn't work, i tried to call AJAX method on button and the same effect. It should check possibility. When user change the input 'starttime' the function is called and controller checking if this date is possible to book and return true/false. Depends on responde i want to show user message if its possible or not. I did the same method via HTML Post and it works, but i don't want to reload view. – Wiktor Sep 21 '20 at 06:11
  • @MindSwipe I put ```HttpPost``` attribute, i think the problem is with calling method. – Wiktor Sep 21 '20 at 06:21
  • Is `function checkvalidate(startdate, starttime){` being called? If so, check the debugger console (F12) of your browser to see the result of the `ajax` call. – Stefan Sep 21 '20 at 06:24
  • 1
    Then, is the controller named correctly? Default routing for ASP.NET would lead me to believe that your `CheckValidate` method is inside the `HomeController` and that you have no `/API` prefix for API routes, is that correct? – MindSwipe Sep 21 '20 at 06:24
  • @MindSwipe Sure. The method is inside the default ```HomeController``` and i don't have ```/API``` prefix. – Wiktor Sep 21 '20 at 06:30
  • 2
    @Stefan i caught the bug. ```"Uncaught TypeError: startdate.val is not a function"``` – Wiktor Sep 21 '20 at 06:34
  • Okay, you should fix that first. – Stefan Sep 21 '20 at 06:35
  • @Stefan i get value by ```.value``` but now is another one bug ```Uncaught TypeError: (s.dataType || "*").toLowerCase is not a function``` – Wiktor Sep 21 '20 at 06:48
  • I edited my post with code, now the problem is to post parameters to method in controller. – Wiktor Sep 21 '20 at 06:55
  • So, you're hitting the controller but the parameters are empty? – Stefan Sep 21 '20 at 07:49
  • @Stefan ye, now i got parameters but don't have response – Wiktor Sep 21 '20 at 07:51

2 Answers2

0

There are a few things missing from your ajax call. You need to specify data you're sending in such way so that it is sent as JSON and properly. To do that you need to stringify your javascript json object and declare that you're sending a JSON data type. Here is your click event handler code with changes:

$(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";
          }
       }
    })
 });

You can read more about it here: jquery ajax documentation

There are also other existing question here that already answer your question such as this one.

Marko
  • 12,543
  • 10
  • 48
  • 58
  • I updated my post. My ajax function is sending parameters to controller, but i did't get response, because console doesn't log response. – Wiktor Sep 21 '20 at 07:55
0

You can do like this.

var obj = {};
    obj.startdate = document.getElementById('startdate');
    obj.starttime = document.getElementById('starttime');
    
        $.ajax({
            type: "POST",
            url: "/Home/CheckValidate",
            data: JSON.stringify(obj),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                //failure  message
            }
        });
        function OnSuccess(response) {
            //do your stuff after success response
        }
    
Nischal Tyagi
  • 199
  • 1
  • 10