| by Achyut Kendre | 5 comments

How to make AJAX request using jQuery?

Learn JQuery
J Query Introduction

Example : https://drive.google.com/file/d/1Ed49rtebyOtRC6sDW4PKscqpvMYRuR3W/view?usp=sharing

jQuery provides you built in method to make AJAX request to sever and retrieve result.

What is AJAX in jQuery?

AJAX is called Asynchronous Java Script with XML , it enables us to make the sync request to the server and retrieve the result from the server to load it in UI without refreshing or reloading the page.

To implement the ajax using ajax() method using following syntax –

$.ajax({
url:
“url”,
type:“get/post/put/delete”,
contentType:“application/json/xml”,
success:function(result) {},
error:function(err){}
})

url:- this parameter allow you to specify the url of a program to which you want to make the request.
type:- this parameter allow you to specify the method used to make the request like get, post, delete, put.
contentType:- allow you to specify the type of content you are expecting from the server.
success:- allow you to specify the function/method that will be executed when the ajax call is successful. This method also get the result of call in variable or parameter.
error: – allow you to specify the function/method that will be executed when their is error and error information will be received the error parameter.

jQuery AJAx Method Example.

Let us implement it step by step –

Step1: Create Empty ASP.NET Core Project.

Step 2: Activate the MVC and End Point Routing

public void ConfigureServices(IServiceCollection services)        {
            services.AddControllersWithViews();
        }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)   {
            if (env.IsDevelopment())            {
                app.UseDeveloperExceptionPage();
            }
            app.UseStaticFiles();
            app.UseRouting();
            app.UseEndpoints(endpoints =>         {
                endpoints.MapDefaultControllerRoute();
            });
        }

Step 3: Create Home Controller and Index Action with Index View.

public class HomeController : Controller
 {
        public IActionResult Index()
        {
            return View();
        }
 }

Step 4: Install jQuery to install jQuery refer previous article (install it using libman)

Step 5: Create Models Folder and Create Customer Model as follows.

namespace JQueryAJAXEx.Models
{
    public class Customer
    {
        public Int64 CustomerID { get; set; }
        public string CustomerName { get; set; }
        public string Address { get; set; }
        public string EmailID { get; set; }
        public string MobileNo { get; set; }
        public decimal CreditLimit { get; set; }

