0% found this document useful (0 votes)
4 views12 pages

Sending a Request to a Server Using AJAX

The document provides examples of using AJAX in an MVC application to send requests to the server, handle responses, and update the UI without refreshing the page. It covers various scenarios including form submission, displaying data from the database in JSON format, and image previews. Additionally, it demonstrates how to manage large amounts of data and update content dynamically using AJAX techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views12 pages

Sending a Request to a Server Using AJAX

The document provides examples of using AJAX in an MVC application to send requests to the server, handle responses, and update the UI without refreshing the page. It covers various scenarios including form submission, displaying data from the database in JSON format, and image previews. Additionally, it demonstrates how to manage large amounts of data and update content dynamically using AJAX techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Sending a request to a server using AJAX :

obj1=new XMLHttpRequest();
obj1.open("GET","another_page_name",true);
obj1.send();

For Example :
(i) Open a new MVC Application :
(ii) Write the code on “Index.cshtml” view page as :-

<input type="button" value="Click Me" onclick="fun1()" />


<script type="text/javascript">
function fun1()
{
if (window.XMLHttpRequest)
{
obj1 = new XMLHttpRequest();
obj1.onreadystatechange = fun2;
}
obj1.open("POST", "Home/Index", true); // Here “Home” is controller and
“Index”
is action name in MVC application.
obj1.send();
}
function fun2()
{
if (obj1.readyState == 0)
{
alert("Request is not initilize"); // this message displays, if
the
Browser does not support ajax.
}
if (obj1.readyState == 1)
{
alert("Resuest is ready to sent");
}
if (obj1.readyState == 2)
{
alert("Request Sent");
}
if (obj1.readyState == 3)
{
alert("Request In Process");
}
if (obj1.readyState == 4)
{
alert("Request is completed");
}
}
</script>

Example of AJAX that display the sum of two numbers in the textbox:
(i) write in the “index.cshtml” view page as :
Type First Number : <input type="text" id="txt1" value="0" onkeyup="fun1()" /> +
<br/><br/>
Type Second Number : <input type="text" id="txt2" value="0" onkeyup="fun1()" />
<br/><br/>
Sum Result is : <input type="text" id="txt3" value="0" /><br/><br/>

<script type="text/javascript">
function fun1()
{
if (window.XMLHttpRequest)
{
var t1 = document.getElementById("txt1").value;
var t2 = document.getElementById("txt2").value;
obj1 = new XMLHttpRequest();
obj1.onreadystatechange = fun2;
obj1.open("POST", "Home/first?num1=" + t1 + "&num2=" + t2, true);
obj1.send();
}
}
function fun2()
{
if (obj1.readyState == 4)
{
document.getElementById("txt3").value = obj1.responseText;
}
}
</script>

(ii) Write in the “Home” Controller page as :

public ActionResult Index()


{
return View();
}

public ActionResult first(String num1,String num2)


{
string str = "";
try
{
str = "" + (int.Parse(num1) + int.Parse(num2));
}
catch
{
}
return Content(str);
}

Example of ajax for display records on the page after key press in the textbox :
(i) write in the “index.cshtml” view page as :

Type Name : <input type="text" id="txt_nm" onkeyup="fun1()" /><br/><hr/>


<div id="div1">
<h1>Ranjit Kumar</h1>
</div>
<script type="text/javascript">
function fun1()
{
if (window.XMLHttpRequest)
{
obj1 = new XMLHttpRequest();
obj1.onreadystatechange = fun2;
}
var t1 = document.getElementById("txt_nm").value;
obj1.open("POST", "Home/first?nm=" + t1, true);
obj1.send();
}
function fun2()
{
if (obj1.readyState == 4)
{
document.getElementById("div1").innerHTML = obj1.responseText;
}
}
</script>

(ii) Write in the “Home” Controller page as :

public ActionResult Index()


{
return View();
}

public ActionResult first(String nm)


