-2

I have this jQuery to respond to a button being clicked and call a REST method:

$(document).ready(function() {
    $("#btnGetData").click(function() {
    alert("The button was clicked.");

    var unitval = _unit; 
    var begdateval = _beginDate;
    var enddateval = _endDate; 

    var model = JSON.stringify({ unit: unitval, begdate: begdateval, enddate: enddateval });
    $.ajax({
        type: 'GET',
        url: '@Url.Action("GetQuadrantData", "LandingPage")',
        data: { unit: unitval, begdate: begdateval, enddate: enddateval},
        contentType: 'application/json',
        cache: false,
        success: function (returneddata) {
        },
        error: function () {
            alert('hey, boo-boo!');
        }
        });

    }); // button click
}); // ready

It is not just that the REST method is not getting called - this handler is apparently not firing at all, as I see no alerts (neither "The button was clicked." nor "hey, boo-boo!").

The script is being added - I can step through it, and the vars (such as "unitval") are being assigned the appropriate values.

So why does clicking the button, which is declared like so:

<button class="btn green smallbutton" id="btnGetData" name="btnGetData">SUBMIT</button>

...do nothing?

This is the script that's being added (from View > Page Source):

<script>$(document).ready(function() {$("#btnGetData").click(function() {alert("The button was clicked.");var unitval 
= ABUELOS;var begdateval = 2016-08-21;var enddateval = 2016-08-27;var model = JSON.stringify({ unit: unitval, begdate: 
begdateval, enddate: enddateval });$.ajax({type: 'GET',url: '@Url.Action("GetQuadrantData", "LandingPage")',data: { 
unit: unitval, begdate: begdateval, enddate: enddateval},contentType: 'application/json',cache: false,success: 
function (returneddata) {},error: function () {alert('hey, boo-boo!');}});});});</script>

This may not be pertinent (yet, anyway), but this is the REST method that I want to call from that button click:

public class LandingPageController : ApiController
. . .
    [Route("{unit}/{begdate}/{enddate}")]
    public HttpResponseMessage GetQuadrantData(string unit, string begdate, string enddate)
    {
        _unit = unit;
        _beginDate = begdate;
        _endDate = enddate;
        string beginningHtml = GetBeginningHTML(); // This could be called from any page to reuse the same "header"
        string top10ItemsPurchasedHtml = GetTop10ItemsPurchasedHTML();
        string pricingExceptionsHtml = GetPricingExceptionsHTML();
        string forecastedSpendHtml = GetForecastedSpendHTML();
        string deliveryPerformanceHtml = GetDeliveryPerformanceHTML();
        string endingHtml = GetEndingHTML();
        String HtmlToDisplay = string.Format("{0}{1}{2}{3}{4}{5}",
            beginningHtml,
            top10ItemsPurchasedHtml,
            pricingExceptionsHtml,
            forecastedSpendHtml,
            deliveryPerformanceHtml,
            endingHtml);

        return new HttpResponseMessage()
        {
            Content = new StringContent(
                HtmlToDisplay,
                Encoding.UTF8,
                "text/html"
            )
        };
    }

UPDATE

This is a error dump from the console:

Failed to find a valid digest in the 'integrity' attribute for resource 'https://code.jquery.com/jquery-1.12.4.min.js' with computed SHA-256 integrity 'ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ='. The resource has been blocked.

Uncaught Error: Bootstrap's JavaScript requires jQuery

Failed to load resource: the server responded with a status of 404 (Not Found)

Uncaught Error: Bootstrap's JavaScript requires jQuery

Uncaught ReferenceError: $ is not defined

Failed to load resource: the server responded with a status of 404 (Not Found)

UPDATE 2

I am adding jQuery; I have this in my "head" section:

<script src='https://code.jquery.com/jquery-1.12.4.min.js' integrity='sha256-lZFHibXzMHo3GGeehn1hudTAP3Sc0uKXBXAzHX1sjtk=' crossorigin='anonymous'></script>
<link href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css' rel='stylesheet' />
<script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js'></script>

UPDATE 3

Incorporating some of the suggestions here, this is my running page source (button still unresponsive):