        public static List<Customer> GetCustomers()
        {
            List<Customer> lst = new List<Customer>();
            lst.Add(new Customer() {CustomerID=121,CustomerName="Ganesh",Address="Nigdi Pune",EmailID="Ganesh@gmail.com",CreditLimit=45000,MobileNo="8989898"});
            lst.Add(new Customer() { CustomerID = 122, CustomerName = "Suresh", Address = "Nigdi Pune", EmailID = "suresh@gmail.com", CreditLimit = 55000, MobileNo = "78989898" });
            lst.Add(new Customer() { CustomerID = 123, CustomerName = "Sudhir", Address = "Mumbai", EmailID = "sudhir@gmail.com", CreditLimit = 65000, MobileNo = "777989898" });
            lst.Add(new Customer() { CustomerID = 124, CustomerName = "Anil", Address = "Delhi", EmailID = "Anil@gmail.com", CreditLimit = 75000, MobileNo = "8977789898" });
            lst.Add(new Customer() { CustomerID = 125, CustomerName = "Amol", Address = "Nigdi Pune", EmailID = "Amol@hotmail.com", CreditLimit = 45000, MobileNo = "8989898" });
            lst.Add(new Customer() { CustomerID = 121, CustomerName = "Ganesh", Address = "Nigdi Pune", EmailID = "Ganesh@gmail.com", CreditLimit = 45000, MobileNo = "8989898" });
            lst.Add(new Customer() { CustomerID = 122, CustomerName = "Suresh", Address = "Nigdi Pune", EmailID = "suresh@gmail.com", CreditLimit = 55000, MobileNo = "78989898" });
            lst.Add(new Customer() { CustomerID = 123, CustomerName = "Sudhir", Address = "Mumbai", EmailID = "sudhir@gmail.com", CreditLimit = 65000, MobileNo = "777989898" });
            lst.Add(new Customer() { CustomerID = 124, CustomerName = "Anil", Address = "Delhi", EmailID = "Anil@gmail.com", CreditLimit = 75000, MobileNo = "8977789898" });
            lst.Add(new Customer() { CustomerID = 125, CustomerName = "Amol", Address = "Nigdi Pune", EmailID = "Amol@hotmail.com", CreditLimit = 45000, MobileNo = "8989898" });

            lst.Add(new Customer() { CustomerID = 121, CustomerName = "Ganesh", Address = "Nigdi Pune", EmailID = "Ganesh@gmail.com", CreditLimit = 45000, MobileNo = "8989898" });
            lst.Add(new Customer() { CustomerID = 122, CustomerName = "Suresh", Address = "Nigdi Pune", EmailID = "suresh@gmail.com", CreditLimit = 55000, MobileNo = "78989898" });
            lst.Add(new Customer() { CustomerID = 123, CustomerName = "Sudhir", Address = "Mumbai", EmailID = "sudhir@gmail.com", CreditLimit = 65000, MobileNo = "777989898" });
            lst.Add(new Customer() { CustomerID = 124, CustomerName = "Anil", Address = "Delhi", EmailID = "Anil@gmail.com", CreditLimit = 75000, MobileNo = "8977789898" });
            lst.Add(new Customer() { CustomerID = 125, CustomerName = "Amol", Address = "Nigdi Pune", EmailID = "Amol@hotmail.com", CreditLimit = 45000, MobileNo = "8989898" });
            lst.Add(new Customer() { CustomerID = 121, CustomerName = "Ganesh", Address = "Nigdi Pune", EmailID = "Ganesh@gmail.com", CreditLimit = 45000, MobileNo = "8989898" });
            lst.Add(new Customer() { CustomerID = 122, CustomerName = "Suresh", Address = "Nigdi Pune", EmailID = "suresh@gmail.com", CreditLimit = 55000, MobileNo = "78989898" });
            lst.Add(new Customer() { CustomerID = 123, CustomerName = "Sudhir", Address = "Mumbai", EmailID = "sudhir@gmail.com", CreditLimit = 65000, MobileNo = "777989898" });
            lst.Add(new Customer() { CustomerID = 124, CustomerName = "Anil", Address = "Delhi", EmailID = "Anil@gmail.com", CreditLimit = 75000, MobileNo = "8977789898" });
            lst.Add(new Customer() { CustomerID = 125, CustomerName = "Amol", Address = "Nigdi Pune", EmailID = "Amol@hotmail.com", CreditLimit = 45000, MobileNo = "8989898" });
            lst.Add(new Customer() { CustomerID = 121, CustomerName = "Ganesh", Address = "Nigdi Pune", EmailID = "Ganesh@gmail.com", CreditLimit = 45000, MobileNo = "8989898" });
            lst.Add(new Customer() { CustomerID = 122, CustomerName = "Suresh", Address = "Nigdi Pune", EmailID = "suresh@gmail.com", CreditLimit = 55000, MobileNo = "78989898" });
            lst.Add(new Customer() { CustomerID = 123, CustomerName = "Sudhir", Address = "Mumbai", EmailID = "sudhir@gmail.com", CreditLimit = 65000, MobileNo = "777989898" });
            lst.Add(new Customer() { CustomerID = 124, CustomerName = "Anil", Address = "Delhi", EmailID = "Anil@gmail.com", CreditLimit = 75000, MobileNo = "8977789898" });
            lst.Add(new Customer() { CustomerID = 125, CustomerName = "Amol", Address = "Nigdi Pune", EmailID = "Amol@hotmail.com", CreditLimit = 45000, MobileNo = "8989898" });
            lst.Add(new Customer() { CustomerID = 121, CustomerName = "Ganesh", Address = "Nigdi Pune", EmailID = "Ganesh@gmail.com", CreditLimit = 45000, MobileNo = "8989898" });
            lst.Add(new Customer() { CustomerID = 122, CustomerName = "Suresh", Address = "Nigdi Pune", EmailID = "suresh@gmail.com", CreditLimit = 55000, MobileNo = "78989898" });
            lst.Add(new Customer() { CustomerID = 123, CustomerName = "Sudhir", Address = "Mumbai", EmailID = "sudhir@gmail.com", CreditLimit = 65000, MobileNo = "777989898" });
            lst.Add(new Customer() { CustomerID = 124, CustomerName = "Anil", Address = "Delhi", EmailID = "Anil@gmail.com", CreditLimit = 75000, MobileNo = "8977789898" });
            lst.Add(new Customer() { CustomerID = 125, CustomerName = "Amol", Address = "Nigdi Pune", EmailID = "Amol@hotmail.com", CreditLimit = 45000, MobileNo = "8989898" });
            lst.Add(new Customer() { CustomerID = 121, CustomerName = "Ganesh", Address = "Nigdi Pune", EmailID = "Ganesh@gmail.com", CreditLimit = 45000, MobileNo = "8989898" });
            lst.Add(new Customer() { CustomerID = 122, CustomerName = "Suresh", Address = "Nigdi Pune", EmailID = "suresh@gmail.com", CreditLimit = 55000, MobileNo = "78989898" });
            lst.Add(new Customer() { CustomerID = 123, CustomerName = "Sudhir", Address = "Mumbai", EmailID = "sudhir@gmail.com", CreditLimit = 65000, MobileNo = "777989898" });
            lst.Add(new Customer() { CustomerID = 124, CustomerName = "Anil", Address = "Delhi", EmailID = "Anil@gmail.com", CreditLimit = 75000, MobileNo = "8977789898" });
            lst.Add(new Customer() { CustomerID = 125, CustomerName = "Amol", Address = "Nigdi Pune", EmailID = "Amol@hotmail.com", CreditLimit = 45000, MobileNo = "8989898" });
            return lst;
        }
    }
}

