In this article we will clarify our knowledge about using and posting a form with JQuery and Ajax.
Before dive into core topic let’s have an overview about JQuery and Ajax. What is it?
What is JQuery?
Well, JQuery is a framework (tools) for writing JavaScript, Walk as “write less, do more”, jQuery is to make easier to use JavaScript.
What is JavaScript?
JavaScript is an object-oriented computer programming (Scripting)language commonly used to create interactive effects within web browsers.
Let’s have a sample Example:
We have a submit button in our FormSubmit MVC application. Let’s try to show a message when it is clicked.
Here is our button with defined id=”btnSubmit”
Now we need to write some script to do that, here is some JavaScript code:
var myBtn = document.getElementById('btnSubmit'); myBtn.addEventListener('click', function (e) { e.preventDefault(); //This prevents the default action alert('Hello'); //Show the alert });
By this code the result will show “Hello”
Now if we can get the same result by using jQuery instead of it. Let’s have a look: $('#btnSubmit').click(function (event) { event.preventDefault();//This prevents the default action alert("Hello"); //Show the alert });
Note: Here use of ‘e’ is just a short for event which raised the event. We can pass any variable name. Notice that the ‘e’ is changed to name ‘event’ in JQuery part.
Ok, this piece of code is also producing the same result “Hello”. This is why jQuery is known as “write less, do more”.
Finally the Script:
Let’s focus on Ajax:
AJAX stands for “Asynchronous JavaScript and XML”. AJAX is about exchanging data with a server, without reloading the whole page. It is a technique for creating fast and dynamic web pages.
In .NET, we can call server side code using two ways:
- ASP .NET AJAX
- jQuery AJAX
In this article we will focus on JQuery Ajax.
$.ajax () Method:
JQuery’s core method for creating Ajax requests. Here are some jQuery AJAX methods:
- $.ajax() Performs an async AJAX request
- $.get() Loads data from a server using an AJAX HTTP GET request
- $.post() Loads data from a server using an AJAX HTTP POST request
To know more click ..
$.ajax () Method Configuration option:
Options that we use:
- async
- type
- url
- data
- datatype
- success
- error
Let’s have details overview:
async
Set to false if the request should be sent synchronously. Defaults to true.
Note that if you set this option to false, your request will block execution of other code until the response is received.
Ex: async: false,
type
This is type of HTTP Request and accepts a valid HTTP verb.
The type of the request, “POST” or “GET”. Defaults to “GET”. Other request types, such as “PUT” and “DELETE” can be used, but they may not be supported by all browsers.
Ex: type: "POST",
url
The URL for the request.
Ex: url: "/Home/JqAJAX",
data
The data to be sent to the server. This can either be an object or a query string.
Ex: data: JSON.stringify(student),
dataType
The type of data you expect back from the server. By default, jQuery will look at the MIME type of the response if no dataType is specified.
Accepted values are text, xml, json, script, html jsonp.
Ex: dataType: "json",
contentType
This is the content type of the request you are making. The default is ‘application/x-www-form-urlencoded’.
contentType: 'application/json; charset=utf-8',
success
A callback function to run if the request succeeds. The function receives the response data (converted to a JavaScript object if the dataType was JSON), as well as the text status of the request and the raw request object.
success: function (result) { $('#result').html(result); }
error
A callback function to run if the request results in an error. The function receives the raw request object and the text status of the request.
error: function (result) { alert('Error occured!!'); }
Let’s Post Values:
We often use the using the jQuery Ajax method in ASP.NET Razor Web Pages. Here is a sample code:
Script:
Controller Action:
// GET: Home/JqAJAX [HttpPost] public ActionResult JqAJAX(Student st) { try { return Json(new { msg = "Successfully added " + st.Name }); } catch (Exception ex) { throw ex; } }
Posting JSON
JSON is a data interchange format where values are converted to a string. The recommended way to create JSON is include the JSON.stringify method. In this case we have defined:
JSON.stringify(Student)
And the data type set to
datatype: "json"
and the content type set to application/json
contentType: 'application/json; charset=utf-8'
Syntax:
JSON.stringify(value[, replacer[, space]])
Code:
var Student = { ID: '10001', Name: 'Shashangka', Age: 31 }; $.ajax({ type: "POST", url: "/Home/JqAJAX", data: JSON.stringify(Student), contentType: 'application/json; charset=utf-8', success: function (data) { alert(data.msg); }, error: function () { alert("Error occured!!") } });
Controller Action:
// GET: Home/JqAJAX [HttpPost] public ActionResult JqAJAX(Student st) { try { return Json(new { msg = "Successfully added " + st.Name }); } catch (Exception ex) { throw ex; } }
JSON Response Result:
Sent data format:
{"ID":"10001","Name":"Shashangka","Age":31}
Received Data format:
{"msg":"Successfully added Shashangka"}
Let’s Post JavaScript Objects:
To send JavaScript Objects we need to omit the JSON.stringify(Student) method and we need to pass the plain object to the data option. In this case we have defined:
data: Student
And the data type set to
datatype: "html"
and the content type set to default
contentType: 'application/x-www-form-urlencoded'
Code:
var Student = { ID: '10001', Name: 'Shashangka', Age: 31 }; $.ajax({ type: "POST", url: "/Home/JqAJAX", data: Student, contentType: 'application/x-www-form-urlencoded', success: function (data) { alert(data.msg); }, error: function () { alert("Error occured!!") } });
Controller Action:
// GET: Home/JqAJAX [HttpPost] public ActionResult JqAJAX(Student st) { try { return Json(new { msg = "Successfully added " + st.Name }); } catch (Exception ex) { throw ex; } }
JavaScript Objects Response Result:
Sent data format:
ID=10001&Name=Shashangka&Age=31
Received Data format:
{"msg":"Successfully added Shashangka"}
Let’s Post JavaScript Arrays:
To send Array we need to omit the JSON.stringify(Student) method and we need to pass the plain object to the data option. In this case we have defined:
data: Student
And the data type set to
datatype: "html"
and the content type set to default
contentType: 'application/x-www-form-urlencoded'
Code:
var ID = ["Shashangka", "Shekhar", "Mandal"]; $.ajax({ type: "POST", url: "/Home/JqAJAX", data: { values: ID }, datatype: "html", contentType: 'application/x-www-form-urlencoded', success: function (data) { alert(data.msg); }, error: function () { alert("Error occured!!") } });
Controller Action:
// GET: Home/JqAJAX [HttpPost] public ActionResult JqAJAX(string[] values) { try { return Json(new { msg = String.Format("Fist Name: {0}", values[0]) }); } catch (Exception ex) { throw ex; } }
Array Response Result:
Sent data format:
values[]=Shashangka&values[]=Shekhar&values[]=Mandal
Received Data format:
{"msg":"Fist Name: Shashangka"}
Hope this will help to understand different data type and Ajax posting. Thanks 🙂