Skip to content

jQuery AJAX and REST API Integration: Practical Coding Tips and Examples

Recently, I picked up jQuery again for a project, and it felt so familiar—like an old friend. If you remember, I used to talk about jQuery a lot before Vue and other modern frameworks, it was everything in web development. Anyway, this time I connected my C# backend to a REST API using AJAX calls. It’s simple in theory, but sometimes you get stuck, right? So I wanted to share this, maybe you’ll find it useful.

Yes, when I mention jQuery AJAX, some might wonder what it does. Basically, it allows you to send requests to the server and get data without refreshing the webpage. For example, you fill out a form and want to check with the backend if the data is valid before submitting—without reloading the page, keeping the user experience smooth. For those developing REST APIs, it’s indispensable, because on the .NET side, you can fetch data with Dapper, return JSON, and then jQuery captures and displays it.

Meanwhile, I remembered my PHP days when I also spent a lot of time with AJAX. But now, with Vue, jQuery has somewhat been sidelined, although I still find it practical. So, let’s get back to the main point. The power of AJAX: it works asynchronously, meaning the page doesn’t freeze. You send a request, and while waiting for the server’s response, you can do other things. Just watch out for cross-origin issues sometimes—you’ll need to handle CORS settings on your backend.

One of my favorite parts is error handling. jQuery AJAX has success and error callbacks, which help you catch problems. For instance, if a 404 error occurs, you can alert ‘Data not found.’ I once forgot to handle errors, and users saw an empty page, which was embarrassing! 🙂

Basic Usage of jQuery AJAX

Let’s get to practical coding. After including jQuery, a simple GET request looks like this:
<script>$(document).ready(function(){
  $.ajax({
    url: ‘api/data’,
    type: ‘GET’,
    dataType: ‘json’,
    success: function(data){
      console.log(data); // You can output or process data here
    },
    error: function(){
      alert(‘An error occurred’);
    }
  });
});</script> This is it. Adjust the URL to your REST API endpoint. If you’re retrieving data from PostgreSQL with Dapper, you write the query and return JSON.

For POST requests, you need to send data. Set type to ‘POST’, include data as an object, and specify contentType as ‘application/json’. In C#, I use [FromBody] to parse JSON. Ultimately, this integration works regardless of whether you use MySQL or PostgreSQL, as they just return JSON data.

Also, jQuery’s beforeSend can display a loading indicator:
<script>$(function(){
  $.ajax({
    beforeSend: function(){ $(‘#loader’).show(); },
    complete: function(){ $(‘#loader’).hide(); }
  });
});</script> Isn’t that nice? Users see a spinner while waiting, improving UX.

Sometimes, promise-based syntax can be confusing—jQuery AJAX already returns a promise, but I try not to mix it with async/await. What do you prefer: still using jQuery or switching to fetch API?

Sample Integration with REST API

Let me give an example: fetching user list in my REST API. On the server side, in C#:
[HttpGet] public IActionResult GetUsers() { var users = _repo.GetAll(); return Ok(users); }
In PostgreSQL with Dapper:
using (var conn = new NpgsqlConnection(cs)) { return conn.Query<User>(“SELECT * FROM users”).ToList(); }

And on the frontend, using jQuery AJAX:
$.ajax({ url: ‘/api/users’, method: ‘GET’, success: function(users){
$.each(users, function(i, user){ $(‘#userList’).append(‘<li>’ + user.name + ‘</li>’); });
}, error: function(xhr){ console.log(‘Error: ‘ + xhr.status); } });
Thus, the list populates correctly. If there’s a lot of data, consider adding pagination to avoid slowdowns.

I think I made a mistake recently—forgot to write https in the URL, resulting in a mixed content error. Always check the browser console. The jQuery documentation has plenty of examples, visit the official jQuery site for details.

Here’s a POST example: adding a new user.
var newUser = { name: $(‘#name’).val(), email: $(‘#email’).val() };
$.ajax({ url: ‘/api/users’, type: ‘POST’, contentType: ‘application/json’, data: JSON.stringify(newUser), success: function(){ alert(‘Added!’); }, error: function(){ alert(‘Failed to add’); } });
And in C#:
[HttpPost] public IActionResult AddUser([FromBody] User user) { _repo.Add(user); return Ok(); }

It works well, but don’t forget to add validation.

I personally like Dapper because it allows raw SQL queries without being as heavy as Entity Framework. It’s fast with PostgreSQL, and the same applies to MySQL—no major difference in my view.

One last note: I updated my jQuery version recently, and although AJAX settings remained the same, some methods became deprecated. Be cautious when upgrading. Search for ‘jQuery AJAX migration guide’ for helpful resources.

Security and Best Practices

Regarding security, include CSRF tokens in AJAX requests:
headers: { ‘X-CSRF-TOKEN’: $(‘meta[name=csrf-token]’).attr(‘content’) }
On the C# side, validate the anti-forgery token. Very important to prevent hackers from posting malicious data.

Timeout issues can occur—add timeout: 5000 to cancel requests after 5 seconds. I’ve experienced users waiting infinitely when I forgot this, which wasn’t ideal. 🙂

By the way, just like in embedded systems design, AJAX-like requests are used in embedded hardware projects too—though that’s another topic. If you want to mix jQuery with Vue, you can wrap jQuery calls or Vue’s $http, if needed.

In conclusion, jQuery AJAX remains a fantastic tool for REST API integration. I use it daily for practical and quick development. If you’re starting, try a demo project and see how easy it is. I once read an article mentioning that fetch is trending now, but for me, jQuery remains accessible and simple.

For detailed examples, search for ‘jquery ajax rest api example’ or visit MDN Web Docs for AJAX tutorials. Hope this helps, and feel free to ask questions in the comments.

That’s all for now. Use AJAX to speed up your web apps and enjoy the process. Next time, I might cover Vue integration—but for now, that’s it.