Search Results

Search found 8063 results on 323 pages for 'ajax'.

Page 2/323 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Can somebody explain the differences, status and future of the various ASP.NET AJAX libraries and to

    - by tjrobinson
    I'm confused about the differences and relationships between the various Microsoft ASP.NET AJAX components/libraries/toolkits and particularly the naming of them. It starts off relatively simple with ASP.NET AJAX itself: ASP.NET AJAX 1.0 (available for ASP.NET 2.0 in a separate package called ASP.NET 1.0 Extensions) ASP.NET AJAX 3.5 (included with ASP.NET 3.5) ASP.NET AJAX 4.0 (included with ASP.NET 4.0) Then come the various projects on CodePlex and elsewhere: ASP.NET AJAX Control Toolkit (aka Original Ajax Control Toolkit) Samples CodePlex It seems that the September 2009 Release is the final release of the Original Ajax Control Toolkit and that it's been superseded by... Ajax Control Toolkit in ASP.NET Ajax Library It looks like the old ASP.NET AJAX Control Toolkit has now become part of a larger ASP.NET Ajax Library but is still maintained seperately on CodePlex. This release is in beta at time of writing so presumably if I want to use the "Control Toolkit" I should stick with the September 2009 Release of the Original ASP.NET AJAX Control Toolkit CodePlex Microsoft Ajax Library Preview Is this the same as the ASP.NET Ajax Library mentioned above just with a confusing name variation? Is the "Control Toolkit" included in Preview 6 and is it older newer or older than the code in Ajax Control Toolkit in ASP.NET Ajax Library? CodePlex Microsoft ASP.NET Ajax Wiki - note the inconsistent insertion of ASP.NET into the name Links to useful articles, roadmaps would be useful.

    Read the article

  • jQuery Templates on Microsoft Ajax CDN

    - by Stephen Walther
    The beta version of the jQuery Templates plugin is now hosted on the Microsoft Ajax CDN. You can start using the jQuery Templates plugin in your application by referencing both jQuery 1.4.2 and jQuery Templates from the CDN. Here are the two script tags that you will want to use when developing an application: <script type="text/javascript" src=”http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js”></script> <script type="text/javascript" src=”http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.js”></script> In addition, minified versions of both files are available from the CDN: <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script> Here’s a full code sample of using jQuery Templates from the CDN to display pictures of cats from Flickr: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Cats</title> <style type="text/css"> html { background-color:Orange; } #catBox div { width:250px; height:250px; border:solid 1px black; background-color:White; margin:5px; padding:5px; float:left; } #catBox img { width:200px; height: 200px; } </style> </head> <body> <h1>Cat Photos!</h1> <div id="catBox"></div> <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script> <script id="catTemplate" type="text/x-jquery-tmpl"> <div> <b>${title}</b> <br /> <img src="${media.m}" /> </div> </script> <script type="text/javascript"> var url = "http://api.flickr.com/services/feeds/groups_pool.gne?id=44124373027@N01&lang=en-us&format=json&jsoncallback=?"; // Grab some flickr images of cats $.getJSON(url, function (data) { // Format the data using the catTemplate template $("#catTemplate").tmpl(data.items).appendTo("#catBox"); }); </script> </body> </html> This page displays a list of cats retrieved from Flickr: Notice that the cat pictures are retrieved and rendered with just a few lines of code: var url = "http://api.flickr.com/services/feeds/groups_pool.gne?id=44124373027@N01&lang=en-us&format=json&jsoncallback=?"; // Grab some flickr images of cats $.getJSON(url, function (data) { // Format the data using the catTemplate template $("#catTemplate").tmpl(data.items).appendTo("#catBox"); }); The final line of code, the one that calls the tmpl() method, uses the Templates plugin to render the cat photos in a template named catTemplate. The catTemplate template is contained within a SCRIPT element with type="text/x-jquery-tmpl". The jQuery Templates plugin is an “official” jQuery plugin which will be included in jQuery 1.5 (the next major release of jQuery). You can read the full documentation for the plugin at the jQuery website: http://api.jquery.com/category/plugins/templates/ The jQuery Templates plugin is still beta so we would really appreciate your feedback on the plugin. Let us know if you use the Templates plugin in your website.

    Read the article

  • jquery - loading inline javascript via AJAX

    - by yaya3
    I have thrown together a quick prototype to try and establish a few very basic truths regarding what inline JavaScript can do when it is loaded with AJAX: index.html <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> </head> <body> <script type="text/javascript"> $('p').css('color','white'); alert($('p').css('color')); // DISPLAYS FIRST but is "undefined" $(document).ready(function(){ $('#ajax-loaded-content-wrapper').load('loaded-by-ajax.html', function(){ $('p').css('color','grey'); alert($('p').css('color')); // DISPLAYS LAST (as expected) }); $('p').css('color','purple'); alert($('p').css('color')); // DISPLAYS SECOND }); </script> <p>Content not loaded by ajax</p> <div id="ajax-loaded-content-wrapper"> </div> </body> </html> loaded-by-ajax.html <p>Some content loaded by ajax</p> <script type="text/javascript"> $('p').css('color','yellow'); alert($('p').css('color')); // DISPLAYS THIRD $(document).ready(function(){ $('p').css('color','pink'); alert($('p').css('color')); // DISPLAYS FOURTH }); </script> <p>Some content loaded by ajax</p> <script type="text/javascript"> $(document).ready(function(){ $('p').css('color','blue'); alert($('p').css('color')); // DISPLAYS FIFTH }); $('p').css('color','green'); alert($('p').css('color')); // DISPLAYS SIX </script> <p>Some content loaded by ajax</p> Notes: a) All of the above (except the first) successfully change the colour of all the paragraphs (in firefox 3.6.3). b) I've used alert instead of console.log as console is undefined when called in the 'loaded' HTML. Truths(?): $(document).ready() does not treat the 'loaded' HTML as a new document, or reread the entire DOM tree including the loaded HTML, it is pointless inside AJAX loaded content JavaScript that is contained inside 'loaded' HTML can effect the style of existing DOM nodes One can successfully use the jQuery library inside 'loaded' HTML to effect the style of existing DOM nodes One can not use the firebug inside 'loaded' HTML can effect the existing DOM (proven by Note a) Am I correct in deriving these 'truths' from my tests (test validity)? If not, how would you test for these?

    Read the article

  • How do you implement a combobox filter using AJAX in ASP.NET?

    - by geocine
    To save some time on discussing my problem you could check the demo below: http://demos.telerik.com/aspnet-ajax/combobox/examples/functionality/filteringcombo/defaultcs.aspx I already checked the ListBoxExtender on the Ajax Control Toolkit but it wouldn't give me fine results. What I want to do is to filter a listbox which is populated by over 3000 records from the database upon typing. It should not only filter the listbox with the starting letters but also the group of characters which could be found in between each item on the list. The list is a list of Item Name as a value and an Item Code as the key.

    Read the article

  • jquery - establishing truths when loading inline javascript via AJAX

    - by yaya3
    I have thrown together a quick prototype to try and establish a few very basic truths regarding what inline JavaScript can do when it is loaded with AJAX: index.html <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> </head> <body> <script type="text/javascript"> $('p').css('color','white'); alert($('p').css('color')); // DISPLAYS FIRST but is "undefined" $(document).ready(function(){ $('#ajax-loaded-content-wrapper').load('loaded-by-ajax.html', function(){ $('p').css('color','grey'); alert($('p').css('color')); // DISPLAYS LAST (as expected) }); $('p').css('color','purple'); alert($('p').css('color')); // DISPLAYS SECOND }); </script> <p>Content not loaded by ajax</p> <div id="ajax-loaded-content-wrapper"> </div> </body> </html> loaded-by-ajax.html <p>Some content loaded by ajax</p> <script type="text/javascript"> $('p').css('color','yellow'); alert($('p').css('color')); // DISPLAYS THIRD $(document).ready(function(){ $('p').css('color','pink'); alert($('p').css('color')); // DISPLAYS FOURTH }); </script> <p>Some content loaded by ajax</p> <script type="text/javascript"> $(document).ready(function(){ $('p').css('color','blue'); alert($('p').css('color')); // DISPLAYS FIFTH }); $('p').css('color','green'); alert($('p').css('color')); // DISPLAYS SIX </script> <p>Some content loaded by ajax</p> Notes: a) All of the above (except the first) successfully change the colour of all the paragraphs (in firefox 3.6.3). b) I've used alert instead of console.log as console is undefined when called in the 'loaded' HTML. Truths(?): $(document).ready() does not treat the 'loaded' HTML as a new document, or reread the entire DOM tree including the loaded HTML JavaScript that is contained inside 'loaded' HTML can effect the style of existing DOM nodes One can successfully use the jQuery library inside 'loaded' HTML to effect the style of existing DOM nodes One can not use the firebug inside 'loaded' HTML can effect the existing DOM (proven by Note a) Am I correct in deriving these 'truths' from my tests (test validity)? If not, how would you test for these?

    Read the article

  • New January 2013 Release of the Ajax Control Toolkit

    - by Stephen.Walther
    I am super excited to announce the January 2013 release of the Ajax Control Toolkit! I have one word to describe this release and that word is “Charts” – we’ve added lots of great new chart controls to the Ajax Control Toolkit. You can download the new release directly from http://AjaxControlToolkit.CodePlex.com – or, just fire the following command from the Visual Studio Library Package Manager Console Window (NuGet): Install-Package AjaxControlToolkit You also can view the new chart controls by visiting the “live” Ajax Control Toolkit Sample Site. 5 New Ajax Control Toolkit Chart Controls The Ajax Control Toolkit contains five new chart controls: the AreaChart, BarChart, BubbleChart, LineChart, and PieChart controls. Here is a sample of each of the controls: AreaChart: BarChart: BubbleChart: LineChart: PieChart: We realize that people love to customize the appearance of their charts so all of the chart controls include properties such as color properties. The chart controls render the chart on the browser using SVG. The chart controls are compatible with any browser which supports SVG including Internet Explorer 9 and new and recent versions of Google Chrome, Mozilla Firefox, and Apple Safari. (If you attempt to display a chart on a browser which does not support SVG then you won’t get an error – you just won’t get anything). Updates to the HTML Sanitizer If you are using the HtmlEditorExtender on a public-facing website then it is really important that you enable the HTML Sanitizer to prevent Cross-Site Scripting (XSS) attacks. The HtmlEditorExtender uses the HTML Sanitizer by default. The HTML Sanitizer strips out any suspicious content (like JavaScript code and CSS expressions) from the HTML submitted with the HtmlEditorExtender. We followed the recommendations of OWASP and ha.ckers.org to identify suspicious content. We updated the HTML Sanitizer with this release to protect against new types of XSS attacks. The HTML Sanitizer now has over 220 unit tests. The Ajax Control Toolkit team would like to thank Gil Cohen who helped us identify and block additional XSS attacks. Change in Ajax Control Toolkit Version Format We ran out of numbers. The Ajax Control Toolkit was first released way back in 2006. In previous releases, the version of the Ajax Control Toolkit followed the format: Release Year + Date. So, the previous release was 60919 where 6 represented the 6th release year and 0919 represent September 19. Unfortunately, the AssembyVersion attribute uses a UInt16 data type which has a maximum size of 65,534. The number 70123 is bigger than 65,534 so we had to change our version format with this release. Fortunately, the AssemblyVersion attribute actually accepts four UInt16 numbers so we used another one. This release of the Ajax Control Toolkit is officially version 7.0123. This new version format should work for another 65,000 years. And yes, I realize that 7.0123 is less than 60,919, but we ran out of numbers. Summary I hope that you find the chart controls included with this latest release of the Ajax Control Toolkit useful. Let me know if you use them in applications that you build. And, let me know if you run into any issues using the new chart controls. Next month, back to improving the File Upload control – more exciting stuff.

    Read the article

  • Understanding Ajax crawling of search site

    - by vacuum
    I have a couple of questions about Ajax crawling of site, which is kind of search engine itself. The base article explains the mechanism of making AJAX application crawlable. All this stuff with HTML-snapshots is clear and easy to implement, but I cant understand where will Google bot will get "the crawler finds a pretty AJAX URL"( ie www.example.com/ajax.html#key=value) to work with. First thing, that came on mind - is breadcrumb. In sitemap we can specify pages with breadcrumb on it. so bot will go to these pages and get HTML-snapshots from here. But I'm sure, there are exists other ways to give bot this "pretty AJAX URL". In our case, we have simple search site, where user enters keyword, presses "Find", js execute Ajax request, receives JSON reponce and fill page with results(without any refresh of course). In this case - how to make google bot crawle all the presults in addition to sitemap? Is there some example of solution, described in article above?

    Read the article

  • How would you pass objects with MVC and jQuery AJAX?

    - by Ken
    I am finally experimenting and trying to learn MVC after years of asp.net. I am used to using asp.net AJAX PageMethods where you can pass an object that automagically gets parsed to whatever type the parameter is in that method. Javascript: PageMethods.AddPerson({First:"John",Last:"Doe"}); Code-Behind: [WebMethod] public static Result AddPerson(Person objPerson) { return Person.Save(); } How would do this using MVC and jQuery? Did just have to send strings and parse the json to object?

    Read the article

  • To Ajax or Not to Ajax a listing page

    - by kaivalya
    Here i am talking about product listing pages where there are multiple filters that filter the list of products appearing on the page like product types, categories price range etc. I have done such pages using both ajax and no ajax way in the past. What I like about using ajax in such page is that, when filters are selected I only update the section that contains the product list. There is no need to refresh the whole page which could end up re-loading the images on top bar, banners etc and slow down the user performance. Ajax way in my opinion becomes more compact and responsive from user experience. Down side for ajax route for me is; since filter states are not maintained in the URL I end up maintaining them on the server. This becomes complicated if I want to handle multi window scenarios and it is also costly to maintain such state on server memory for each session. Not using ajax and simply keeping all filter values on url and refreshing the page is quite simple but the luxury of refreshing only the pane that really needs to be refreshed is lost. Lately I am seeing a lot of large scale e-commerce sites that are using non-ajax approach on their listing pages and this is making me question one more time if it might be more efficient to build non-ajax listing make due to the long term maintenance ease and sacrifice a little bit from user experience. I am about to start implementing a new listing page for a product which I have the flexibility to go either way and I would appreciate your inputs.

    Read the article

  • Using the West Wind Web Toolkit to set up AJAX and REST Services

    - by Rick Strahl
    I frequently get questions about which option to use for creating AJAX and REST backends for ASP.NET applications. There are many solutions out there to do this actually, but when I have a choice - not surprisingly - I fall back to my own tools in the West Wind West Wind Web Toolkit. I've talked a bunch about the 'in-the-box' solutions in the past so for a change in this post I'll talk about the tools that I use in my own and customer applications to handle AJAX and REST based access to service resources using the West Wind West Wind Web Toolkit. Let me preface this by saying that I like things to be easy. Yes flexible is very important as well but not at the expense of over-complexity. The goal I've had with my tools is make it drop dead easy, with good performance while providing the core features that I'm after, which are: Easy AJAX/JSON Callbacks Ability to return any kind of non JSON content (string, stream, byte[], images) Ability to work with both XML and JSON interchangeably for input/output Access endpoints via POST data, RPC JSON calls, GET QueryString values or Routing interface Easy to use generic JavaScript client to make RPC calls (same syntax, just what you need) Ability to create clean URLS with Routing Ability to use standard ASP.NET HTTP Stack for HTTP semantics It's all about options! In this post I'll demonstrate most of these features (except XML) in a few simple and short samples which you can download. So let's take a look and see how you can build an AJAX callback solution with the West Wind Web Toolkit. Installing the Toolkit Assemblies The easiest and leanest way of using the Toolkit in your Web project is to grab it via NuGet: West Wind Web and AJAX Utilities (Westwind.Web) and drop it into the project by right clicking in your Project and choosing Manage NuGet Packages from anywhere in the Project.   When done you end up with your project looking like this: What just happened? Nuget added two assemblies - Westwind.Web and Westwind.Utilities and the client ww.jquery.js library. It also added a couple of references into web.config: The default namespaces so they can be accessed in pages/views and a ScriptCompressionModule that the toolkit optionally uses to compress script resources served from within the assembly (namely ww.jquery.js and optionally jquery.js). Creating a new Service The West Wind Web Toolkit supports several ways of creating and accessing AJAX services, but for this post I'll stick to the lower level approach that works from any plain HTML page or of course MVC, WebForms, WebPages. There's also a WebForms specific control that makes this even easier but I'll leave that for another post. So, to create a new standalone AJAX/REST service we can create a new HttpHandler in the new project either as a pure class based handler or as a generic .ASHX handler. Both work equally well, but generic handlers don't require any web.config configuration so I'll use that here. In the root of the project add a Generic Handler. I'm going to call this one StockService.ashx. Once the handler has been created, edit the code and remove all of the handler body code. Then change the base class to CallbackHandler and add methods that have a [CallbackMethod] attribute. Here's the modified base handler implementation now looks like with an added HelloWorld method: using System; using Westwind.Web; namespace WestWindWebAjax { /// <summary> /// Handler implements CallbackHandler to provide REST/AJAX services /// </summary> public class SampleService : CallbackHandler { [CallbackMethod] public string HelloWorld(string name) { return "Hello " + name + ". Time is: " + DateTime.Now.ToString(); } } } Notice that the class inherits from CallbackHandler and that the HelloWorld service method is marked up with [CallbackMethod]. We're done here. Services Urlbased Syntax Once you compile, the 'service' is live can respond to requests. All CallbackHandlers support input in GET and POST formats, and can return results as JSON or XML. To check our fancy HelloWorld method we can now access the service like this: http://localhost/WestWindWebAjax/StockService.ashx?Method=HelloWorld&name=Rick which produces a default JSON response - in this case a string (wrapped in quotes as it's JSON): (note by default JSON will be downloaded by most browsers not displayed - various options are available to view JSON right in the browser) If I want to return the same data as XML I can tack on a &format=xml at the end of the querystring which produces: <string>Hello Rick. Time is: 11/1/2011 12:11:13 PM</string> Cleaner URLs with Routing Syntax If you want cleaner URLs for each operation you can also configure custom routes on a per URL basis similar to the way that WCF REST does. To do this you need to add a new RouteHandler to your application's startup code in global.asax.cs one for each CallbackHandler based service you create: protected void Application_Start(object sender, EventArgs e) { CallbackHandlerRouteHandler.RegisterRoutes<StockService>(RouteTable.Routes); } With this code in place you can now add RouteUrl properties to any of your service methods. For the HelloWorld method that doesn't make a ton of sense but here is what a routed clean URL might look like in definition: [CallbackMethod(RouteUrl="stocks/HelloWorld/{name}")] public string HelloWorld(string name) { return "Hello " + name + ". Time is: " + DateTime.Now.ToString(); } The same URL I previously used now becomes a bit shorter and more readable with: http://localhost/WestWindWebAjax/HelloWorld/Rick It's an easy way to create cleaner URLs and still get the same functionality. Calling the Service with $.getJSON() Since the result produced is JSON you can now easily consume this data using jQuery's getJSON method. First we need a couple of scripts - jquery.js and ww.jquery.js in the page: <!DOCTYPE html> <html> <head> <link href="Css/Westwind.css" rel="stylesheet" type="text/css" /> <script src="scripts/jquery.min.js" type="text/javascript"></script> <script src="scripts/ww.jquery.min.js" type="text/javascript"></script> </head> <body> Next let's add a small HelloWorld example form (what else) that has a single textbox to type a name, a button and a div tag to receive the result: <fieldset> <legend>Hello World</legend> Please enter a name: <input type="text" name="txtHello" id="txtHello" value="" /> <input type="button" id="btnSayHello" value="Say Hello (POST)" /> <input type="button" id="btnSayHelloGet" value="Say Hello (GET)" /> <div id="divHelloMessage" class="errordisplay" style="display:none;width: 450px;" > </div> </fieldset> Then to call the HelloWorld method a little jQuery is used to hook the document startup and the button click followed by the $.getJSON call to retrieve the data from the server. <script type="text/javascript"> $(document).ready(function () { $("#btnSayHelloGet").click(function () { $.getJSON("SampleService.ashx", { Method: "HelloWorld", name: $("#txtHello").val() }, function (result) { $("#divHelloMessage") .text(result) .fadeIn(1000); }); });</script> .getJSON() expects a full URL to the endpoint of our service, which is the ASHX file. We can either provide a full URL (SampleService.ashx?Method=HelloWorld&name=Rick) or we can just provide the base URL and an object that encodes the query string parameters for us using an object map that has a property that matches each parameter for the server method. We can also use the clean URL routing syntax, but using the object parameter encoding actually is safer as the parameters will get properly encoded by jQuery. The result returned is whatever the result on the server method is - in this case a string. The string is applied to the divHelloMessage element and we're done. Obviously this is a trivial example, but it demonstrates the basics of getting a JSON response back to the browser. AJAX Post Syntax - using ajaxCallMethod() The previous example allows you basic control over the data that you send to the server via querystring parameters. This works OK for simple values like short strings, numbers and boolean values, but doesn't really work if you need to pass something more complex like an object or an array back up to the server. To handle traditional RPC type messaging where the idea is to map server side functions and results to a client side invokation, POST operations can be used. The easiest way to use this functionality is to use ww.jquery.js and the ajaxCallMethod() function. ww.jquery wraps jQuery's AJAX functions and knows implicitly how to call a CallbackServer method with parameters and parse the result. Let's look at another simple example that posts a simple value but returns something more interesting. Let's start with the service method: [CallbackMethod(RouteUrl="stocks/{symbol}")] public StockQuote GetStockQuote(string symbol) { Response.Cache.SetExpires(DateTime.UtcNow.Add(new TimeSpan(0, 2, 0))); StockServer server = new StockServer(); var quote = server.GetStockQuote(symbol); if (quote == null) throw new ApplicationException("Invalid Symbol passed."); return quote; } This sample utilizes a small StockServer helper class (included in the sample) that downloads a stock quote from Yahoo's financial site via plain HTTP GET requests and formats it into a StockQuote object. Lets create a small HTML block that lets us query for the quote and display it: <fieldset> <legend>Single Stock Quote</legend> Please enter a stock symbol: <input type="text" name="txtSymbol" id="txtSymbol" value="msft" /> <input type="button" id="btnStockQuote" value="Get Quote" /> <div id="divStockDisplay" class="errordisplay" style="display:none; width: 450px;"> <div class="label-left">Company:</div> <div id="stockCompany"></div> <div class="label-left">Last Price:</div> <div id="stockLastPrice"></div> <div class="label-left">Quote Time:</div> <div id="stockQuoteTime"></div> </div> </fieldset> The final result looks something like this:   Let's hook up the button handler to fire the request and fill in the data as shown: $("#btnStockQuote").click(function () { ajaxCallMethod("SampleService.ashx", "GetStockQuote", [$("#txtSymbol").val()], function (quote) { $("#divStockDisplay").show().fadeIn(1000); $("#stockCompany").text(quote.Company + " (" + quote.Symbol + ")"); $("#stockLastPrice").text(quote.LastPrice); $("#stockQuoteTime").text(quote.LastQuoteTime.formatDate("MMM dd, HH:mm EST")); }, onPageError); }); So we point at SampleService.ashx and the GetStockQuote method, passing a single parameter of the input symbol value. Then there are two handlers for success and failure callbacks.  The success handler is the interesting part - it receives the stock quote as a result and assigns its values to various 'holes' in the stock display elements. The data that comes back over the wire is JSON and it looks like this: { "Symbol":"MSFT", "Company":"Microsoft Corpora", "OpenPrice":26.11, "LastPrice":26.01, "NetChange":0.02, "LastQuoteTime":"2011-11-03T02:00:00Z", "LastQuoteTimeString":"Nov. 11, 2011 4:20pm" } which is an object representation of the data. JavaScript can evaluate this JSON string back into an object easily and that's the reslut that gets passed to the success function. The quote data is then applied to existing page content by manually selecting items and applying them. There are other ways to do this more elegantly like using templates, but here we're only interested in seeing how the data is returned. The data in the object is typed - LastPrice is a number and QuoteTime is a date. Note about the date value: JavaScript doesn't have a date literal although the JSON embedded ISO string format used above  ("2011-11-03T02:00:00Z") is becoming fairly standard for JSON serializers. However, JSON parsers don't deserialize dates by default and return them by string. This is why the StockQuote actually returns a string value of LastQuoteTimeString for the same date. ajaxMethodCallback always converts dates properly into 'real' dates and the example above uses the real date value along with a .formatDate() data extension (also in ww.jquery.js) to display the raw date properly. Errors and Exceptions So what happens if your code fails? For example if I pass an invalid stock symbol to the GetStockQuote() method you notice that the code does this: if (quote == null) throw new ApplicationException("Invalid Symbol passed."); CallbackHandler automatically pushes the exception message back to the client so it's easy to pick up the error message. Regardless of what kind of error occurs: Server side, client side, protocol errors - any error will fire the failure handler with an error object parameter. The error is returned to the client via a JSON response in the error callback. In the previous examples I called onPageError which is a generic routine in ww.jquery that displays a status message on the bottom of the screen. But of course you can also take over the error handling yourself: $("#btnStockQuote").click(function () { ajaxCallMethod("SampleService.ashx", "GetStockQuote", [$("#txtSymbol").val()], function (quote) { $("#divStockDisplay").fadeIn(1000); $("#stockCompany").text(quote.Company + " (" + quote.Symbol + ")"); $("#stockLastPrice").text(quote.LastPrice); $("#stockQuoteTime").text(quote.LastQuoteTime.formatDate("MMM dd, hh:mmt")); }, function (error, xhr) { $("#divErrorDisplay").text(error.message).fadeIn(1000); }); }); The error object has a isCallbackError, message and  stackTrace properties, the latter of which is only populated when running in Debug mode, and this object is returned for all errors: Client side, transport and server side errors. Regardless of which type of error you get the same object passed (as well as the XHR instance optionally) which makes for a consistent error retrieval mechanism. Specifying HttpVerbs You can also specify HTTP Verbs that are allowed using the AllowedHttpVerbs option on the CallbackMethod attribute: [CallbackMethod(AllowedHttpVerbs=HttpVerbs.GET | HttpVerbs.POST)] public string HelloWorld(string name) { … } If you're building REST style API's this might be useful to force certain request semantics onto the client calling. For the above if call with a non-allowed HttpVerb the request returns a 405 error response along with a JSON (or XML) error object result. The default behavior is to allow all verbs access (HttpVerbs.All). Passing in object Parameters Up to now the parameters I passed were very simple. But what if you need to send something more complex like an object or an array? Let's look at another example now that passes an object from the client to the server. Keeping with the Stock theme here lets add a method called BuyOrder that lets us buy some shares for a stock. Consider the following service method that receives an StockBuyOrder object as a parameter: [CallbackMethod] public string BuyStock(StockBuyOrder buyOrder) { var server = new StockServer(); var quote = server.GetStockQuote(buyOrder.Symbol); if (quote == null) throw new ApplicationException("Invalid or missing stock symbol."); return string.Format("You're buying {0} shares of {1} ({2}) stock at {3} for a total of {4} on {5}.", buyOrder.Quantity, quote.Company, quote.Symbol, quote.LastPrice.ToString("c"), (quote.LastPrice * buyOrder.Quantity).ToString("c"), buyOrder.BuyOn.ToString("MMM d")); } public class StockBuyOrder { public string Symbol { get; set; } public int Quantity { get; set; } public DateTime BuyOn { get; set; } public StockBuyOrder() { BuyOn = DateTime.Now; } } This is a contrived do-nothing example that simply echoes back what was passed in, but it demonstrates how you can pass complex data to a callback method. On the client side we now have a very simple form that captures the three values on a form: <fieldset> <legend>Post a Stock Buy Order</legend> Enter a symbol: <input type="text" name="txtBuySymbol" id="txtBuySymbol" value="GLD" />&nbsp;&nbsp; Qty: <input type="text" name="txtBuyQty" id="txtBuyQty" value="10" style="width: 50px" />&nbsp;&nbsp; Buy on: <input type="text" name="txtBuyOn" id="txtBuyOn" value="<%= DateTime.Now.ToString("d") %>" style="width: 70px;" /> <input type="button" id="btnBuyStock" value="Buy Stock" /> <div id="divStockBuyMessage" class="errordisplay" style="display:none"></div> </fieldset> The completed form and demo then looks something like this:   The client side code that picks up the input values and assigns them to object properties and sends the AJAX request looks like this: $("#btnBuyStock").click(function () { // create an object map that matches StockBuyOrder signature var buyOrder = { Symbol: $("#txtBuySymbol").val(), Quantity: $("#txtBuyQty").val() * 1, // number Entered: new Date() } ajaxCallMethod("SampleService.ashx", "BuyStock", [buyOrder], function (result) { $("#divStockBuyMessage").text(result).fadeIn(1000); }, onPageError); }); The code creates an object and attaches the properties that match the server side object passed to the BuyStock method. Each property that you want to update needs to be included and the type must match (ie. string, number, date in this case). Any missing properties will not be set but also not cause any errors. Pass POST data instead of Objects In the last example I collected a bunch of values from form variables and stuffed them into object variables in JavaScript code. While that works, often times this isn't really helping - I end up converting my types on the client and then doing another conversion on the server. If lots of input controls are on a page and you just want to pick up the values on the server via plain POST variables - that can be done too - and it makes sense especially if you're creating and filling the client side object only to push data to the server. Let's add another method to the server that once again lets us buy a stock. But this time let's not accept a parameter but rather send POST data to the server. Here's the server method receiving POST data: [CallbackMethod] public string BuyStockPost() { StockBuyOrder buyOrder = new StockBuyOrder(); buyOrder.Symbol = Request.Form["txtBuySymbol"]; ; int qty; int.TryParse(Request.Form["txtBuyQuantity"], out qty); buyOrder.Quantity = qty; DateTime time; DateTime.TryParse(Request.Form["txtBuyBuyOn"], out time); buyOrder.BuyOn = time; // Or easier way yet //FormVariableBinder.Unbind(buyOrder,null,"txtBuy"); var server = new StockServer(); var quote = server.GetStockQuote(buyOrder.Symbol); if (quote == null) throw new ApplicationException("Invalid or missing stock symbol."); return string.Format("You're buying {0} shares of {1} ({2}) stock at {3} for a total of {4} on {5}.", buyOrder.Quantity, quote.Company, quote.Symbol, quote.LastPrice.ToString("c"), (quote.LastPrice * buyOrder.Quantity).ToString("c"), buyOrder.BuyOn.ToString("MMM d")); } Clearly we've made this server method take more code than it did with the object parameter. We've basically moved the parameter assignment logic from the client to the server. As a result the client code to call this method is now a bit shorter since there's no client side shuffling of values from the controls to an object. $("#btnBuyStockPost").click(function () { ajaxCallMethod("SampleService.ashx", "BuyStockPost", [], // Note: No parameters - function (result) { $("#divStockBuyMessage").text(result).fadeIn(1000); }, onPageError, // Force all page Form Variables to be posted { postbackMode: "Post" }); }); The client simply calls the BuyStockQuote method and pushes all the form variables from the page up to the server which parses them instead. The feature that makes this work is one of the options you can pass to the ajaxCallMethod() function: { postbackMode: "Post" }); which directs the function to include form variable POST data when making the service call. Other options include PostNoViewState (for WebForms to strip out WebForms crap vars), PostParametersOnly (default), None. If you pass parameters those are always posted to the server except when None is set. The above code can be simplified a bit by using the FormVariableBinder helper, which can unbind form variables directly into an object: FormVariableBinder.Unbind(buyOrder,null,"txtBuy"); which replaces the manual Request.Form[] reading code. It receives the object to unbind into, a string of properties to skip, and an optional prefix which is stripped off form variables to match property names. The component is similar to the MVC model binder but it's independent of MVC. Returning non-JSON Data CallbackHandler also supports returning non-JSON/XML data via special return types. You can return raw non-JSON encoded strings like this: [CallbackMethod(ReturnAsRawString=true,ContentType="text/plain")] public string HelloWorldNoJSON(string name) { return "Hello " + name + ". Time is: " + DateTime.Now.ToString(); } Calling this method results in just a plain string - no JSON encoding with quotes around the result. This can be useful if your server handling code needs to return a string or HTML result that doesn't fit well for a page or other UI component. Any string output can be returned. You can also return binary data. Stream, byte[] and Bitmap/Image results are automatically streamed back to the client. Notice that you should set the ContentType of the request either on the CallbackMethod attribute or using Response.ContentType. This ensures the Web Server knows how to display your binary response. Using a stream response makes it possible to return any of data. Streamed data can be pretty handy to return bitmap data from a method. The following is a method that returns a stock history graph for a particular stock over a provided number of years: [CallbackMethod(ContentType="image/png",RouteUrl="stocks/history/graph/{symbol}/{years}")] public Stream GetStockHistoryGraph(string symbol, int years = 2,int width = 500, int height=350) { if (width == 0) width = 500; if (height == 0) height = 350; StockServer server = new StockServer(); return server.GetStockHistoryGraph(symbol,"Stock History for " + symbol,width,height,years); } I can now hook this up into the JavaScript code when I get a stock quote. At the end of the process I can assign the URL to the service that returns the image into the src property and so force the image to display. Here's the changed code: $("#btnStockQuote").click(function () { var symbol = $("#txtSymbol").val(); ajaxCallMethod("SampleService.ashx", "GetStockQuote", [symbol], function (quote) { $("#divStockDisplay").fadeIn(1000); $("#stockCompany").text(quote.Company + " (" + quote.Symbol + ")"); $("#stockLastPrice").text(quote.LastPrice); $("#stockQuoteTime").text(quote.LastQuoteTime.formatDate("MMM dd, hh:mmt")); // display a stock chart $("#imgStockHistory").attr("src", "stocks/history/graph/" + symbol + "/2"); },onPageError); }); The resulting output then looks like this: The charting code uses the new ASP.NET 4.0 Chart components via code to display a bar chart of the 2 year stock data as part of the StockServer class which you can find in the sample download. The ability to return arbitrary data from a service is useful as you can see - in this case the chart is clearly associated with the service and it's nice that the graph generation can happen off a handler rather than through a page. Images are common resources, but output can also be PDF reports, zip files for downloads etc. which is becoming increasingly more common to be returned from REST endpoints and other applications. Why reinvent? Obviously the examples I've shown here are pretty basic in terms of functionality. But I hope they demonstrate the core features of AJAX callbacks that you need to work through in most applications which is simple: return data, send back data and potentially retrieve data in various formats. While there are other solutions when it comes down to making AJAX callbacks and servicing REST like requests, I like the flexibility my home grown solution provides. Simply put it's still the easiest solution that I've found that addresses my common use cases: AJAX JSON RPC style callbacks Url based access XML and JSON Output from single method endpoint XML and JSON POST support, querystring input, routing parameter mapping UrlEncoded POST data support on callbacks Ability to return stream/raw string data Essentially ability to return ANYTHING from Service and pass anything All these features are available in various solutions but not together in one place. I've been using this code base for over 4 years now in a number of projects both for myself and commercial work and it's served me extremely well. Besides the AJAX functionality CallbackHandler provides, it's also an easy way to create any kind of output endpoint I need to create. Need to create a few simple routines that spit back some data, but don't want to create a Page or View or full blown handler for it? Create a CallbackHandler and add a method or multiple methods and you have your generic endpoints.  It's a quick and easy way to add small code pieces that are pretty efficient as they're running through a pretty small handler implementation. I can have this up and running in a couple of minutes literally without any setup and returning just about any kind of data. Resources Download the Sample NuGet: Westwind Web and AJAX Utilities (Westwind.Web) ajaxCallMethod() Documentation Using the AjaxMethodCallback WebForms Control West Wind Web Toolkit Home Page West Wind Web Toolkit Source Code © Rick Strahl, West Wind Technologies, 2005-2011Posted in ASP.NET  jQuery  AJAX   Tweet (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Executing AJAX scripts within an AJAX response

    - by KcYxA
    Hi there, I'm having trouble using AJAX page updates along with other AJAX scripts. During a normal page load, the AJAX scripts (picture scrolling and picture thumbnails) work fine. But when I update a page with AJAX, these scripts (usually loaded in the header of the initial page load) stop working. I am wondering if this is specific to these scripts and I need to look into them deeper to resolve/re-write or if I am missing something more generic in combining AJAX page updates with AJAX scripts the returned code relies on. Embedded javascript runs fine. Thanks for your ideas! PS: The scripts I am using are from www.dynamicdrive.com are: 1) stepcarousel (http://www.dynamicdrive.com/dynamicindex4/stepcarousel.htm) and 23) thumbnailviewer (http://www.dynamicdrive.com/dynamicindex4/thumbnail.htm) from the

    Read the article

  • AJAX 4 no ASP.NET 4 Web Application

    - by renatohaddad
    Andei fazendo uns testes no AJAX Control Toolkit 4 que deverá ser usado com o ASP.NET 4 no Visual Studio .NET 2010 e confesso que gostei muito. O link para download é http://www.asp.net/ajaxlibrary/act.ashx e todas as instruções constam no site. Notei que há diversos controles novos e um que me chamou a atenção foi o de Upload assíncrono para controlar os uploads de arquivos para o server. Vale a pena estudar um pouco estas novidades. Para quem já usava o AJAX no ASP.NET 3.5, a idéia do Toolkit é igual, exceto a adição de novos controles. Com o AJAX vc pode mudar todo o comportamento da sua aplicação WEB, requisições no server passam a ser menos frequentes, o layout ajuda e muito com os controles do AJAX. Nativamente no VS 2010 já há o AJAX que a MS suporta nativamente (ScriptManager, UpdatePanel, UpdateProgress, etc), mas vale a pena implementar alguns controles do Toolkit. Bons estudos!

    Read the article

  • ASP.NET AJAX and my axe!

    - by Marlon
    So, I'm seriously considering axing ASP.NET AJAX from my future projects as I honestly feel it's too bloated, and at times convoluted. I'm also starting to feel it is a dying library in the .NET framework as I hardly see any quality components from the open-source community. All the kick-ass components are usually equally bloated commercial components... It was cool at first, but now I tend to get annoyed with it more than anything else. I'm planning on switching over to the jQuery library as just about everything in ASP.NET AJAX is often easily achievable with jQuery, and, more often than not, more graceful of a solution that ASP.NET AJAX and it has a much stronger open-source community. Perhaps, it's just me, but do you feel the same way about ASP.NET AJAX? How was/is your experience working with ASP.NET AJAX?

    Read the article

  • May 2011 Release of the Ajax Control Toolkit

    - by Stephen Walther
    I’m happy to announce that the Superexpert team has published the May 2011 release of the Ajax Control Toolkit at CodePlex. You can download the new release at the following URL: http://ajaxcontroltoolkit.codeplex.com/releases/view/65800 This release focused on improving the ModalPopup and AsyncFileUpload controls. Our team closed a total of 34 bugs related to the ModalPopup and AsyncFileUpload controls. Enhanced ModalPopup Control You can take advantage of the Ajax Control Toolkit ModalPopup control to easily create popup dialogs in your ASP.NET Web Forms applications. When the dialog appears, you cannot interact with any page content which appears behind the modal dialog. For example, the following page contains a standard ASP.NET Button and Panel. When you click the Button, the Panel appears as a popup dialog: <%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Simple.aspx.vb" Inherits="ACTSamples.Simple" %> <%@ Register TagPrefix="act" Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Simple Modal Popup Sample</title> <style type="text/css"> html { background-color: blue; } #dialog { border: 2px solid black; width: 500px; background-color: White; } #dialogContents { padding: 10px; } .modalBackground { background-color:Gray; filter:alpha(opacity=70); opacity:0.7; } </style> </head> <body> <form id="form1" runat="server"> <div> <act:ToolkitScriptManager ID="tsm" runat="server" /> <asp:Panel ID="dialog" runat="server"> <div id="dialogContents"> Here are the contents of the dialog. <br /> <asp:Button ID="btnOK" Text="OK" runat="server" /> </div> </asp:Panel> <asp:Button ID="btnShow" Text="Open Dialog" runat="server" /> <act:ModalPopupExtender TargetControlID="btnShow" PopupControlID="dialog" OkControlID="btnOK" DropShadow="true" BackgroundCssClass="modalBackground" runat="server" /> </div> </form> </body> </html>     Notice that the page includes two controls from the Ajax Control Toolkit: the ToolkitScriptManager and the ModalPopupExtender control. Any page which uses any of the controls from the Ajax Control Toolkit must include a ToolkitScriptManager. The ModalPopupExtender is used to create the popup. The following properties are set: · TargetControlID – This is the ID of the Button or LinkButton control which causes the modal popup to be displayed. · PopupControlID – This is the ID of the Panel control which contains the content displayed in the modal popup. · OKControlID – This is the ID of a Button or LinkButton which causes the modal popup to close. · DropShadow – Displays a drop shadow behind the modal popup. · BackgroundCSSClass – The name of a Cascading Style Sheet class which is used to gray out the background of the page when the modal popup is displayed. The ModalPopup is completely cross-browser compatible. For example, the following screenshots show the same page displayed in Firefox 4, Internet Explorer 9, and Chrome 11: The ModalPopup control has lots of nice properties. For example, you can make the ModalPopup draggable. You also can programmatically hide and show a modal popup from either server-side or client-side code. To learn more about the properties of the ModalPopup control, see the following website: http://www.asp.net/ajax/ajaxcontroltoolkit/Samples/ModalPopup/ModalPopup.aspx Animated ModalPopup Control In the May 2011 release of the Ajax Control Toolkit, we enhanced the Modal Popup control so that it supports animations. We made this modification in response to a feature request posted at CodePlex which got 65 votes (plenty of people wanted this feature): http://ajaxcontroltoolkit.codeplex.com/workitem/6944 I want to thank Dani Kenan for posting a patch to this issue which we used as the basis for adding animation support for the modal popup. Thanks Dani! The enhanced ModalPopup in the May 2011 release of the Ajax Control Toolkit supports the following animations: OnShowing – Called before the modal popup is shown. OnShown – Called after the modal popup is shown. OnHiding – Called before the modal popup is hidden. OnHidden – Called after the modal popup is hidden. You can use these animations, for example, to fade-in a modal popup when it is displayed and fade-out the popup when it is hidden. Here’s the code: <act:ModalPopupExtender ID="ModalPopupExtender1" TargetControlID="btnShow" PopupControlID="dialog" OkControlID="btnOK" DropShadow="true" BackgroundCssClass="modalBackground" runat="server"> <Animations> <OnShown> <Fadein /> </OnShown> <OnHiding> <Fadeout /> </OnHiding> </Animations> </act:ModalPopupExtender>     So that you can experience the full joy of this animated modal popup, I recorded the following video: Of course, you can use any of the animations supported by the Ajax Control Toolkit with the modal popup. The animation reference is located here: http://www.asp.net/ajax/ajaxcontroltoolkit/Samples/Walkthrough/AnimationReference.aspx Fixes to the AsyncFileUpload In the May 2011 release, we also focused our energies on performing bug fixes for the AsyncFileUpload control. We fixed several major issues with the AsyncFileUpload including: It did not work in master pages It did not work when ClientIDMode=”Static” It did not work with Firefox 4 It did not work when multiple AsyncFileUploads were included in the same page It generated markup which was not HTML5 compatible The AsyncFileUpload control is a super useful control. It enables you to upload files in a form without performing a postback. Here’s some sample code which demonstrates how you can use the AsyncFileUpload: <%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Simple.aspx.vb" Inherits="ACTSamples.Simple1" %> <%@ Register TagPrefix="act" Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>Simple AsyncFileUpload</title> </head> <body> <form id="form1" runat="server"> <div> <act:ToolkitScriptManager ID="tsm" runat="server" /> User Name: <br /> <asp:TextBox ID="txtUserName" runat="server" /> <asp:RequiredFieldValidator EnableClientScript="false" ErrorMessage="Required" ControlToValidate="txtUserName" runat="server" /> <br /><br /> Avatar: <act:AsyncFileUpload ID="async1" ThrobberID="throbber" UploadingBackColor="yellow" ErrorBackColor="red" CompleteBackColor="green" UploaderStyle="Modern" PersistFile="true" runat="server" /> <asp:Image ID="throbber" ImageUrl="uploading.gif" style="display:none" runat="server" /> <br /><br /> <asp:Button ID="btnSubmit" Text="Submit" runat="server" /> </div> </form> </body> </html> And here’s the code-behind for the page above: Public Class Simple1 Inherits System.Web.UI.Page Private Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click If Page.IsValid Then ' Get Form Fields Dim userName As String Dim file As Byte() userName = txtUserName.Text If async1.HasFile Then file = async1.FileBytes End If ' Save userName, file to database ' Redirect to success page Response.Redirect("SimpleDone.aspx") End If End Sub End Class   The form above contains an AsyncFileUpload which has values for the following properties: ThrobberID – The ID of an element in the page to display while a file is being uploaded. UploadingBackColor – The color to display in the upload field while a file is being uploaded. ErrorBackColor – The color to display in the upload field when there is an error uploading a file. CompleteBackColor – The color to display in the upload field when the upload is complete. UploaderStyle – The user interface style: Traditional or Modern. PersistFile – When true, the uploaded file is persisted in Session state. The last property PersistFile, causes the uploaded file to be stored in Session state. That way, if completing a form requires multiple postbacks, then the user needs to upload the file only once. For example, if there is a server validation error, then the user is not required to re-upload the file after fixing the validation issue. In the sample code above, this condition is simulated by disabling client-side validation for the RequiredFieldValidator control. The RequiredFieldValidator EnableClientScript property has the value false. The following video demonstrates how the AsyncFileUpload control works: You can learn more about the properties and methods of the AsyncFileUpload control by visiting the following page: http://www.asp.net/ajax/ajaxcontroltoolkit/Samples/AsyncFileUpload/AsyncFileUpload.aspx Conclusion In the May 2011 release of the Ajax Control Toolkit, we addressed over 30 bugs related to the ModalPopup and AsyncFileUpload controls. Furthermore, by building on code submitted by the community, we enhanced the ModalPopup control so that it supports animation (Thanks Dani). In our next sprint for the June release of the Ajax Control Toolkit, we plan to focus on the HTML Editor control. Subscribe to this blog to keep updated.

    Read the article

  • mouse over and ajax tooltip

    - by vichet
    I have a number of links which I would like to get some information by using ajax calls and display the information as tooltip. I have bind the function that make the ajax call with the event on mouseover of the link something like: $('#div a').bind('mouseover', function () { //sending the ajax call } everything looks/work fine except, when the user unintentionally move the mouse pointer over all the links, I saw that there are many ajax calls. so my question how can I prevent the ajax call unless the users hover the mouse pointer on the link for at least 3 or 4 seconds first.

    Read the article

  • ASP.NET MVC 2 Post AJAX from from JavaScript

    - by ANDyW
    Hi, I got control with strongly typed View, with Ajax.BeginForm(). Now I would like to change submit method from <input type="submit" id="testClick" value="Submit" /> To some javascript method DoSubmit(). What I tried is : Invoke click on that submit button Invoke submit on form ('form1').submit(), document.forms['form1'].submit() jQuery forms with ('form1').AjaxSubmit(); Create jQuery AJAX $.ajax({ type: "POST", url: $("#form1").attr("action"), data: $("#form1").serialize(), success: function() { alert("epic win!!!1!1!") }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert("epic fail!") } }); All those method created normal request (not AJAX), or they didn't work. So anyone know how I can do AJAX submit "Form", from JavaScript and strongly typed mechanism (public AcrionResult MyFormAction(FormModel model); ) will work?

    Read the article

  • echoing javascript when an ajax funtion is called

    - by Roland
    I'm doing a ajax call via the normal jquery ajax funtion My ajax looks as follows jQuery('#yt10').live('click',function(){jQuery.ajax({'data':{'set':$("#booking_set_id1").val(),'setStat':$("#booking_stockStatus").val(),'setNum':$("#booking_setNum").val()},'beforeSend':function(){ if($("#booking_set_id1").val() == "" || $("#booking_stockStatus").val() == "" || $("#booking_setNum").val() == ""){ $("#error").addClass("flash-error"); $("#error").html("Please fill in all relevant set details before adding a set"); return false; } },'dataType':'html','success':function(data,status){ $("#mainrow").show(); $("#error").removeClass("flash-error"); $("#error").html(""); $("#setTable tr:last").after(data); $("#booking_set_id1").val(""); $("#booking_stockStatus").val(""); $("#booking_setNum").val(""); },'url':'/booking/newSet','cache':false});return false;}); Now the function newSet needs to echo javascript to the bowser but somehow jquery filters the javscript out. Is it possible to echo javascript via ajax

    Read the article

  • Getting browser to make an AJAX call ASAP, while page is still loading

    - by Chris
    I'm looking for tips on how to get the browser to kick off an AJAX call as soon as possible into processing a web page, ideally before the page is fully downloaded. Here's my approximate motivation: I have a web page that takes, say, 5 seconds to load. It calls a web service that takes, say, 10 seconds to load. If loading the page and calling the web service happened sequentially, the user would have to wait 15 seconds to see all the information. However, if I can get the web service call started before the 5 second page load is complete, then at least some of the work can happened in parallel. Ideally I'd like as much of the work to happen in parallel as possible. My initial theory was that I should place the AJAX-calling javascript as high up as possible in the web page HTML source (being mindful of putting it after the jquery.js include, because I'm making the call using jquery ajax). I'm also being mindful not to wrap the AJAX call in a jquery ready event handler. (I mention this because ready events are popular in a lot of jquery example code.) However, the AJAX call still doesn't seem to get kicked off as early as I'm hoping (at least as judged by the Google Chrome "Timeline" feature), so I'm wondering what other considerations apply. One thing that might potentially be detrimental is that the AJAX call is back to the same web server that's serving the original web page, so I might be in danger of hitting a browser limit on the # of HTTP connections back to that one machine? (The HTML page loads a number of images, css files, etc..)

    Read the article

  • jquery ajax call from link loaded with ajax

    - by Jay
    //deep linking $("document").ready(function(){ contM = $('#main-content'); contS = $('#second-content'); $(contM).hide(); $(contM).addClass('hidden'); $(contS).hide(); $(contS).addClass('hidden'); function loadURL(URL) { //console.log("loadURL: " + URL); $.ajax({ url: URL, type: "POST", dataType: 'html', data: {post_loader: 1}, success: function(data){ $(contM).html(data); $(contM).animW(); } }); } // Event handlers $.address.init(function(event) { //console.log("init: " + $('[rel=address:' + event.value + ']').attr('href')); }).change(function(event) { $.ajax({ url: $('[rel=address:' + event.value + ']').attr('href'), type: "POST", dataType: 'html', data: {post_loader: 1}, success: function(data){ $(contM).html(data); $(contM).animW(); }}); //console.log("change"); }) $('.update-main a').live('click', function(){ loadURL($(this).attr('href')); }); $(".update-second a").live('click', function() { var link = $(this); $.ajax({ url: link.attr("href"), dataType: 'html', data: {post_loader: 1}, success: function(data){ $(contS).html(data); $(contS).animW(); }}); }); }); I'm using jquery and the 'addresses' plugin to load content with ajax and maintain pagination. The problem I'm having is some content loads with links which are intended to load content into a secondary window. I'm using the .live() method to allow jquery to listen for new links loaded into the primary content div. This works until the .ajax() method is called for these fresh links loaded with ajax, where the method begins, but follows the original link before data can be received. I'm assuming the problem is in the client-side scripting, but it may be a problem with the call made to the server. I'm using the wordpress loop to parse the url and generate the html loaded via jquery. Thanks for any tips!

    Read the article

  • Problem binding action parameters using FCKeditor, AJAX and ASP.NET MVC

    - by TonE
    I have a simple ASP.Net MVC View which contains an FCKeditor text box (created using FCKeditor's Javascript ReplaceTextArea() function). These are included within an Ajax.BeginForm helper: <% using (Ajax.BeginForm("AddText", "Letters", new AjaxOptions() { UpdateTargetId = "addTextResult" })) {%> <div> <input type="submit" value="Save" /> </div> <div> <%=Html.TextArea("testBox", "Content", new { @name = "testBox" })%> <script type=""text/javascript""> window.onload = function() { var oFCKeditor = new FCKeditor('testBox') ; var sBasePath = '<%= Url.Content("~/Content/FCKeditor/") %>'; oFCKeditor.BasePath = sBasePath; oFCKeditor.ToolbarSet = "Basic"; oFCKeditor.Height = 400; oFCKeditor.ReplaceTextarea() ; } </script> <div id="addTextResult"> </div> <%} %> The controller action hanlding this is: [ValidateInput(false)] public ActionResult AddText(string testBox) { return Content(testBox); } Upon initial submission of the Ajax Form the testBox string in the AddText action is always "Content", whatever the contents of the FCKeditor have been changed to. If the Ajax form is submitted again a second time (without further changes) the testBox paramater correctly contains the actual contents of the FCKeditor. If I use a Html.TextArea without replacing with FCKeditor it works correctly, and if I use a standard Post form submit inplace of AJAX all works as expected. Am I doing something wrong? If not is there a suitable/straight-forward workaround for this problem?

    Read the article

  • Ajax Talk at .NET Developers Association

    - by Stephen Walther
    Thanks everyone who came to my Ajax talk tonight at the .NET Developers Association! The slides and demos from the talk can be downloaded by clicking the following link:   ASP.NET Ajax: What’s New?    You need Visual Studio  2010 to view the code samples. The first project, named Demos, contains the following samples: ASPAjax4 1_CompositeScripts.aspx – Demonstrates how to use the ScriptManger to combine, compress, and cache JavaScript files automatically. 2_EnableCdn.aspx – Demonstrates how to retrieve ASP.NET Ajax framework scripts from the Microsoft Ajax CDN automatically. jQuery 1_Selectors.aspx – Demonstrates how to use jQuery selectors 2_WebForms.aspx – Demonstrates how to use the client tablesorter plugin with ASP.NET Web Forms. 3_MVC.aspx – Demonstrates how to use jQuery animation and the templating plugin with ASP.NET MVC. 4_OData.aspx – Demonstrates how to use jQuery with the Netflix API by using JSONP and odata. 5_Templating.aspx – Demonstrates how to use jQuery client templating. 6_TemplateConditionals.aspx – Demonstrates how to use logic within a jQuery template. 7_DataLinking.aspx – Demonstrates how to perform data-binding in jQuery. 8_Converters.aspx – Demonstrates how to defines converters that work with data-binding. The second project, named ACT_Tools, illustrates how to use the Microsoft Ajax Minifier and the JSBuild JavaScript preprocessor. When you perform a build in Visual Studio, all JavaScript and CSS files are minified automatically. Furthermore, any *.pre.js file is processed using the JSBuild preprocessor and the output is saved to the ScriptOutput folder. Select Show All Files in Visual Studio to see the generated results of the minifier and the preprocessor.

    Read the article

  • Could Ajax + Caching be seen as cloaking?

    - by Angel
    I have a website where we use a technique to speed up loading times based in a combination of AJAX + caching. Basically, when we have a section in a page with content which is slow to retrieve, we first look if it's cached. If it is, then we serve the content, if it's not, we serve a placeholder and then make an AJAX call in the client to retrieve the content, wich is now cached for subsequent requests. As a consecuence, sometimes you get the entire page content in the first request, and sometimes you get those placeholders, wich get filled inmediatly with the responses of the AJAX request. You can see an example in the results count by category in the right column of this page: http://www.inzoco.com/crits/2-1-3-28-185-0-28079-0-0/listado-piso-en-alquiler-en-madrid-madrid.aspx I'm worried if it could be seen as cloaking by search engines because if you make a request for a page wich content isn't cached and then ask again for the same page, you would get different responses, the first with the placeholders and AJAX requests and the second one with al the content rendered.

    Read the article

  • Global "ajax call" notification with asp.net mvc/jquery

    - by Joel Martinez
    I need to be notified any time a largeish asp.net mvc web application makes an ajax call to the server. We're using both jquery, and the built-in Ajax.* methods to do the remote calls, and I would like a global way of knowing when we make a call without having to manually inject some sort of "IsMakingCall" method to every request. The root problem we're trying to solve is session timeout. If the user leaves a page up and goes to lunch (for example), they get errors when they get back because the ajax call is returning the login page instead of the expected json or partial html result. My idea was to have a js timer which would be reset any time we make an ajax call. That way, if the timer runs out (ie. their session has now timed out) I can just auto-log them out. This is how sites like bank of america and mint.com work. Thanks!

    Read the article

  • Adsense in a ajax based application?

    - by prashant_sp
    How do I add adsense or other ads in a asp.net ajax/ajax based application ? (ex. ra-ajax samples page) or GWT Is creating an iframe a viable solution? As stated below, placing adsense script is easy. But the google bot wont be able to scan my ajax based page, as all of the content is javascript. There wont be contextual ads. So wont be able to monetize. It would be great for static ads. Any idea/inputs?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >