Introduction:

Here we are going to explain what is post() method  or how to use post() method or why use post() method  or how to send an HTTP POST  request to the server and retrieve data without browser postback/refresh  in jQuery with example.

Description: 

The jQuery post() method use to send an HTTP POST request to the server and retrieve the data without browser postback/refresh.  

Let’s see a demonstration example of post() method 

Index.cshtml:

@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>post Method</title>
    <script src="~/Scripts/jquery-1.7.1.min.js"></script>
</head>
<body>
    <input type="button" id="btnpost" value="Load Data using Post" />
    <div id="divResult"></div>
        <script>        $("#btnpost").click(function () {
   $.post("/Tutorials/GetJsonData",function (data) {                      
     $("#divResult").html("<b>The result is:</b> "+ JSON.stringify(data) + "");
   });       
});   
</script>
</body>
</html>

TutorialsController:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace Jquery.Controllers
{
    public class TutorialsController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public JsonResult GetJsonData()
        {
            Students[] obj = new Students[]  
            {
                new Students()  
                {    
                  StudentId = 1, 
                  Name = "NitinTyagi"
                  Marks = 400 
                }, 
                new Students()  
                { 
                    StudentId = 2, 
                    Name = "AshishTripathi"
                    Marks = 500 
                } 
            };
            return Json(obj, JsonRequestBehavior.AllowGet);
        }
 
    }
 
    public class Students
    {
        public int StudentId { get; set; }
        public string Name { get; set; }
        public int Marks { get; set; }
    }
}

 

Here on click of “btnpost” button, post() method will fire.

Here

  1. url: Any valid url
  2. data : data to send to the server
  3. success: function to execute when the request is processed successfully, the “data” is the exact value that will have all the response string returned from the server.

 In above code when we click on button then send an http post request to the server and retrive data in “divResult”.

Output:

 .post()-Post request to server in jQuery

I hope it will help to you.

 

 

 

0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

You may also like