Showing posts with label ajax jquery. Show all posts
Showing posts with label ajax jquery. Show all posts

Monday, 12 December 2011

Cannot read JSON object property - MVC AJAX

If you're ever banging your head against a brick wall trying to figure out why your javascript code is returning 'undefined' when you attempt to 'alert()' a JSON object property...particuarly if you know that the server is returning an error code, try inspecting the the JSON object via 'responseText'

eg JSON: { "propertyName" : "propertyValue" }

Instead of accessing the property like:

alert(propertyName.propertyValue);

Try:

alert(responseText.propertyName.propertyValue);

The reason for this is: [google "can't access JSON object responseText"]

Friday, 22 July 2011

Ajax with jQuery

Needed a quick reference for future use of Ajax utilising the jQuery framework.

After a lot of research i've collated this quick guide based on a good article @ sitepoint: Easy Ajax with jQuery Article

SitePoint offers a good introduction to Ajax

Creating a Simple Input control that sends data back to the Server

First, all we need is an <input> element on our page - i'm going to use a radio button at this stage and send back to the server its 'value' attribute the moment it is clicked by the user.

<input id="rad" type="radio" value="34553" />

Then we need to bind to the Radio Button's click event.

(NB: Notice that we don't put anything about the click event in the markup - all the behavior can be separated from the content this way!)

$("#rad").click(function(){
  $('#myForm').ajaxForm(function() { 
     // do something on success...
  });
});

NB: Could have used the ajaxForm 'Options' parameter to denote the success function. See this reference about What Are The ajaxForm Options?

The above is equivalent to:

var options = {
    method: 'POST',
    url: 'MyForm.aspx',
    success: function(response) {
     // do something on success...
    }
};
$("#rad").click(function(){
  $('#myForm').ajaxForm(options);
});

This Stack Overflow post discusses ways to trigger a Server Side ASP.Net Event via AJAX and jQuery

and links to this article where the solution method was inspired from: Using jQuery to directly call ASP.NET AJAX page methods