Search Results

Search found 186 results on 8 pages for 'jsonp'.

Page 1/8 | 1 2 3 4 5 6 7 8  | Next Page >

  • Creating a JSONP Formatter for ASP.NET Web API

    - by Rick Strahl
    Out of the box ASP.NET WebAPI does not include a JSONP formatter, but it's actually very easy to create a custom formatter that implements this functionality. JSONP is one way to allow Browser based JavaScript client applications to bypass cross-site scripting limitations and serve data from the non-current Web server. AJAX in Web Applications uses the XmlHttp object which by default doesn't allow access to remote domains. There are number of ways around this limitation <script> tag loading and JSONP is one of the easiest and semi-official ways that you can do this. JSONP works by combining JSON data and wrapping it into a function call that is executed when the JSONP data is returned. If you use a tool like jQUery it's extremely easy to access JSONP content. Imagine that you have a URL like this: http://RemoteDomain/aspnetWebApi/albums which on an HTTP GET serves some data - in this case an array of record albums. This URL is always directly accessible from an AJAX request if the URL is on the same domain as the parent request. However, if that URL lives on a separate server it won't be easily accessible to an AJAX request. Now, if  the server can serve up JSONP this data can be accessed cross domain from a browser client. Using jQuery it's really easy to retrieve the same data with JSONP:function getAlbums() { $.getJSON("http://remotedomain/aspnetWebApi/albums?callback=?",null, function (albums) { alert(albums.length); }); } The resulting callback the same as if the call was to a local server when the data is returned. jQuery deserializes the data and feeds it into the method. Here the array is received and I simply echo back the number of items returned. From here your app is ready to use the data as needed. This all works fine - as long as the server can serve the data with JSONP. What does JSONP look like? JSONP is a pretty simple 'protocol'. All it does is wrap a JSON response with a JavaScript function call. The above result from the JSONP call looks like this:Query17103401925975181569_1333408916499( [{"Id":"34043957","AlbumName":"Dirty Deeds Done Dirt Cheap",…},{…}] ) The way JSONP works is that the client (jQuery in this case) sends of the request, receives the response and evals it. The eval basically executes the function and deserializes the JSON inside of the function. It's actually a little more complex for the framework that does this, but that's the gist of what happens. JSONP works by executing the code that gets returned from the JSONP call. JSONP and ASP.NET Web API As mentioned previously, JSONP support is not natively in the box with ASP.NET Web API. But it's pretty easy to create and plug-in a custom formatter that provides this functionality. The following code is based on Christian Weyers example but has been updated to the latest Web API CodePlex bits, which changes the implementation a bit due to the way dependent objects are exposed differently in the latest builds. Here's the code:  using System; using System.IO; using System.Net; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Threading.Tasks; using System.Web; using System.Net.Http; namespace Westwind.Web.WebApi { /// <summary> /// Handles JsonP requests when requests are fired with /// text/javascript or application/json and contain /// a callback= (configurable) query string parameter /// /// Based on Christian Weyers implementation /// https://github.com/thinktecture/Thinktecture.Web.Http/blob/master/Thinktecture.Web.Http/Formatters/JsonpFormatter.cs /// </summary> public class JsonpFormatter : JsonMediaTypeFormatter { public JsonpFormatter() { SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json")); SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/javascript")); //MediaTypeMappings.Add(new UriPathExtensionMapping("jsonp", "application/json")); JsonpParameterName = "callback"; } /// <summary> /// Name of the query string parameter to look for /// the jsonp function name /// </summary> public string JsonpParameterName {get; set; } /// <summary> /// Captured name of the Jsonp function that the JSON call /// is wrapped in. Set in GetPerRequestFormatter Instance /// </summary> private string JsonpCallbackFunction; public override bool CanWriteType(Type type) { return true; } /// <summary> /// Override this method to capture the Request object /// and look for the query string parameter and /// create a new instance of this formatter. /// /// This is the only place in a formatter where the /// Request object is available. /// </summary> /// <param name="type"></param> /// <param name="request"></param> /// <param name="mediaType"></param> /// <returns></returns> public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType) { var formatter = new JsonpFormatter() { JsonpCallbackFunction = GetJsonCallbackFunction(request) }; return formatter; } /// <summary> /// Override to wrap existing JSON result with the /// JSONP function call /// </summary> /// <param name="type"></param> /// <param name="value"></param> /// <param name="stream"></param> /// <param name="contentHeaders"></param> /// <param name="transportContext"></param> /// <returns></returns> public override Task WriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, TransportContext transportContext) { if (!string.IsNullOrEmpty(JsonpCallbackFunction)) { return Task.Factory.StartNew(() => { var writer = new StreamWriter(stream); writer.Write( JsonpCallbackFunction + "("); writer.Flush(); base.WriteToStreamAsync(type, value, stream, contentHeaders, transportContext).Wait(); writer.Write(")"); writer.Flush(); }); } else { return base.WriteToStreamAsync(type, value, stream, contentHeaders, transportContext); } } /// <summary> /// Retrieves the Jsonp Callback function /// from the query string /// </summary> /// <returns></returns> private string GetJsonCallbackFunction(HttpRequestMessage request) { if (request.Method != HttpMethod.Get) return null; var query = HttpUtility.ParseQueryString(request.RequestUri.Query); var queryVal = query[this.JsonpParameterName]; if (string.IsNullOrEmpty(queryVal)) return null; return queryVal; } } } Note again that this code will not work with the Beta bits of Web API - it works only with post beta bits from CodePlex and hopefully this will continue to work until RTM :-) This code is a bit different from Christians original code as the API has changed. The biggest change is that the Read/Write functions no longer receive a global context object that gives access to the Request and Response objects as the older bits did. Instead you now have to override the GetPerRequestFormatterInstance() method, which receives the Request as a parameter. You can capture the Request there, or use the request to pick up the values you need and store them on the formatter. Note that I also have to create a new instance of the formatter since I'm storing request specific state on the instance (information whether the callback= querystring is present) so I return a new instance of this formatter. Other than that the code should be straight forward: The code basically writes out the function pre- and post-amble and the defers to the base stream to retrieve the JSON to wrap the function call into. The code uses the Async APIs to write this data out (this will take some getting used to seeing all over the place for me). Hooking up the JsonpFormatter Once you've created a formatter, it has to be added to the request processing sequence by adding it to the formatter collection. Web API is configured via the static GlobalConfiguration object.  protected void Application_Start(object sender, EventArgs e) { // Verb Routing RouteTable.Routes.MapHttpRoute( name: "AlbumsVerbs", routeTemplate: "albums/{title}", defaults: new { title = RouteParameter.Optional, controller = "AlbumApi" } ); GlobalConfiguration .Configuration .Formatters .Insert(0, new Westwind.Web.WebApi.JsonpFormatter()); }   That's all it takes. Note that I added the formatter at the top of the list of formatters, rather than adding it to the end which is required. The JSONP formatter needs to fire before any other JSON formatter since it relies on the JSON formatter to encode the actual JSON data. If you reverse the order the JSONP output never shows up. So, in general when adding new formatters also try to be aware of the order of the formatters as they are added. Resources JsonpFormatter Code on GitHub© Rick Strahl, West Wind Technologies, 2005-2012Posted in Web Api   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (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

  • Please explain JSONP

    - by Cheeso
    I don't understand jsonp. I understand JSON. I don't understand JSONP. Wikipedia is the top search result for JSONP. It says JSONP or "JSON with padding" is a JSON extension wherein a prefix is specified as an input argument of the call itself. Huh? What call? That doesn't make any sense to me. JSON is a data format. There's no call. The 2nd search result is from some guy named Remy, who writes JSONP is script tag injection, passing the response from the server in to a user specified function. I can sort of understand that, but it's still not making any sense. What is JSONP, why was it created (what problem does it solve), and why would I use it? Addendum: I've updated Wikipedia with a clearer and more thorough description of JSONP, based on jvenema's answer. Thanks, all.

    Read the article

  • Configurationless WCF using Factories and JSONP

    - by FlySwat
    I'm using the WebServiceHostFactory in my WCF services to avoid having to create a crapton of binding configuration in web.config. However, I'd like to expose the services as XML/JSON and JSONP. Reading: http://jasonkelly.net/archive/2009/02/24/using-jquery-amp-jsonp-for-cross-domain-ajax-with-wcf-services.aspx It does not look like I can extend WCF to add JSONP without resorting to a mountain of custom binding config. So, for those who have done it, is it possible to have a restful WCF service that responds in XML/JSON/JSONP depending on the UriTemplate, without resorting to a ton of config wiring?

    Read the article

  • jsonp cross domain only working in IE

    - by iboeno
    EDIT: At first I thought it wasn't working cross domain at all, now I realize it only works in IE I'm using jQuery to call a web service (ASP.NET .axmx), and trying to us jsonp so that I can call it across different sites. Right now it is working ONLY in IE, but not in Firefox, Chrome, Safari. Also, in IE, a dialog pops up warning "This page is accessing information that is not under its control..." Any ideas? Here is the code: $.ajax({ type: "POST", url: "http://test/TestService.asmx/HelloWorld?jsonp=?", dataType: "jsonp", success: function(data) { alert(data.prop1); }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert(XMLHttpRequest.status + " " + textStatus + " " + errorThrown); } }); And the server code is: [ScriptService] public class TestService : System.Web.Services.WebService{ [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public void HelloWorld() { string jsoncallback = HttpContext.Current.Request["jsonp"]; var response = string.Format("{0}({1});", jsoncallback, @"{'prop1' : '" + DateTime.Now.ToString() + "'}"); HttpContext.Current.Response.Write(response); } }

    Read the article

  • How safe is JSONP implementation for login functionality

    - by MKS
    Hi Guys, I am using JSONP for login authentication, below is sample JQuery Code: $.ajax({ type:"GET", url: "https://staging/login/Login.aspx", // Send the login info to this page data: str, dataType: "jsonp", timeout: 200000, jsonp:"skywardDetails", success: function(result) { //Do something after the success } }); In above code, I am having HTTPS page for authentication, from my login dailog box, I am sending username and password to my login.aspx page, which calls "WEB SERVICE" taking input send by the login dialog page and return the users details as JSONP object. My question is that, how safe is above implementation and do also suggest how can I improve my security implementation. Thanks!

    Read the article

  • How to use type: "POST" in jsonp ajax call

    - by MKS
    Hi Guy, I am using JQuery ajax jsonp. I have got below JQuery Code: $.ajax({ type:"GET", url: "Login.aspx", // Send the login info to this page data: str, dataType: "jsonp", timeout: 200000, jsonp:"skywardDetails", success: function(result) { // Show 'Submit' Button $('#loginButton').show(); // Hide Gif Spinning Rotator $('#ajaxloading').hide(); } }); The above code is working fine, I just want to send the request as "POST" instead of "GET", Please suggest how can I achieve this. Thanks

    Read the article

  • Netflix, jQuery, JSONP, and OData

    - by Stephen Walther
    At the last MIX conference, Netflix announced that they are exposing their catalog of movie information using the OData protocol. This is great news! This means that you can take advantage of all of the advanced OData querying features against a live database of Netflix movies. In this blog entry, I’ll demonstrate how you can use Netflix, jQuery, JSONP, and OData to create a simple movie lookup form. The form enables you to enter a movie title, or part of a movie title, and display a list of matching movies. For example, Figure 1 illustrates the movies displayed when you enter the value robot into the lookup form.   Using the Netflix OData Catalog API You can learn about the Netflix OData Catalog API at the following website: http://developer.netflix.com/docs/oData_Catalog The nice thing about this website is that it provides plenty of samples. It also has a good general reference for OData. For example, the website includes a list of OData filter operators and functions. The Netflix Catalog API exposes 4 top-level resources: Titles – A database of Movie information including interesting movie properties such as synopsis, BoxArt, and Cast. People – A database of people information including interesting information such as Awards, TitlesDirected, and TitlesActedIn. Languages – Enables you to get title information in different languages. Genres – Enables you to get title information for specific movie genres. OData is REST based. This means that you can perform queries by putting together the right URL. For example, if you want to get a list of the movies that were released after 2010 and that had an average rating greater than 4 then you can enter the following URL in the address bar of your browser: http://odata.netflix.com/Catalog/Titles?$filter=ReleaseYear gt 2010&AverageRating gt 4 Entering this URL returns the movies in Figure 2. Creating the Movie Lookup Form The complete code for the Movie Lookup form is contained in Listing 1. Listing 1 – MovieLookup.htm <!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>Netflix with jQuery</title> <style type="text/css"> #movieTemplateContainer div { width:400px; padding: 10px; margin: 10px; border: black solid 1px; } </style> <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></script> <script src="App_Scripts/Microtemplates.js" type="text/javascript"></script> </head> <body> <label>Search Movies:</label> <input id="movieName" size="50" /> <button id="btnLookup">Lookup</button> <div id="movieTemplateContainer"></div> <script id="movieTemplate" type="text/html"> <div> <img src="<%=BoxArtSmallUrl %>" /> <strong><%=Name%></strong> <p> <%=Synopsis %> </p> </div> </script> <script type="text/javascript"> $("#btnLookup").click(function () { // Build OData query var movieName = $("#movieName").val(); var query = "http://odata.netflix.com/Catalog" // netflix base url + "/Titles" // top-level resource + "?$filter=substringof('" + escape(movieName) + "',Name)" // filter by movie name + "&$callback=callback" // jsonp request + "&$format=json"; // json request // Make JSONP call to Netflix $.ajax({ dataType: "jsonp", url: query, jsonpCallback: "callback", success: callback }); }); function callback(result) { // unwrap result var movies = result["d"]["results"]; // show movies in template var showMovie = tmpl("movieTemplate"); var html = ""; for (var i = 0; i < movies.length; i++) { // flatten movie movies[i].BoxArtSmallUrl = movies[i].BoxArt.SmallUrl; // render with template html += showMovie(movies[i]); } $("#movieTemplateContainer").html(html); } </script> </body> </html> The HTML page in Listing 1 includes two JavaScript libraries: <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></script> <script src="App_Scripts/Microtemplates.js" type="text/javascript"></script> The first script tag retrieves jQuery from the Microsoft Ajax CDN. You can learn more about the Microsoft Ajax CDN by visiting the following website: http://www.asp.net/ajaxLibrary/cdn.ashx The second script tag is used to reference Resig’s micro-templating library. Because I want to use a template to display each movie, I need this library: http://ejohn.org/blog/javascript-micro-templating/ When you enter a value into the Search Movies input field and click the button, the following JavaScript code is executed: // Build OData query var movieName = $("#movieName").val(); var query = "http://odata.netflix.com/Catalog" // netflix base url + "/Titles" // top-level resource + "?$filter=substringof('" + escape(movieName) + "',Name)" // filter by movie name + "&$callback=callback" // jsonp request + "&$format=json"; // json request // Make JSONP call to Netflix $.ajax({ dataType: "jsonp", url: query, jsonpCallback: "callback", success: callback }); This code Is used to build a query that will be executed against the Netflix Catalog API. For example, if you enter the search phrase King Kong then the following URL is created: http://odata.netflix.com/Catalog/Titles?$filter=substringof(‘King%20Kong’,Name)&$callback=callback&$format=json This query includes the following parameters: $filter – You assign a filter expression to this parameter to filter the movie results. $callback – You assign the name of a JavaScript callback method to this parameter. OData calls this method to return the movie results. $format – you assign either the value json or xml to this parameter to specify how the format of the movie results. Notice that all of the OData parameters -- $filter, $callback, $format -- start with a dollar sign $. The Movie Lookup form uses JSONP to retrieve data across the Internet. Because WCF Data Services supports JSONP, and Netflix uses WCF Data Services to expose movies using the OData protocol, you can use JSONP when interacting with the Netflix Catalog API. To learn more about using JSONP with OData, see Pablo Castro’s blog: http://blogs.msdn.com/pablo/archive/2009/02/25/adding-support-for-jsonp-and-url-controlled-format-to-ado-net-data-services.aspx The actual JSONP call is performed by calling the $.ajax() method. When this call successfully completes, the JavaScript callback() method is called. The callback() method looks like this: function callback(result) { // unwrap result var movies = result["d"]["results"]; // show movies in template var showMovie = tmpl("movieTemplate"); var html = ""; for (var i = 0; i < movies.length; i++) { // flatten movie movies[i].BoxArtSmallUrl = movies[i].BoxArt.SmallUrl; // render with template html += showMovie(movies[i]); } $("#movieTemplateContainer").html(html); } The movie results from Netflix are passed to the callback method. The callback method takes advantage of Resig’s micro-templating library to display each of the movie results. A template used to display each movie is passed to the tmpl() method. The movie template looks like this: <script id="movieTemplate" type="text/html"> <div> <img src="<%=BoxArtSmallUrl %>" /> <strong><%=Name%></strong> <p> <%=Synopsis %> </p> </div> </script>   This template looks like a server-side ASP.NET template. However, the template is rendered in the client (browser) instead of the server. Summary The goal of this blog entry was to demonstrate how well jQuery works with OData. We managed to use a number of interesting open-source libraries and open protocols while building the Movie Lookup form including jQuery, JSONP, JSON, and OData.

    Read the article

  • Why isn't jQuery automatically appending the JSONP callback?

    - by Aseem Kishore
    The $.getJSON() documentation states: If the specified URL is on a remote server, the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details. The $.ajax() documentation for the jsonp data type states (emphasis mine): Loads in a JSON block using JSONP. Will add an extra "?callback=?" to the end of your URL to specify the callback. So it seems that if I call $.getJSON() with a cross-domain URL, the extra "callback=?" parameter should automatically get added. (Other parts of the documentation support this interpretation.) However, I'm not seeing that behavior. If I don't add the "callback=?" explicitly, jQuery incorrectly makes an XMLHttpRequest (which returns null data since I can't read the response cross-domain). If I do add it explicitly, jQuery correctly makes a <script> request. Here's an example: var URL = "http://www.geonames.org/postalCodeLookupJSON" + "?postalcode=10504&country=US"; function alertResponse(data, status) { alert("data: " + data + ", status: " + status); } $.getJSON(URL, alertResponse); // alerts "data: null, status: success" $.getJSON(URL + "&callback=?", alertResponse); // alerts "data: [object Object], status: undefined" So what's going on? Am I misunderstanding the documentation or forgetting something? It goes without saying that this isn't a huge deal, but I'm creating a web API and I purposely set the callback parameter to "callback" in the hopes of tailoring it nicely to jQuery usage. Thanks!

    Read the article

  • Shopify JSONP issue in ajaxAPI

    - by Aaron U
    I'm getting some odd response back from shopify ajaxapi for jsonp. If you cURL a Shopify ajax api location http://storename.domain.com/cart.json?callback=handler you will get a jsonp response. But something is breaking the same request in browsers. It appears to be related to compression? Here are some responses from each browser when attempting to call the jsonp as documented. Firefox: The page you are trying to view cannot be shown because it uses an invalid or unsupported form of compression. Internet Explorer: Internet Explorer cannot display the webpage Chrome/Safari/Webkit: Cannot decode raw data, or failed (chrome) Attempted use via jquery: $.getJSON('http://storename.domain.com/cart.json?callback=?', function(data) { ... }); // Results in a failed request, viewable network request panels of dev tools Here is some output from cURL including response headers: $ curl -i http://storename.domain.com/cart.json?callback=CALLBACK_FUNC HTTP/1.1 200 OK Server: nginx Date: Tue, 18 Dec 2012 13:48:29 GMT Content-Type: application/javascript; charset=utf-8 Transfer-Encoding: chunked Connection: keep-alive Status: 200 OK ETag: cachable:864076445587123764313132415008994143575 Cache-Control: max-age=0, private, must-revalidate X-Alternate-Cache-Key: cachable:11795444887523410552615529412743919200 X-Cache: hit, server X-Request-Id: a0c33a55230fe42bce79b462f6fe450d X-UA-Compatible: IE=Edge,chrome=1 Set-Cookie: _session_id=b6ace1d7b0dbedd37f7787d10e173131; path=/; HttpOnly X-Runtime: 0.033811 P3P: CP="NOI DSP COR NID ADMa OPTa OUR NOR" CALLBACK_FUNC({"token":null,"note":null,"attributes":{},"total_price":0,...}) Also related unanswered here: Shopify Ajax API JSONP supported? Thanks

    Read the article

  • Javascript: How to test JSONP on localhost

    - by hqt
    Here is the way I test JSONP: I run XAMPP, and in folder htdocs I create a javascript folder . I create json1.json file contain some data to process. After that, I run this html file locally, and it will call a function in "other machine" (in this case is localhost) Here is my code : <head> <script> function updateSales(sales) { alert('test jsonp'); // real code here } </script> </head> <body> <h1>JSONP Example</h1> <script src="http://localhost:85/javascript/json1.json?callback=updateSales"></script> </body> But when I run, nothing happen. But if change to other real json on the internet, it will work. It means change line : <script src="http://localhost:85/javascript/json1.json?callback=updateSales"></script> to line: <script src="http://gumball.wickedlysmart.com/?callback=updateSales"></script> It will work smoothly. So, I don't know how to test JSONP by using localhost, please help me. Thanks :)

    Read the article

  • jsonp is not firing beforeSend?

    - by user283357
    Hi All, I am working on a project to call a webservice from different domain using $.ajax with dataType set to jsonp. $.ajax({ type: "GET", url: testService.asmx, async: true, contentType: "application/json; charset=utf-8", dataType: "jsonp", beforeSend: function (XMLHttpRequest) { alert('Before Send'); //Nothing happnes }, success: function (response) { alert('Success'); //this was fired }, complete: function (XMLHttpRequest, textStatus) { alert('After Send'); //this was fired } }); The problem is I have a ...loading animation which I want to display while the web service request is being processed. I tried using "beforeSend:" to show the loading animation but it seems like "beforeSend" is not getting fired. The animation works fine when the app is on the same domain (using jsonp) but when I move the app into a different server, everything works except "beforeSend" is not getting called. So users will not be able to see the loading animation. Is there any workaround for this?

    Read the article

  • Does JSONP scale? How many JSONP requests can I send?

    - by Cheeso
    Based on Please explain JSONP, I understand that JSONP can be used to get around the same-origin policy. But in order to do that, the page must use a <script> tag. I know that pages can dynamically emit new script tags, such as with: <script type="text/javascript" language='javascript'> document.write('<script type="text/javascript" ' + 'id="contentloadtag" defer="defer" ' + 'src="javascript:void(0)"><\/script>'); var contentloadtag=document.getElementById("contentloadtag"); contentloadtag.onreadystatechange=function(){ if (this.readyState=="complete") { init(); } } </script> (the above works in IE, don't think it works in FF). ... but does this mean, effectively, that every JSONP call requires me to emit another <script> tag into the document? Can I remove the <script> tags that are done?

    Read the article

  • IE9 syntax on jquery crossbrowser with jsonp and FF, Chrome

    - by Andrew Walker
    I have the following code and i have a problem in ensuring part of it is used when a IE browser is used, and remove it when any other browser is used: $.ajax({ url: 'http://mapit.mysociety.org/areas/'+ulo, type: 'GET', cache: false, crossDomain: true, dataType: 'jsonp', success: function(response) { This works fine in IE9 because I have put the dataType as jsonp. But this will not work on Chrome or FF. So I need to remove the dataType. I tried this: <!--[IF IE]> dataType: 'jsonp', <![endif]--> But it did not work. It's worth noting, it does not need the dataType set when in FF or Chrome as it's json. Whats the correct syntax to have this work ? Thanks Andrew

    Read the article

  • Jsonp cross-domain ajax

    - by Guillaume le Floch
    I'm working on an application which use ajax call to get html from the server. When I run it on the server, everything works fine. But when I'm running on a localhost, I've a 'Access-Control-Allow-Origin' error. I looked arround and it seems like using jsonp could be the solution. So, my ajax call looks like that: $.ajax({ url: url, dataType: 'jsonp', crossDomain: true, type: 'GET', success: function(data){ // should put the data in a div }, error: function(){ //do some stuff with errors } }); I get html from the server, but I always have this error: Uncaught SyntaxError: Unexpected token < Is there a way to wrap the jsonp response in html? Thanks!

    Read the article

  • Do I need jsonp?

    - by franziga
    Since firefox 3, cross domain XmlHttpRequest is available. As my understand, jsonp is also doing something about cross domain. If I only need to deal with firefox 3, do I still need to use jsonp?

    Read the article

  • ASP.NET MVC 2 JSONP with MVC Futures

    - by mighty_man
    I´m using mvc futures 2 with WebApiEnabled for XML and JSON support. But due to cross domain issues with jQuery $.ajax I´m lookin in to JSONP. Is there a simple way to extend futures rest function for JSONP or should I do something else. Do anyone have some hints on this subject ?

    Read the article

  • JSONP & jQuery Chunking

    - by Tom
    Hi Guys, I am wanting to utilize JSONP for a project with x-domain scripting but little concerned with the 2048 character limit in IE. Does JSONP support "chunking" automatically if character size exceeds 2048 ? If yes, does anyone have any examples they can share ? Thx

    Read the article

  • No data when attempting to get JSONP data from cross domain PHP script

    - by Alex
    I am trying to pull latitude and longitude values from another server on a different domain using a singe id string. I am not very familiar with JQuery, but it seems to be the easiest way to go about getting around the same origin problem. I am unable to use iframes and I cannot install PHP on the server running this javascript, which is forcing my hand on this. My queries appear to be going through properly, but I am not getting any results back. I was hoping someone here might have an idea that could help, seeing as I probably wouldn't recognize most obvious errors here. My javascript function is: var surl = "http://...omitted.../pull.php"; var idnum = 5a; //in practice this is defined above alert("BEFORE"); $.ajax({ url: surl, data: {id: idnum}, dataType: "jsonp", jsonp : "callback", jsonp: "jsonpcallback", success: function (rdata) { alert(rdata.lat + ", " + rdata.lon); } }); alert("BETWEEN"); function jsonpcallback(rtndata) { alert("CALLED"); alert(rtndata.lat + ", " + rtndata.lon); } alert("AFTER"); When my javascript is run, the BEFORE, BETWEEN and AFTER alerts are displayed. The CALLED and other jsonpcallback alerts are not shown. Is there another way to tell if the jsoncallback function has been called? Below is the PHP code I have running on the second server. I added the count table to my database just so that I can tell when this script is run. Every time I call the javascript, count has had an extra item inserted and the id number is correct. <?php header("content-type: application/json"); if (isset($_GET['id']) || isset($_POST['id'])){ $db_handle = mysql_connect($server, $username, $password); if (!$db_handle) { die('Could not connect: ' . mysql_error()); } $db_found = mysql_select_db($database, $db_handle); if ($db_found) { if (isset($_POST['id'])){ $SQL = sprintf("SELECT * FROM %s WHERE loc_id='%s'", $loctable, mysql_real_escape_string($_POST['id'])); } if (isset($_GET['id'])){ $SQL = sprintf("SELECT * FROM %s WHERE loc_id='%s'", $loctable, mysql_real_escape_string($_GET['id'])); } $result = mysql_query($SQL, $db_handle); $db_field = mysql_fetch_assoc($result); $rtnjsonobj -> lat = $db_field["lat"]; $rtnjsonobj -> lon = $db_field["lon"]; if (isset($_POST['id'])){ echo $_POST['jsonpcallback']. '('. json_encode($rtnjsonobj) . ')'; } if (isset($_GET['id'])){ echo $_GET['jsonpcallback']. '('. json_encode($rtnjsonobj) . ')'; } $SQL = sprintf("INSERT INTO count (bullshit) VALUES ('%s')", $_GET['id']); $result = mysql_query($SQL, $db_handle); $db_field = mysql_fetch_assoc($result); } mysql_close($db_handle); } else { $rtnjsonobj -> lat = 404; $rtnjsonobj -> lon = 404; echo $_GET['jsonpcallback']. '('. json_encode($rtnjsonobj) . ')'; }?> I am not entirely sure if the jsonp returned by this PHP is correct. When I go directly to the PHP script without including any parameters, I do get the following. ({"lat":404,"lon":404}) The callback function is not included, but that much can be expected when it isn't included in the original call. Does anyone have any idea what might be going wrong here? Thanks in advance!

    Read the article

  • use jsonp to get xml cross domain

    - by lmkk
    I am trying to read xml into a webpage from another server, and I assume that my problem is Same-Origin Policy, and therefore a cross domain problem. I have a bit of googling and it seems that jsonp is the way forward. Based on some examples I found here on stackoverflow and another sites, this is what I have, and it does not "hit" the server with the xml. I can view the xml in a browser. $(document).ready(function(){ $.ajax({ type: 'GET', dataType: 'jsonp', url: 'http://192.168.0.106:8111/getconfiguration?', success: function (xml) { //do stuff with received xml }}); Any suggestions? please keep in mind that I am a newbie with regards to JS / JQuery ;o)

    Read the article

  • Error calling webservice using JSONP + jquery with IE on remote domain

    - by Jay Heavner
    I have a .Net webservice on my app server that returns data formatted as JSONP. I have an HTML test client on that server which works fine using IE, Firefox, & Chrome. If I copy the same HTML to my workstation or deploy to my webserver it works with Firefox & Chrome but in IE I'm getting two javascript errors. Message: Object doesn't support this property or method Line: 1 Char: 1 Code: 0 URI: http://mydomain/WebServices/LyrisProxy/Services/Lyris/JSONP/Lyris.asmx/AddUser?lyrisInstance="1"&email="[email protected]"&fullName="My Name"&lyrisList="listname"&format=json&callback=jsonp1274109819864&_=1274109829665 Message: Member not found. Line: 59 Char: 209 Code: 0 URI: http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js I'm kind of at loss as to what to do to fix this.

    Read the article

  • How do I catch jQuery $.getJSON (or $.ajax with datatype set to 'jsonp') error when using JSONP?

    - by Andy May
    Is it possible to catch an error when using JSONP with jQuery? I've tried both the $.getJSON and $.ajax methods but neither will catch the 404 error I'm testing. Here is what I've tried (keep in mind that these all work successfully, but I want to handle the case when it fails): jQuery.ajax({ type: "GET", url: handlerURL, dataType: "jsonp", success: function(results){ alert("Success!"); }, error: function(XMLHttpRequest, textStatus, errorThrown){ alert("Error"); } }); And also: jQuery.getJSON(handlerURL + "&callback=?", function(jsonResult){ alert("Success!"); }); I've also tried adding the $.ajaxError but that didn't work either: jQuery(document).ajaxError(function(event, request, settings){ alert("Error"); }); Thanks in advance for any replies!

    Read the article

  • Grails: JSONP callback without id and class in JSON file

    - by Klaas
    Hi, I am working on a REST based interface where people get a json file. The client needs to access the file from another Domain. I use jsonp which works so far. My problem is the rendering in Grails. At the moment I use the 'as JSON' to marshalling the object: render "${params.jsoncallback}(${user as JSON})" The Json file getting to the client inclused all attributes, incluing the id and class, which I do not want to have in there. In case it is not jsonp, I do it this way, which works great: render(contentType:'text/json'){ userName user.userName userImage user.userImage : : } So how do I get the id and class attributes out of the json when rendering "user as JSON"? Any idea? best regards, Klaas

    Read the article

  • Jsonp request using jquery to fetch bing web results

    - by Blankman
    using this as a guide: http://msdn.microsoft.com/en-us/library/dd250846.aspx can someone help me with the jquery call? Do I actually pass in the javascript code for the callback, or just the name of the function? BingSearch = function($bingUrl, $bingAppID, $keyword, $callBack) { $bingUrl = $bingUrl + "?JsonType=callback&JsonCallback=" + $callBack + "&Appid=" + $bingAppID + "&query=" + encodeURI($keyword) + "&sources=web"; $.ajax({ dataType: 'jsonp', jsonp: $callBack, url: $bingUrl, success: function(data) { alert('success'); $callBack(data); }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert("error: " + textStatus); } }); };

    Read the article

  • cross-domain data with AJAX using JSONP

    - by kooshka
    I'm trying to get data from Geobytes. One of the templates returns JSON and I need to cross-domain access it. I wrote these 2 functions function getCountry(ip) { var surl = "http://www.geobytes.com/IpLocator.htm?GetLocation&template=json.txt"; $.ajax({ url: surl, data: '{"ipaddress":"' + ip + '"}', dataType: "jsonp", jsonp: "callback", jsonpCallback: "jsonpcallback" }); } function jsonpcallback(rtndata) { alert(rtndata.message); } The call is executed but I get 1 warning: Resource interpreted as Script but transferred with MIME type text/html: "http://www.geobytes.com/IpLocator.htm?GetLocation&template=json.txt&callback=jsonpcallback&{%22ipaddress%22:%22200.167.254.166%22}&_=1353148931121" 1 Error: Uncaught SyntaxError: Unexpected token : The error is thrown on the returned data at {"geobytes":{"countryid":117, I think is maybe because it's 117 and not "117" but I obviously can't control the returned data How can I fix these 2 issues?

    Read the article

  • JSONP Implications with true REST

    - by REA_ANDREW
    From my understanding JSONP can only be achieved using the GET verb. Assuming this is true which I think it is, then this rules out core compliance with true REST in which you should make use of different verbs i.e. GET,PUT,POST,DELETE etc... for different and specific purposes. My question is what type of barriers am I likely to come up against if I where to say allow updating and deleting of resources using a JSONP service using a get request. Is it better practice to offer a JSON service and state that the user will need a server side proxy to consume using JavaScript XDomain? Cheers , Andrew

    Read the article

1 2 3 4 5 6 7 8  | Next Page >