Step 6: Create GetCustomers() method which will return you a customer data in the form in JSON.

public JsonResult GetCustomers()
  {
            List<Customer> lst = Customer.GetCustomers();
            return Json(lst);
  }

Step 7: Invoke this action from Index View using Ajax Method as follows –


@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script type="text/javascript" src="~/js/jquery/jquery.js" > </script>
    <script type="text/javascript">
        $(function () { 

            $("#btn").click(function () {

                $.ajax({
                    url: "/home/getcustomers",
                    type: "Get",
                    contentType: "application/json",
                    success: function (result) {
                    //    alert(JSON.stringify(result)); 
                        var str = "";
                        $("#tb").empty();
                        for (var i = 0; i < result.length; i++) {
                            str = "<tr><td>" + result[i].customerID + "</td>";
                            str += "<td>" + result[i].customerName + "</td>";
                            str += "<td>" + result[i].address + "</td>";
                            str += "<td>" + result[i].emailID + "</td>";
                            str += "<td>" + result[i].mobileNo + "</td>";
                            str += "<td>" + result[i].creditLimit + "</td></tr>";
                            $("#tb").append(str);
                        }

                    },
                    error: function (err) {
                        alert("Error:"+ err.statusText);
                    }
                });

            });
        });
    </script>
</head>
<body>
     <input type="button" value="load" id="btn" />
      <table border="1">
          <tr>
              <td>
                  Customer ID
              </td>
              <td>
                 Customer Name
              </td>
              <td>
                  Address
              </td>
              <td>
                 Email ID
              </td>
              <td>
                  Mobile No
              </td>
              <td>
                 Credit Limit
              </td>
          </tr>
          <tbody id="tb">

          </tbody>
      </table>
</body>
</html>

This way we can use jquery ajax to make a sync request to server and retrieve the result from the server.

5 Comments

web site

August 9, 2024 at 10:57 pm Reply

Very interesting subject, thanks for putting up.Blog monetyze

Noe Wragge

September 5, 2024 at 12:02 pm Reply

I like how well-written and informative your content is. You have actually given us, your readers, brilliant information and not just filled up your blog with flowery texts like many blogs today do. If you visit my website UY8 about E-Book Marketing, I’m sure you can also find something for yourself.

StroyBlog.by

October 18, 2024 at 10:00 am Reply

Возведение коттеджа – это важное и требующее внимания занятие, предполагающее не только финансовых
вложений, но и осознанного подхода на каждом этапе.
Недавно я столкнулся с необходимостью построить дом для своей
семьи и начал тщательно изучать все нюансы.
В процессе поиска информации я нашел очень полезный ресурс StroyBlog.by, где собраны множество полезных советов и рекомендации для
людей, собирающихся строить
загородного дома в Республике Беларусь.

На первом этапе, с которого стоит начать процесс строительства, является выбор подходящего участка.
Этот момент может показаться простым, но на практике существует множество
нюансов: транспортную доступность, инфраструктуру, грунтовые условия
и и другие ключевые факторы.

На сайте я нашел полезную информацию о том,
какие могут возникнуть ошибки при покупке участка и что
делать, чтобы их избежать.

