a developer's notes – a semi-technical web development BLOG

May 23, 2013

Sample jquery ajax Calls

Filed under: Javascript / JQuery — Duy Nguyen @ 3:47 pm
Tags: , , ,

Sample jQuery ajax POST:

$('#buttonId').click(function () {
	$.ajax({
		type: 'POST',
		url: ApplicationRoot + 'controller/PostMethod',
		data: JSON.stringify({ Name: $('#Name').val(), Address: $('#Address').val() }),
		contentType: 'application/json',
		dataType: 'json',
		success: aCallBackFunctionName
	});
});

[HttpPost]
public JsonResult PostMethod(string Name, string Address)
{
	if (!String.IsNullOrEmpty(Name) && !String.IsNullOrEmpty(Address))
	{
        //TODO: Save the data in database
        return Json("ok");
	}
    else
	{
        return "Please complete the form.";
	}
}

Sample jQuery ajax GET:

$.ajax({
	url: ApplicationRoot + 'controller/GetMethod',
	type: 'GET',
	data: { selectedId : id},
	dataType: 'json',
	error: function (xhr, textStatus, errorThrown) {
		//alert(xhr.status);
		//alert(thrownError);
	},
	success: function (data) {
		//do something
	}
});

[HttpGet]
public JsonResult GetMethod()
{
	// do something
	var data = 1;
	return Json(data, JsonRequestBehavior.AllowGet);
}

If you’re using the Anti-Forgery Requests for HttpPost then do this..

		var tokenVal = $('input[name=__RequestVerificationToken]').val();
		
        $('#buttonId').click(function () {
            $.ajax({
                type: 'POST',
                url: ApplicationRoot + 'controller/PostMethod',
                data: JSON.stringify({ filter: $('#Filter').val(), itemIDs: $('#items').val(), __RequestVerificationToken : tokenVal}),
                contentType: 'application/json',
                dataType: 'json',
                success: aCallBackFunctionName
            });
        });

[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult PostMethod(string Name, string Address)
{
	if (!String.IsNullOrEmpty(Name) && !String.IsNullOrEmpty(Address))
	{
        //TODO: Save the data in database
        return Json("ok");
	}
    else
	{
        return "Please complete the form.";
	}
}
Advertisements

2 Comments »

  1. Reblogged this on Sutoprise Avenue, A SutoCom Source.

    Comment by SutoCom — May 25, 2013 @ 6:29 am | Reply

  2. Reblogged this on Frendy Lee Educational Spot.

    Comment by Frendy Lee — May 28, 2013 @ 10:51 pm | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: