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

September 5, 2011

Javascript Ajax Calls

Filed under: Javascript / JQuery — Duy Nguyen @ 1:34 pm
Tags: , , ,

You need to add a Web Method attribute on your methods on the code behind. This allows your Javascript aJax calls to these methods.

September 2, 2011

A Sample AJAX Script

Filed under: Javascript / JQuery — Duy Nguyen @ 2:51 am
Tags: , , , ,

Here is a sample AJax application. This was taken from “Ajax for Dummies”.

Here a user clicks on the “Display Message” button and it retrieves text from a text file and changes the text on the web page.

The application:


Here is the code:

<script language = “javascript”>

//Create the XMLHttpRequest object
var XMLHttpRequestObject = false;
 
if (window.XMLHttpRequest) {
    XMLHttpRequestObject = new XMLHttpRequest();
}
else if (window.ActiveXObject) { //For Internet Explorer only
    XMLHttpRequestObject = new ActiveXObject(“Microsoft.XMLHTTP”);
}
 
//a function that takes a path for the datasource location and the div's ID to put the retrieved data into
function getData(dataSource, divID){
    if(XMLHttpRequestObject) {

        //find the div to put the data into
        var obj = document.getElementById(divID);

        //open(“method”, “URL”[, asyncFlag[, “userName”[, “password”]]])
        XMLHttpRequestObject.open(“GET”, dataSource); 

        //Set up the anonymous function to call when ready. The actual request isn't until later
        XMLHttpRequestObject.onreadystatechange = function() 
        {   
            //readState[ 0:uninitialize, 1:loading, 2:loaded, 3:interactive, 4:complete ]
            //status 200 = OK
            if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
                //data retrieved sucessfully so put the retrieved data into the div
                obj.innerHTML = XMLHttpRequestObject.responseText;
            }
        }
       
        //request server for data. And the anonymous function will handle the response back from the server
        XMLHttpRequestObject.send(null); //null is only used for GETs
    }
}

</script>
 
<body>
 
<H1>Fetching data with Ajax</H1>
    <form>
        <input type = 'button' value = 'Display Message' onclick = 'getData(‘http://localhost/ch01/data.txt’,‘targetDiv’)'>
    </form>
 
    <div id='targetDiv'>
        <p>The fetched data will go here.</p>
    </div>
 
</body>

The text file data.txt, contains:

This text was fetched using Ajax.

I hope this was simple enough. The interesting thing about this is that the function to handle the response is setup before the actual request call. Enjoy!

Blog at WordPress.com.