После выбора участка, необходимо заняться проектированием дома.
Одним из важных моментов является
планировка, которая должна быть удобной и
функциональной. Недочеты на этой стадии могут стать причиной лишних расходов и проблем в дальнейшем.
На Stroyblog.by приведены примеры планировок, которые можно
адаптировать под свои нужды, а также советы по выбору
архитектурного стиля.
Следующим важным этапом является — это выбор
строительных материалов. Современные технологии предлагают множество вариантов:
от традиционного кирпича до современных
решений, таких как газобетон и СИП-панели.
Каждый из них имеет свои плюсы и минусы, и решение необходимо принимать, исходя
из учитывая климатические условия и бюджет.
На сайте есть рекомендации по выбору материалов,
что помогает сделать осознанный выбор.

Не менее важно уделить
внимание выбору подрядчика.
Итоговый результат строительства во
многом зависит от компетенции и квалификации команды,
которая выполняет работы.
На Stroyblog.by можно найти советы по тому, как
правильно выбрать проверенного подрядчика, а также как контролировать качество выполненных работ.

Не стоит забывать и про благоустройство территории после завершения строительства.
Поначалу может показаться, что это второстепенная
задача, однако красивый ландшафтный дизайн
и продуманное расположение хозяйственных
построек добавят уют и завершенность любому участку.

В заключение хочется отметить, что возведение
частного дома — это долгий и сложный процесс,
который требует скрупулезного подхода к
мелочам. Благодаря ресурсам вроде Stroyblog.by, вы
сможете избежать большинства ошибок и сделать строительство менее стрессовым.
Если вы только начинаете свой путь
в этом направлении, советую внимательно изучить
каждый этап и воспользоваться
полезными советами, чтобы сделать дом своей мечты реальностью.

best golf balls

October 23, 2024 at 10:09 am Reply

As an enthusiastic golf player, I can’t worry enough just how crucial the appropriate accessories are to not only enjoying the video game yet additionally boosting your performance on the training
course. Golf is as much a mental game as it is physical, and having the proper equipment can truly make
a difference in just how you approach each round.

To start with, let’s discuss golf handwear covers.
Numerous players ignore the importance of an excellent handwear
cover. It’s not nearly protecting against blisters; a glove helps
you preserve a regular grasp on your club, which is essential for regulating your shots.

Specifically in moist or wet problems, an excellent glove can be the difference between a solid drive and
a wild slice. Gloves with a snug fit made from high-grade leather
often tend to use the very best efficiency.
They mold to your turn over time, offering both comfort and dependability.

Another commonly ignored accessory is the golf tee.
Yes, it’s a small item, but the ideal tee can really
impact your video game. As an example, making use of much longer
tees with your driver can aid you accomplish better launch angles,
while shorter tees are best when you need even more control with your irons.
Personally, I choose using biodegradable or plastic tees because they’re
extra durable and eco-friendly.

Golf bags are an additional essential that deserve even more attention than they generally obtain. A well-designed golf bag isn’t practically style– it’s about
performance and comfort. If you favor walking the course, a lightweight stand bag with good
storage space alternatives can make your round a lot more enjoyable.
On the other hand, if you’re riding in a cart, a cart bag with a lot of room for all your equipment is a
must. The best golf bag assists you stay arranged,
which is important when you require to focus on your video game.

One device that’s coming to be increasingly popular is the rangefinder.
I can not tell you just how much this little tool has boosted my video game.
Recognizing the exact range to the pin or hazards allows you to pick the right club with self-confidence.
Whether you select a laser rangefinder or a GPS one, the accuracy these devices offer is invaluable.

Lastly, never ever take too lightly the significance of
a good golf towel and umbrella. A towel keeps your clubs and rounds
tidy, ensuring far better contact and precision, while an umbrella is a
lifesaver throughout unanticipated weather changes. These little items add to
the general top quality of your video game.

Finally, purchasing the ideal golf devices is vital
for anybody major about boosting their game. Whether it’s a handwear cover that fits just right,
a durable golf bag, or a high-tech rangefinder, having the right tools can make every round a lot more pleasurable and successful.
For anyone looking for detailed evaluations and professional suggestions on the very
best golf gear, I highly suggest checking out best golf balls.

zoritoler imol

November 3, 2024 at 11:05 am Reply

Well I truly liked studying it. This subject procured by you is very helpful for correct planning.

Leave a Reply