{
SqlConnection con = new SqlConnection("server=india; database=amar;
integrated security=sspi");

SqlDataAdapter da = new SqlDataAdapter("select * from stud_info where


name like '" + nm + "%'", con);

DataTable dt = new DataTable();


da.Fill(dt);
String str = "<table style='width:50%; border:1px solid black'><tr><td
style='width:25%'>Roll</td><td style='width:25%'>Name</td><td
style='width:25%'>Address</td><td style='width:25%'>Phone</td></tr>";

foreach (DataRow row in dt.Rows)


{
str += "<tr><td>" + row["Roll"] + "</td><td>" + row[1] + "</td><td>" +
row["address"] + "</td><td>" + row[3] + "</td></tr>";
}
str += "</table>";
return Content(str);
}

Submit the Form using Ajax in MVC :


"BeginForm()" is an extension method that writes an opening "<form>" tag to the response.
"BeginForm()" is an extension method for both HtmlHelper and AjaxHelper classes. It returns
an MVCForm object from both HtmlHelper and AjaxHelper class instances so there is no more
difference but the AjaxHelper method submits the form asynchronously using JavaScript.

There are two types of the BeginForm() extension methods, they are:-

 Html.BeginForm()
 Ajax.BeginForm()

The behavior of both "Html.BeginForm()" and "Ajax.BeginForm()" although these are the
same and return the same MvcForm object.

Example of Ajax.BeginForm() method :

(i) Open a new MVC application.


(ii) Write the code in “Home” controller as :

public ActionResult Index()


{
return View();
}

public ActionResult first(String txt_roll,String txt_nm,String txt_add,String


txt_ph)
{
String str = "<h3>Roll : " + txt_roll + "</h3>";
str += "<h3>Name : " + txt_nm + "</h3>";
str += "<h3>Address : " + txt_add + "</h3>";
str += "<h3>Phone : " + txt_ph + "</h3>";
return Content(str);
}

(iii) Write the code in “index.cshtml” view page as :

<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"
type="text/javascript"></script>

Note: The above line may be write either in the “views/shared/_layout.cshtml” page
or “index.cshtml” view page.

@using (Ajax.BeginForm("first", "Home", new AjaxOptions { UpdateTargetId = "rkj" }))


{
<div id="rkj"></div>
<h3>Roll : @Html.TextBox("txt_roll") </h3>
<h3>Name : @Html.TextBox("txt_nm") </h3>
<h3>Address : @Html.TextBox("txt_add") </h3>
<h3>Phone : @Html.TextBox("txt_ph") </h3>
<input type="submit" value="Click Me" />
}

The output of Above program is:-


Before Submit Form After Submit Form

Creating Json Result using Model Class in MVC:


(i) Create a new MVC Application.
(ii) Add one Model file (Eg.: Class1.cs).
(iii) Edit the code in “Class1.cs” Model file as :--

public class student


{
public String Roll { get; set; }
public String Name { get; set; }
public String Address { get; set; }
public String Phone { get; set; }
public student(String p1 = "", String p2 = "", String p3 = "", String p4 = "")
{
Roll = p1;
Name = p2;
Address = p3;
Phone = p4;
}
}
public class class1
{
public List<student> get_data()
{
List<student> col = new List<student>();
for (int i = 1; i <= 25; i++)
{
col.Add(new student("R" + i, "Ranjit" + i, "Patna" + i, "568464" + i));
}
return (col);
}
}
(iv) Edit the code in “Home” controller page as :--

public JsonResult Index()


{
class1 c1 = new class1();
return Json(c1.get_data(), JsonRequestBehavior.AllowGet);
}
(v) Execute the above application.

The output of above program is :--

Displaying Large Amount of Data in JSON Format :


(i) Create a new MVC Application.
(ii) Add one Model file (Eg.: Class1.cs).
(iii) Edit the code in “Class1.cs” Model file as :--

public class student


{
public String Roll { get; set; }
public String Name { get; set; }
public String Address { get; set; }
public String Phone { get; set; }
public student(String p1 = "", String p2 = "", String p3 = "", String p4 = "")
{
Roll = p1;
Name = p2;
Address = p3;
Phone = p4;
}
}
public class class1
{
public List<student> get_data()
{
List<student> col = new List<student>();
for (int i = 1; i <= 55000; i++)
{
col.Add(new student("R" + i, "Ranjit" + i, "Patna" + i, "568464" + i));
}
return (col);
}
}

(iv) Edit the code in “Home” controller page as :--

public JsonResult Index()


{
class1 c1 = new class1();
return Json(c1.get_data(), JsonRequestBehavior.AllowGet);
}

(v) If we execute the above program then it will generate an error as :-

(vi) To eliminate the above error we have to “override” the “json” function in
“Home” controller as :-

public JsonResult Index()


{
class1 c1 = new class1();
return Json(c1.get_data(), JsonRequestBehavior.AllowGet);
}

protected override JsonResult Json(object data, string ct, System.Text.Encoding ce,


JsonRequestBehavior behavior)
{
return new JsonResult()
{
Data = data,
ContentType = ct,
ContentEncoding = ce,
JsonRequestBehavior = behavior,
MaxJsonLength = Int32.MaxValue
};
}

(vii) Execute the above application.

The output of above program is :


Displaying Database record in JSON Format:
(i) Create a new MVC Application.
(ii) Add one Model file (Eg.: Class1.cs).
(iii) Edit the code in “Class1.cs” Model file as :--

using System.Data.SqlClient;
using System.Data;
namespace MvcApplication10.Models
{
public class student
{
public String Roll { get; set; }
public String Name { get; set; }
public String Address { get; set; }
public String Phone { get; set; }
public student(String p1 = "", String p2 = "", String p3 = "", String p4 = "")
{
Roll = p1;
Name = p2;
Address = p3;
Phone = p4;
}
}
public class class1
{
SqlConnection con = new SqlConnection("server=india; database=ranjit;
integrated security=sspi");
public List<student> get_data()
{
SqlDataAdapter da = new SqlDataAdapter("select * from stud_info", con);
DataTable dt = new DataTable();
da.Fill(dt);
List<student> col = new List<student>();
foreach(DataRow row in dt.Rows)
{
col.Add(new student(row["Roll"].ToString(), row["name"].ToString(),
row["address"].ToString(), row["phone"].ToString()));
}
return (col);
}
}
}

(iv) Edit the code in “Home” controller page as :--

public JsonResult Index()


{
class1 c1 = new class1();
return Json(c1.get_data(), JsonRequestBehavior.AllowGet);
}

(v) Execute the above application.


Show Image Preview before uploading the image file :
(i) Write the code in “index.cshtml” view page as :-

<script src="~/Scripts/jquery-ui-1.8.20.js"></script>
<script type="text/javascript">
function showimagepreview(input) {
if (input.files && input.files[0]) {
var fr = new FileReader();
fr.onload = function (e) {
$('#img1').attr('src', e.target.result);
}
fr.readAsDataURL(input.files[0]);
}
}
</script>

<body>
<form id="form1" runat="server">
<input type="file" name="filUpload" id="filUpload"
onchange="showimagepreview(this)" />
<img id="img1" alt="uploaded image preview" />
</form>
</body>

Change Image after 1 seconds continuously without refreshing


page :
(i) Open a new MVC Application.
(ii) Store some images in the “solution explorer” within “image1” folder as :-

(iii) Create one Model file and then edit the code in model file as :

public class first


{
public String Id { get; set; }
public String Pict_Name { get; set; }

public first(String p1 = "", String p2 = "")


{
Id = p1;
Pict_Name = p2;
}
}
public class class1
{
public static List<first> get_data()
{
List<first> col = new List<first>();
for(int i=1;i<=10;i++)
{
col.Add(new first(""+i,"/image1/"+i+".jpg"));
}
return (col);
}
}

(iv) Edit the code in the “Home” controller as :-

public ActionResult Index()


{
return View();
}

public ActionResult test()


{
Random rnd = new Random();
int r = rnd.Next(1,10);
first f1 = class1.get_data()[r];
return PartialView("View1",f1);
}
(v) Write the code in the “index.cshtml” view page as :-

<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(function ()
{
setInterval(function () { $('#div1').load('/Home/test'); }, 1000);
});

</script>
<div id="div1">

</div>
<input type="button" id="btn1" value="Click Me"/>
(vi) Add one “View1.cshtml” View page for partially refresh.
(vii) Edit the code in the “View1.cshtml” view page as :-

@model MvcApplication10.Models.first

<img src="@Model.Pict_Name" alt="@Model.Id" style="width:200px; height:200px" />

(viii) Execute the above application.

Example of update progress in ajax :


(i) Create a new MVC application.
(ii) Copy any animated “pict1.gif” picture in the “Image” folder of Solution
Explorer.
(iii) Write the code in “index.cshtml” view page.

<script src="~/Scripts/jquery-1.7.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btn1").click(function () {
$.ajax(
{
url: "Home/first",
dataType: 'text',
success: fun1,
beforeSend:fun2
});
});
});

function fun1(rk) {

$("#div1").html(rk);
}
function fun2()
{
$("#img1").attr("style","visibility:visible");
}
</script>
<div id="div1">
<img src="~/Images/pict1.gif" id="img1" style="visibility:hidden" />
</div>
<input type="button" id="btn1" value="Click Me"/>

(iv) Write the code in “first.cshtml” view page as :-

@for (var i = 1; i <= 25000; i++)


{
<h3>ranjit @i</h3>
}

(v) Execute the above application.

The output of above program is :--

You might also like