<html style='margin-top:20;margin-left:60;margin-right:60; -webkit-box-shadow: -1px 0 5px 0 rgba(0, 0, 0, .25);box-shadow: -1px 0 5px 0 rgba(0, 0, 0, .5);padding-left: 1px;padding-right: 1px;padding-bottom: 15px;'><head><title>Available Reports for ABUELOS</title><script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script><link href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css' rel='stylesheet' /><script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js'></script><link href="~/Content/Site.css" rel="stylesheet" /><![endif]--><style>body {padding-top: 20px;padding-bottom: 20px;background-color: white;}hr {border: 0;height: 1px;color: navy;background: #333;margin-left:-4;margin-right:-4;}table {font-family: arial, sans-serif;font-size: 13px;border-collapse: collapse;width: 100%;}td, th {border: 1px solid #dddddd;text-align: left;padding: 8px;}label { white-space: pre; }tr:nth-child(even) {background-color: #dddddd;}.body-content {-webkit-box-shadow: -1px 0 5px 0 #000000;-webkit-box-shadow: -1px 0 5px 0 rgba(0, 0, 0, .25);box-shadow: -1px 0 5px 0 #000000;box-shadow: -1px 0 5px 0 rgba(0, 0, 0, .5);padding-left: 1px;padding-right: 1px;padding-bottom: 15px;}.jumbotronjr {padding: 2px;margin-top: -12px;margin-bottom: -24px;font-size: 21px;font-weight: 200;color: inherit;background-color: white;}.titletext {font-size: 2.1em;color: darkgreen;font-family: Candara, Calibri, Cambria, serif;margin-left: -32px;}.titletextjr {font-size: 1.4em;color: darkgreen;font-family: Candara, Calibri, Cambria, serif;margin-left: -32px;}.cccsfont {font-size: 0.25em !important;font-family: Calibri, Candara, Cambria, serif !important;}.smalldatepicker {font-size: 12px;font-weight: 100;}.smallbutton {font-size: 11px;font-weight: 100;margin-left: 16;}.addltopmargin {margin-top: 8px;}.sectiontext {font-size: 1em;font-weight: bold;font-family: Candara, Calibri, Cambria, serif;color: green;margin-top: -4px;}.bottommarginbreathingroom {margin-bottom: 2px;}.submitbtnmargins  {margin-top: -4px !important;margin-left: 8px !important;margin-bottom: 8px;}.btn.green{background-color: darkgreen;color: white;}.redfont {color: red;}.bold {font-weight: bold;}.rightjustifytext {text-align: right;}.topleft {margin-top: -8px;margin-left: 12px;margin-bottom: 8px;padding: 16px;border:1px solid black;}.topright {margin-top: -8px;margin-right: 12px;margin-bottom: 8px;margin-left: -12px;padding: 16px;border:1px solid black;}.bottomleft {margin-left: 12px;padding: 16px;border:1px solid black;}.bottomright {margin-right: 12px;margin-left: -12px;padding: 16px;border:1px solid black;}.topright, .topleft {height: 408px; }.bottomright, .bottomleft {height: 408px; }.leftmargin12 {margin-left: 12px !important;}</style></head><body><div class="jumbotronjr"><div class="col-md-3" style="margin-top: 0.6cm"><img src="http://www.proactusa.com/wp-content/themes/proact/images/pa_logo_notag.png" height="86" width="133" alt="PRO*ACT usa logo"></div><div class="col-md-9"><label class="titletext" style="margin-top: 0.2cm;">Customer Dashboard</label><br/><label class='titletextjr' style='margin-top: -2.2cm;'>ABUELOS</label><label> for the week of August 21          </label><input class="smalldatepicker" type="date" id="datepicker" name="daterangefrom" value="2016-08-21"></input><label> to </label><input type="date" class="smalldatepicker" id="datepicker" name="daterangeto" value="2016-08-27"></input><button type="button" class="btn green smallbutton" id="btnGetData" name="btnGetData">GO</button></div><div class="row"><div class="col-md-12"><hr /></div></div><div class="row"><div class="col-md-12"></div></div><div class="row"><div class="col-md-6"><div class="topleft"><h2 class="sectiontext">Top 10 Items Purchased</h2><table><tr><th>Item Code</th><th>Description</th><th class="rightjustifytext">Qty</th></tr><tr><td>156100</td><td>ONIONS, YELLOW JUMBO 50#</td><td class="rightjustifytext">362</td></tr><tr><td>226150</td><td>AVOCADOS, ABUELOS-HASS 70CT  23#</td><td class="rightjustifytext">358</td></tr><tr><td>163150</td><td>PEPPERS, ANAHEIM GREEN 20#</td><td class="rightjustifytext">282</td></tr><tr><td>176000</td><td>POTATOES, RED A 50#</td><td class="rightjustifytext">266</td></tr><tr><td>188301</td><td>TOMATOES, ROMA HOT HOUSE 25#</td><td class="rightjustifytext">230</td></tr><tr><td>167150</td><td>PEPPERS, POBLANO 18 - 20#</td><td class="rightjustifytext">202</td></tr><tr><td>189300</td><td>TOMATILLOS, 30# NO HUSK</td><td class="rightjustifytext">168</td></tr><tr><td>170150</td><td>PEPPERS, GRN CH 1&1/9 BU (18-26#)</td><td class="rightjustifytext">163</td></tr><tr><td>122500</td><td>LETTUCE, ICEBERG LINER 24 CT</td><td class="rightjustifytext">133</td></tr><tr><td>127100</td><td>LETTUCE, ROMAINE 24 CT </td><td class="rightjustifytext">129</td></tr></table></div></div><div class="col-md-6"><div class="topright"><h2 class="sectiontext">Pricing Exceptions - Weekly Recap</h2><label class="redfont" style="font-size: 12px">Red denotes Contract Item Overages</label></br><label style="font-size: 12px">For Weyand on the pricing week of - 7/31/2016</label><table><tr><th>PRO*ACT Member</th><th class="rightjustifytext">Total Occurrences of Summary Items</th><th class="rightjustifytext">Total Summary Exceptions</th><th class="rightjustifytext">Total Percentage of Summary Exceptions</th></tr><tr><td style="width:30%">Stern</td><td style="width:23%" class="rightjustifytext">205</td><td style="width:23%" class="rightjustifytext">2</td><td style="width:24%" class="rightjustifytext">99.02%</td></tr><tr><td>Hardies Dallas</td><td class="rightjustifytext">1,597</td><td class="rightjustifytext">0</td><td class="rightjustifytext">100.00%</td></tr><tr><td>Hardies South</td><td class="rightjustifytext">612</td><td class="rightjustifytext">1</td><td class="rightjustifytext">99.84%</td></tr><tr><td>Go Fresh</td><td class="rightjustifytext">482</td><td class="rightjustifytext">0</td><td class="rightjustifytext">100.00%</td></tr><tr><td>Segovias</td><td class="rightjustifytext">1,360</td><td class="rightjustifytext">2</td><td class="rightjustifytext">99.85%</td></tr><tr><td>Potato Spec</td><td class="rightjustifytext">1,605</td><td class="rightjustifytext">0</td><td class="rightjustifytext">100.00%</td></tr><tr><td class="rightjustifytext bold">TOTAL</td><td class="rightjustifytext bold">5,861</td><td class="rightjustifytext bold">5</td><td class="rightjustifytext bold">99.79%</td></tr></table></div></div></div><div class="row"><div class="col-md-6"><div class="bottomleft"><h2 class="sectiontext">Forecasted Spend - $9,814.81</h2><table><tr><th>Item Code</th><th class="rightjustifytext">Last Week's Usage</th><th class="rightjustifytext">This Week's Price</th><th class="rightjustifytext">Forecasted Spend</th></tr><tr><td>261650</td><td class="rightjustifytext">49</td><td class="rightjustifytext">3.14</td><td class="rightjustifytext">153.86</td></tr><tr><td>231083</td><td class="rightjustifytext">52</td><td class="rightjustifytext">1.25</td><td class="rightjustifytext">65.00</td></tr><tr><td>398980</td><td class="rightjustifytext">46</td><td class="rightjustifytext">4.95</td><td class="rightjustifytext">227.70</td></tr><tr><td>351135</td><td class="rightjustifytext">40</td><td class="rightjustifytext">0.75</td><td class="rightjustifytext">30.00</td></tr><tr><td>398036</td><td class="rightjustifytext">42</td><td class="rightjustifytext">3.00</td><td class="rightjustifytext">126.00</td></tr><tr><td>208110</td><td class="rightjustifytext">42</td><td class="rightjustifytext">2.50</td><td class="rightjustifytext">105.00</td></tr><tr><td>102800</td><td class="rightjustifytext">1835</td><td class="rightjustifytext">2.25</td><td class="rightjustifytext">4,128.75</td></tr><tr><td>367050</td><td class="rightjustifytext">1910</td><td class="rightjustifytext">1.95</td><td class="rightjustifytext">3,724.50</td></tr><tr><td>173100</td><td class="rightjustifytext">66</td><td class="rightjustifytext">19.00</td><td class="rightjustifytext">1,254.00</td></tr><tr><td class="bold">TOTAL</td><td class="bold rightjustifytext">4082</td><td class="bold rightjustifytext">--</td><td class="bold rightjustifytext">$9,814.81</td></tr></table></div></div><div class="col-md-6"><div class="bottomright"><h2 class="sectiontext">Delivery Performance</h2><table><tr><th>PRO*ACT Distributor</th><th>Restaurant Location</th><th class="rightjustifytext">Avg Order Amount</th><th class="rightjustifytext">Avg Package Count</th><th class="rightjustifytext">Total Sales</th></tr><tr><td>Sunrise FL</td><td>A1A ALEWORKS - #4405 - ST. AUGUSTINE</td><td class="rightjustifytext">$475.78</td><td class="rightjustifytext">28.50</td><td class="rightjustifytext">$1,903.10</td></tr><tr><td>Sunrise FL</td><td>RAGTIME TAVERN - #4404 - ATLANTIC BEACH</td><td class="rightjustifytext">$221.46</td><td class="rightjustifytext">17.50</td><td class="rightjustifytext">$885.82</td></tr><tr><td>Sunrise FL</td><td>SEVEN BRIDGES - #4403 - JACKSONVILLE</td><td class="rightjustifytext">$367.49</td><td class="rightjustifytext">22.67</td><td class="rightjustifytext">$1,102.47</td></tr><tr><td>T&T</td><td>BIG RIVER - #4201 - CHATTANOOGA</td><td class="rightjustifytext">$396.06</td><td class="rightjustifytext">22.83</td><td class="rightjustifytext">$2,376.34</td></tr><tr><td>T&T</td><td>BIG RIVER - #4205 - HAMILTON PL</td><td class="rightjustifytext">$424.74</td><td class="rightjustifytext">26.00</td><td class="rightjustifytext">$1,698.95</td></tr><tr><td class="bold">TOTAL</td><td></td><td class="bold rightjustifytext">3,770.42</td><td class="bold rightjustifytext">23.50</td><td class="bold rightjustifytext">$1,592.60</td></tr></table></div></div></div></div><script>window.onload = function(){var btnGetData = document.getElementById('btnGetData');btnGetData.addEventListener("click", function () {alert("Twerking...");var unitval = ABUELOS;var begdateval = 2016-08-21;var enddateval = 2016-08-27;var model = JSON.stringify({ unit: unitval, begdate: begdateval, enddate: enddateval });$.ajax({type: 'GET',url: '@Url.Action("GetQuadrantData", "LandingPage")',data: { unit: unitval, begdate: begdateval, enddate: enddateval},contentType: 'application/json',cache: false,success: function (returneddata) {},error: function () {alert('hey, boo-boo!');}});});</script></div></body></html>

UPDATE 4

Just to try to verify that the problem is that I'm dynamically creating the html (and javascript) with C#, I added the script to the Index.cshtml file (which is the initial page and does not get modified at runtime):

. . .
</style>
    <script>
        $(function () {
            var btnGetData = document.getElementById('btnGetData');
            btnGetData.addEventListener("click", function () {
                alert("It works");
                var unitval = 'Abuelos';
                var begdateval = '2016-08-07';
                var enddateval = '2016-08-13';

                $.ajax({
                    type: 'GET',
                    url: '@Url.Action("GetQuadrantData", "LandingPage")',
                    data: { unit: unitval, begdate: begdateval, enddate: enddateval },
                    contentType: 'application/json',
                    cache: false,
                    success: function (returneddata) {
                    },
                    error: function () {
                        alert('hey, boo-boo!');
                    }
                });
            });
        });

    </script>
</head>
. . .

Here is the method in the LandingPageController : ApiController class I'm trying to call with that AJAX:

[Route("{unit}/{begdate}/{enddate}")]
public HttpResponseMessage GetQuadrantData(string unit, string begdate, string enddate)
{
    _unit = unit;
    . . .

Doing this, I do see the "It works" alert, and then the "hey, boo-boo!" too, from the javascript button click event handler. The breakpoint on the "_unit = unit;" is never reached. That's why I see the "boo-boo" message, I reckon, but I don't know why it's not getting reached.

UPDATE 5

The Url.Action args are still being transformed/translated wrong; in Chrome Dev Tools it shows:

<script>
    $(document).ready(function () {
        $("#btnGetData").click(function () {
            $.ajax({
                type: 'GET',
                url: '/LandingPage/GetQuadrantData',
                console.log(url);
                data: {unit: unitval, begdate: begdateval, enddate: enddateval},
                contentType: 'text/plain',
                cache: false,
                xhrFields: {
                    withCredentials: false
                },
                success: function(returneddata) {
                    alert('Successful: ' + returneddata);
                },
                error: function() {
                    alert('hey, boo-boo!');
                }
            }); // ajax
        }); // button click
    }); // ready
</script>

...so this:

url: '@Url.Action("GetQuadrantData", "LandingPage")',

...is being seen in CDT as this:

url: '/LandingPage/GetQuadrantData',

...and I am not reaching the breakpoint which is set at the last line below:

[System.Web.Http.Route("{unit}/{begdate}/{enddate}")]
[System.Web.Http.HttpGet]
public HttpResponseMessage GetQuadrantData(string unit, string begdate, string enddate)
{
    _unit = unit;

UPDATE 6

It was tripping over this line in the middle of the ajax call:

console.log(url);

...but even when I stripped that out so that the jQuery became this (adding some random data values to the args/data):

$(document).ready(function () {
    $("#btnGetData").click(function () {
        $.ajax({
            type: 'GET',
            url: '@Url.Action("GetQuadrantData", "LandingPage")',
            data: {unit: 'ABUELOS', begdate: '2016-08-25', enddate: '2016-08-31'},
            contentType: 'text/plain',
            cache: false,
            xhrFields: {
                withCredentials: false
            },
            success: function(returneddata) {
                console.log('Successful: ' + returneddata);
            },
            error: function() {
                console.log('hey, boo-boo!');
            }
        }); // ajax
    }); // button click
}); // ready

...I still get the "boo-boo" msg written to the console and the breakpoint in my controller is not hit, presumably because the incorrect url is being generated via the Url.Action() method.

UPDATE 7

If I kludgily/experimentally change the ajax call to this, replacing the Url.Action and data with the raw url:

$(document).ready(function () {
    $("#btnGetData").click(function () {
        $.ajax({
            type: 'GET',
            url: 'http://localhost:52194/api/ABUELOS/2016-08-21/2016-08-27',
            contentType: 'text/plain',
            cache: false,
            xhrFields: {
                withCredentials: false
            },
            success: function(returneddata) {
                console.log('Successful: ' + returneddata);
            },
            error: function() {
                console.log('hey, boo-boo!');
            }
        }); // ajax
    }); // button click
}); // ready

..I do reach the breakpoint in the Controller, but the url on the page does not change, and the data (html) on the page is not updated.

BTW, I did change the jquery reference to this, as nyedidikeke recommended:

<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>

UPDATE 8

With this (after moving the javascript references to the bottom, just above "" BTW):

. . .
</style>
    <script>
    $(document).ready(function () {
        $("#btnGetData").click(function () {
            $.ajax({
                type: 'GET',
                url: '@Url.Action("GetQuadrantData", "LandingPage")',
                data: { unit: 'ABUELOS', begdate: '2016-08-25', enddate: '2016-08-31' },
                contentType: 'text/plain',
                cache: false,
                xhrFields: {
                    withCredentials: false
                },
                success: function(returneddata) {
                    console.log('Successful: ' + returneddata);
                },
                error: function() {
                    console.log('hey, boo-boo!');
                }
            }); // ajax
        }); // button click
    }); // ready
    </script>
</head>
. . .

...I get this in Chrome Dev Tools' console:

http://localhost:52194/LandingPage/GetQuadrantData?unit=ABUELOS&begdate=2016-08-25&enddate=2016-08-31&_=1473095349071 Failed to load resource: the server responded with a status of 404 (Not Found)

hey, boo-boo!

UPDATE 9

This is my Register method in \App_Start\WebApiConfig.cs:

public static void Register(HttpConfiguration config)
{
    config.Routes.Clear(); // added this 9/2/2016 at suggestion from http://www.codemag.com/article/1601031
    config.SuppressDefaultHostAuthentication();
    config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );

    // I don't know if this is where this should go (from http://stackoverflow.com/questions/34626483/how-to-pass-datatable-via-frombody-to-web-api-post-method-c)
    config.Formatters.Add(new DataTableMediaTypeFormatter());
    config.Formatters.Add(new GenericProduceUsageListMediaTypeFormatter());
}

Is there anything wrong here?

ruffin
  • 16,507
  • 9
  • 88
  • 138
B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862
  • 4
    Did you open the console and check for errors ? – adeneo Aug 31 '16 at 20:44
  • 1
    you may need to e.preventDefault() at the first line inside your click handler. I seem to recall a similar problem i've had with the button elements. – Cruiser Aug 31 '16 at 20:51
  • 1
    jQuery is not defined? – guest271314 Aug 31 '16 at 20:56
  • Why not use `console.log("The button was clicked.");` instead of `alert("The button was clicked.");` ? **alert();** may not always render well. So you start troubleshooting from there. – nyedidikeke Aug 31 '16 at 21:00
  • 1
    Good! ... now check the order of your *JS files* and *scripts*: make sure you add your scripts after referencing in order of priority your **jQuery** library, then, your **Bootstrap JS** file; that should resolve most of the errors you have printed in your console log. (Remember to clear your browser cache before running the test again and let's continue further troubleshooting from there.) – nyedidikeke Sep 01 '16 at 10:08
  • I think it has to do with dynamically creating the html with C#; the jquery comes first, then the bootstrap. – B. Clay Shannon-B. Crow Raven Sep 01 '16 at 14:36
  • 1
    @B.ClayShannon: what is your expected endpoint (url) and its format? I need the expected content of your endpoint output as well; I would like to run a full simulation to see closely for an effective solution. Also, where is the resource you are trying to access located? Waiting for your response ... – nyedidikeke Sep 01 '16 at 23:56
  • @nyedidikeke: The URL I want is of the format http://localhost:52194/api/ABUELOS/2016-08-21/2016-08-27 ([Route("{unit}/{begdate}/{enddate}")]). The content of the output is pure html (see "return new HttpResponseMessage" above). The resource is built on the fly (dynamically created html, using data from a SQL Server database). – B. Clay Shannon-B. Crow Raven Sep 02 '16 at 16:08
  • @B.ClayShannon: Check my answer for a detailed explanation and resolution. – nyedidikeke Sep 03 '16 at 07:27
  • 3
    this is an absurdly long question for something that should be relatively simple. – Kevin B Sep 06 '16 at 22:05
  • @KevinB: I agree; that something so presumably common is apparently so hard is almost mind boggling. – B. Clay Shannon-B. Crow Raven Sep 07 '16 at 15:52
  • 1
    @B.ClayShannon here's the problem. You claimed that a button handler isn't being fired. If that's really what is happening, then there was no reason to include ajax in the request. CREATE AN MCVE! if you can't recreate the problem in jsfiddle or with a small bit of code that we can use to recreate the problem, it's not worth asking here, you're just wasting everyone's time. – Kevin B Sep 07 '16 at 15:54
  • Your click handler works just fine, and there's a VERY obvious error in your console. fix the error, and problem solved. or, ask about that instead in the first place. – Kevin B Sep 07 '16 at 15:55
  • @KevinB: The solution is not obvious to me or apparently anyone else, as nobody's answer has solved it yet. – B. Clay Shannon-B. Crow Raven Sep 07 '16 at 15:59
  • They all have however pointed out that your original question makes no sense. You asked why a click handler isn't working, and it's not working because the libraries required for your code to work aren't loaded on the page. – Kevin B Sep 07 '16 at 16:00
  • No, that wasn't the problem; they have been loaded from the git-go. – B. Clay Shannon-B. Crow Raven Sep 07 '16 at 16:03
  • Obviously not, *"Uncaught Error: Bootstrap's JavaScript requires jQuery"* – Kevin B Sep 07 '16 at 16:10
  • that clearly indicates that your library isn't loading, and the error prior to that specifies why. Nether have ANYTHING to do with your button click handler. – Kevin B Sep 07 '16 at 16:18
  • At update 8 your problem became unrelated to client-side, and update 9 we start debugging server-side code! your question has morphed EXTREMELY far away from the original question. – Kevin B Sep 07 '16 at 16:27

5 Answers5

10

In order to successfully reach the click event on your button, you first need to address the issues reported in your console (mainly resource 'integrity' error).

Let's begin by resolving the Subresource Integrity error:

Open up your command-line with openssl at the jQuery file location and run:

cat FILENAME.js | openssl dgst -sha384 -binary | openssl enc -base64 -A

where, FILENAME.js is the name of your jQuery file (either: jquery.min.js, in your case.)

or

make use of SRI Hash Generator (by providing the URL to your desired content delivery network (CDN) script and clicking on the HASH button) to generate a Subresource Integrity (SRI) hash.

As such, your expected output should be as follow:

<script src="https://code.jquery.com/jquery-1.12.4.min.js"
    integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ"
    crossorigin="anonymous"></script>

Note: The integrity attribute enables browsers to check and ensure that your referenced resource file does not get loaded should its content differ from what it used to be at the time of the SRI hash generation.

You should then consider a graceful failover by hosting a copy of the jQuery file on your server for use should the content of your referenced CDN version have been altered.

Do so checking whether jQuery has been defined and reference your failover if it hasn't.

<script src="https://code.jquery.com/jquery-1.12.4.min.js"
    integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ"
    crossorigin="anonymous"></script>
<script>window.jQuery || document.write('<script src="path/to/jquery-1.12.4.min.js"><\/script>')</script>

Remember to stick to this priority order when referencing your JavaScript (JS) files:

  1. jQuery library,
  2. Bootstrap JS file, then
  3. your custom JS file, should there be.

Note: your JS references SHOULD preferably be located the end of your page content, before the close of the body tag (</body>).

Once the fixes above applied, you will successfully get in your console: The button was clicked. when you click on the button (refer to the snippets below).

Your button:

<button class="btn btn-success btn-sm" id="btnGetData" name="btnGetData">SUBMIT</button>

Your script:

<!-- jQuery approach -->
$(document).ready(function() {
    $("#btnGetData").click(function() {
        console.log("The button was clicked.");
    }); // button click
}); // ready

<!-- or -->

<!-- Pure JavaScript approach -->
window.onload = function() {
    var btnGetData = document.getElementById('btnGetData');
    btnGetData.addEventListener("click", function () {
        console.log("The button was clicked.");
    }); // button click
}; // ready

Both jQuery and pure JavaScript approach can now work and enable you reach your button while running an integrity test on your intended external resource (jQuery library) and this, with a graceful failover option, to proceed further.

Note: the jQuery approach was failing because the jQuery library wasn't declared owing to the fact that your SRI check failed with no available failover to still load a jQuery library. That accounts for neither The button was clicked. nor hey, boo-boo! being successfully reached for either a click event on the button and or a click event through, to your jQuery AJAX error function.

Proceeding further, use contentType: 'text/plain' in your jQuery AJAX call instead of contentType: 'application/json' since you are expecting pure HTML, not a JSON response and set withCredentials: false (unless your server must respond with the header) as additional property under xhrFields declaration (refer to the snippets below).

xhrFields: {
    withCredentials: false
},

In summary:

$.ajax({
    type: 'GET',

    url: '@Url.Action("GetQuadrantData", "LandingPage")',

    // Should you face any escape character challenge, use 'url' with @Html.Raw()
    //url: '@Html.Raw(@Url.Action("GetQuadrantData", "LandingPage"))',

    console.log(url);

    data: {unit: unitval, begdate: begdateval, enddate: enddateval},

    contentType: 'text/plain',

    cache: false,

    xhrFields: {
        withCredentials: false
    },

    success: function(returneddata) {
        console.log('Successful: ' + returneddata);
    },

    error: function() {
        console.log('hey, boo-boo!');
    }
});
nyedidikeke
  • 6,899
  • 7
  • 44
  • 59
  • "your JS references SHOULD preferably be located the end of your page content, before the close of the body tag (

    )." Including the css link reference, or just the js refs? Right now, both the css and js are added right after title and right before an inline "style" section.

    – B. Clay Shannon-B. Crow Raven Sep 05 '16 at 15:53
  • 1
    Thanks; this has gotten me partway there; please see Update 5. – B. Clay Shannon-B. Crow Raven Sep 05 '16 at 16:13
  • 1
    Just the *JS refs.* SHOULD be before the close of the body tag (`

    `). For your CSS refs., the `

    ` section is okay. Will check your updates ASAP.

    – nyedidikeke Sep 05 '16 at 16:50
2

Try this out, it simply uses vanilla JS to setup your listener then handles the rest with jQuery.

On the test page I made, I was getting my alert just fine.

window.onload = function() {
    var btnGetData = document.getElementById('btnGetData')
    btnGetData.addEventListener("click", function() {
        alert("Twerking...");
        var unitval = _unit;
        var begdateval = _beginDate;
        var enddateval = _endDate;
        var model = JSON.stringify({
            unit: unitval,
            begdate: begdateval,
            enddate: enddateval
        });
        $.ajax({
            type: 'GET',
            url: '@Url.Action("GetQuadrantData", "LandingPage")',
            data: {
                unit: unitval,
                begdate: begdateval,
                enddate: enddateval
            },
            contentType: 'application/json',
            cache: false,
            success: function(returneddata) {},
            error: function() {
                alert('hey, boo-boo!');
            }
        });
    }); // button click
}
nyedidikeke
  • 6,899
  • 7
  • 44
  • 59
AlexanderGriffin
  • 515
  • 2
  • 13
1

Add button type like this if you are submitting a form:

<button type="submit" class="btn green smallbutton" id="btnGetData" name="btnGetData">SUBMIT</button>

UPDATE

From your "Update 2" change first line this :

<script src='https://code.jquery.com/jquery-1.12.4.min.js' integrity='sha256-lZFHibXzMHo3GGeehn1hudTAP3Sc0uKXBXAzHX1sjtk=' crossorigin='anonymous'></script>

to this:

<script src='https://code.jquery.com/jquery-1.12.4.min.js'></script>

we do not need to check integrity of jquery file here so by removing that you will be able to run jquery without any errors. Thanks

Irfan Anwar
  • 1,878
  • 17
  • 30
  • Muhammad Irfan: [data integrity](https://en.wikipedia.org/wiki/Data_integrity) ought to be considered; not neglected. When ineffectively applied or the content of the referenced resource (should it be effectively applied and accessed) has been altered, the resulting will be an error and or failure to load the external resource unless a graceful failover has been provided (to load a local copy of the external resource). Also, adding `type="submit"` to the button is NOT necessary (unused) as the expected behaviour is already being handled in the JavaScript section. Check my answer for details. – nyedidikeke Sep 04 '16 at 22:54
1

Your code works for me: http://codepen.io/danielvaughn/pen/jrNoko

Are you sure that you're properly importing jQuery? If not, run some jquery functions in your console to make sure it works.

<button class="btn green smallbutton" id="btnGetData" name="btnGetData">SUBMIT</button>
Daniel Vaughn
  • 73
  • 1
  • 7
1

Dude, one question: are you sure you included the jquery library correctly?

I tried this and it worked

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">   

    $(document).ready(function () {
        $("#btnGetData").click(function () {
            alert("The button was clicked.");

        }); // button click
    }); // ready
</script>
allan.p
  • 27
  • 4
  • try this because you are getting a console error because of integrity and crossorign attributes – allan.p Aug 31 '16 at 21:10
  • @allan.p: without the [Subresource Integrity (SRI)](https://www.w3.org/TR/SRI/) check Clay was using (non-functioning), it will definitely work but the point is it's [importance](https://en.wikipedia.org/wiki/Data_integrity). Henceforth, resolving the data integrity check error affecting the resource to be consumed (here, the jQuery library) should be the most effective solution other than alienating it. See my answer applying the fix for a detailed explanation. – nyedidikeke Sep 04 '16 at 22:29