Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement an Ajax call using the tags data-*

I'm trying to implement an Ajax call using the tags data-* as described at jquery-ajax-unobtrusive

I know that I can use a javascript function with $.ajax() but my purpose is to experiment with the tags data-ajax...

I tried this code in the cshtml file

<a class="btn btn-primary" data-ajax-url="/Home/AjaxSample" data-ajax="true" data-ajax-success="AjaxSuccess" data-ajax-failure="AjaxError" data-ajax-method="GET">Ajax</a>

// other code...

function AjaxSuccess() { alert('AjaxSuccess'); }
function AjaxError() { alert('AjaxError'); }

The browser shows the button of course, but nothing happens when I click it. I can't discover any error in the browser debugger. Nothing happens apparently.

Intellisense doesn't show the tags data-ajax and friends. Did I forget to include something?

Are there any complete working examples?

like image 495
Tonyc Avatar asked Mar 23 '17 09:03

Tonyc


People also ask

What is AJAX call with example?

The ajax() method can send all type of http requests. The following example sends http POST request to the server. Example: Send POST Request. $.ajax('/jquery/submitData', { type: 'POST', // http method data: { myData: 'This is my data.'

What is AJAX call in HTML?

AJAX uses both a browser built-in XMLHttpRequest object to get data from the web server and JavaScript and HTML DOM to display that content to the user. Despite the name “AJAX” these calls can also transport data as plain text or JSON instead of XML. AJAX calls use a JavaScript snippet to load dynamic content.

What is the use of AJAX () method?

The ajax() method is used to perform an AJAX (asynchronous HTTP) request. All jQuery AJAX methods use the ajax() method. This method is mostly used for requests where the other methods cannot be used.


1 Answers

The answer from the comments (since no-one has added it):

<script src="~/lib/jquery-ajax-unobtrusive/jquery.unobtrusive-ajax.j‌​s"></script>
<!-- the ~ is to symbolize your project's wwwroot folder

Add the above to your master layout with all of your other scripts (_Layout.cshtml by default).

What this does is include the jQuery unobtrusive ajax file into all of your pages, so that the main script that does all the work is included.

Before doing this, make sure you have installed the package Microsoft.Jquery.Unobtrusive.Ajax

like image 79
Solver Avatar answered Oct 20 '22 01:10

Solver