Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Please be gentle, as I'm still new to web programming and -very- new to Ajax!

I've created a C# function which extracts data from an mssql database, formats it to a json string and returns that. Now I need to make a call from my javascript (jQuery) slider through an aspx page that is related to the C# code file.

I have actually never done anything like this before, from what I could tell by googling I need to use xmlHttpRequest, but how exactly do I make the function get hold of this string?

It would be awesome if someone had some example code that shows how this works.

share|improve this question
add comment

2 Answers

up vote 1 down vote accepted

It's relatively easy with jQuery if you mark the C# function as a [WebMethod] or make it part of a ASP.NET webservice. Both these techniques make it easy to have the response automatically converted into a JSON object by ASP.NET, which makes processing on the client easier (IMHO).

The example below is if the page has a WebMethod named GetData, but it's trivial to change the URL if you create a service.

$.ajax({ url: "somepage.aspx/GetData", 
         method: "POST", // post is safer, but could also be GET
         data: {}, // any data (as a JSON object) you want to pass to the method
         success: function() { alert('We did it!'); }
});

On the server:

[WebMethod]
public static object GetData() {
    // query the data...
    // return as an anonymous object, which ASP.NET converts to JSON
    return new { result = ... };
}
share|improve this answer
    
the webmethod needs to be static if its inside a page, but if its in a webservice no need to make it static. –  Amr ElGarhy Mar 1 '10 at 15:02
    
Great tip! Thanks so much :] –  cc0 Mar 1 '10 at 15:23
add comment

The simplest way to do this is to convert your function into an ASHX file that writes the JSON to the HTTP response.

You can then call it using XmlHttpRequest, although you can call it much more easily using jQuery.

You can call it with jQuery like this:

$.get("/YourFile.ashx", function(obj) { ... }, "json");
share|improve this answer
    
I will look into that right away, thank you! :] –  cc0 Mar 1 '10 at 15:24
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.