Search Results

Search found 288 results on 12 pages for 'xhr'.

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

  • I can't change HTTP request header Content-Type value using jQuery

    - by Matt
    Hi I tried to override HTTP request header content by using jQuery's AJAX function. It looks like this $.ajax({ type : "POST", url : url, data : data, contentType: "application/x-www-form-urlencoded;charset=big5", beforeSend: function(xhr) { xhr.setRequestHeader("Accept-Charset","big5"); xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=big5"); }, success: function(rs) { target.html(rs); } }); Content-Type header is default to "application/x-www-form-urlencoded; charset=UTF-8", but it obviously I can't override its value no matter I use 'contentType' or 'beforeSend' approaches. Could anyone adivse me a hint that how do I or can I change the HTTP request's content-type value? thanks a lot. btw, is there any good documentation that I can study JavaScript's XMLHttpRequest's encoding handling?

    Read the article

  • JQuery + WCF + HTTP 404 Error

    - by hangar18
    HI All, I've searched high and low and finally decided to post a query here. I'm writing a very basic HTML page from which I'm trying to call a WCF service using jQuery and parse it using JSON. Service: IMyDemo.cs [ServiceContract] public interface IMyDemo { [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)] Employee DoWork(); [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)] Employee GetEmp(int age, string name); } [DataContract] public class Employee { [DataMember] public int EmpId { get; set; } [DataMember] public string EmpName { get; set; } [DataMember] public int EmpSalary { get; set; } } MyDemo.svc.cs public Employee DoWork() { // Add your operation implementation here Employee obj = new Employee() { EmpSalary = 12, EmpName = "SomeName" }; return obj; } public Employee GetEmp(int age, string name) { Employee emp = new Employee(); if (age > 0) emp.EmpSalary = 12 + age; if (!string.IsNullOrEmpty(name)) emp.EmpName = "Server" + name; return emp; } WEb.Config <system.serviceModel> <services> <service behaviorConfiguration="EmployeesBehavior" name="MySample.MyDemo"> <endpoint address="" binding="webHttpBinding" contract="MySample.IMyDemo" behaviorConfiguration="EmployeesBehavior"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="EmployeesBehavior"> <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="EmployeesBehavior"> <webHttp/> </behavior> </endpointBehaviors> </behaviors> <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> </system.serviceModel> MyDemo.htm <head> <title></title> <script type="text/javascript" language="javascript" src="Scripts/jquery-1.4.1.js"></script> <script type="text/javascript" language="javascript" src="Scripts/json.js"></script> <script type="text/javascript"> //create a global javascript object for the AJAX defaults. debugger; var ajaxDefaults = {}; ajaxDefaults.base = { type: "POST", timeout : 1000, dataFilter: function (data) { //see http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/ data = JSON.parse(data); //use the JSON2 library if you aren’t using FF3+, IE8, Safari 3/Google Chrome return data.hasOwnProperty("d") ? data.d : data; }, error: function (xhr) { //see if (!xhr) return; if (xhr.responseText) { var response = JSON.parse(xhr.responseText); //console.log works in FF + Firebug only, replace this code if (response) alert(response); else alert("Unknown server error"); } } }; ajaxDefaults.json = $.extend(ajaxDefaults.base, { //see http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/ contentType: "application/json; charset=utf-8", dataType: "json" }); var ops = { baseUrl: "/MyService/MySample/MyDemo.svc/", doWork: function () { //see http://api.jquery.com/jQuery.extend/ var ajaxOptions = $.extend(ajaxDefaults.json, { url: ops.baseUrl + "DoWork", data: "{}", success: function (msg) { console.log("success"); console.log(typeof msg); if (typeof msg !== "undefined") { console.log(msg); } } }); $.ajax(ajaxOptions); return false; }, getEmp: function () { var ajaxOpts = $.extend(ajaxDefaults.json, { url: ops.baseUrl + "GetEmp", data: JSON.stringify({ age: 12, name: "NameName" }), success: function (msg) { $("span#lbl").html("age: " + msg.Age + "name:" + msg.Name); } }); $.ajax(ajaxOpts); return false; } } </script> </head> <body> <span id="lbl">abc</span> <br /><br /> <input type="button" value="GetEmployee" id="btnGetEmployee" onclick="javascript:ops.getEmp();" /> </body> I'm just not able to get this running. When I debug, I see the error being returned from the call is " Server Error in '/jQuerySample' Application. <h2> <i>HTTP Error 404 - Not Found.</i> </h2></span> " Looks like I'm missing something basic here. My sample is based on this I've been trying to fix the code for sometime now so I'd like you to take a look and see if you can figure out what is it that I'm doing wrong here. I'm able to see that the service is created when I browse the service in IE. I've also tried changing the setting as mentioned here Appreciate your help. I'm gonna blog about this as soon as the issue is resolved for the benefit of other devs Thanks -Soni

    Read the article

  • jQuery AJAX (google PageRank)

    - by RobertPitt
    Hey guys, I need a little help.. iv'e been developing a Jqery plug-in to get the page ranks of urls on a website using XHR, The problem is when requesting the rank from google servers the page is returned no content, but if i use an inspector and get the url that was requests and go to it via my browser the pageranks are shown. so it must be something with headers but its just got me puzzled. Heres some source code but i have removed several aspects that are not needed to review. pagerank.plugin.js ( $.fn.PageRank = function(callback) { var _library = new Object(); //Creat the system library _library.parseUrl = function(a) { var b = {}; var a = a || ''; /* * parse the url to extract its parts */ if (a = a.match(/((s?ftp|https?):\/\/){1}([^\/:]+)?(:([0-9]+))?([^\?#]+)?(\?([^#]+))?(#(.+))?/)) { b.scheme = a[2] ? a[2] : "http"; b.host = a[3] ? a[3] : null; b.port = a[5] ? a[5] : null; b.path = a[6] ? a[6] : null; b.args = a[8] ? a[8] : null; b.anchor = a[10] ? a[10] : null } return b } _library.ValidUrl = function(url) { var b = true; return b = url.host === undefined ? false : url.scheme != "http" && url.scheme != "https" ? false : url.host == "localhost" ? false : true } _library.toHex = function(a){ return (a < 16 ? "0" : "") + a.toString(16) } _library.hexEncodeU32 = function(a) { } _library.generateHash = function(a) { for (var b = 16909125, c = 0; c < a.length; c++) { } return _library.hexEncodeU32(b) } var CheckPageRank = function(domain,_call) { var hash = _library.generateHash(domain); $.ajax( { url: 'http://www.google.com/search?client=navclient-auto&ch=8'+hash+'&features=Rank&q=info:' + escape(domain), async: true, dataType: 'html', ifModified:true, contentType:'', type:'GET', beforeSend:function(xhr) { xhr.setRequestHeader('Referer','http://google.com/'); //Set Referer }, success: function(content,textS,xhr){ var d = xhr.responseText.substr(9, 2).replace(/\s$/, ""); if (d == "" || isNaN(d * 1)) d = "0"; _call(d); } }); } //Return the callback $(this).each(function(){ urlsegments = _library.parseUrl($(this).attr('href')) if(_library.ValidUrl(urlsegments)) { CheckPageRank(urlsegments.host,function(rank){ alert(rank) callback(rank); }); } }); return this; //Dont break any chain. } )(jQuery); Index.html (example) <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script> <script type="text/javascript" src="pagerank.plugin.js"></script> <script type="text/javascript"> $(document).ready(function() { $('a').PageRank(function(pr){ alert(pr); }) }); </script> </head> <body> <a href="http://facebook.com">a</a> <a href="http://twitter.com">a</a> <div></div> </body> </html> i just cant understand why its doing this.

    Read the article

  • jQuery ajax in ASP.NET with customErrors mode="On"

    - by Adrian Magdas
    Hi, any idea how to retrieve the original exception thrown on server side when doing ajax calls with jQuery and using customErrors mode="On" in web.config. If mode="Off" I can take the error using this function: error: function(xhr, status, error) { var error = JSON.parse(xhr.responseText); alert(error.Message); } Thanks, Adrian

    Read the article

  • Preventing browser loading indicator with Chrome + GWT-rpc.

    - by Jeeyoung Kim
    Hello. I'm writing a ajax chatting webapp, just to test working with GWT. To simulate server side push of chat messages from the server to the browser, I have a XHR request running behind. It all works fine - except on Chrome, the browser is displaying a loading icon (a spinner) because of the XHR request on background. Is there any way to avoid this? I've tested it in Firefox, and it doesn't display such behavior.

    Read the article

  • Modifying jQuery ajax request Connectino header

    - by Pat
    I'm trying to modify the Connection header with the following code with no success jQuery.ajax ( { url: URL, async: boolVariable, beforeSend: function(xhr) { xhr.setRequestHeader("Connection", "close"); } } ) The request headers via Firebug show: Connection keep-alive X-Requested-With XMLHttpRequest Any odd bugs/problems with setting this particular header known? Or is there something I'm doing wrong?

    Read the article

  • jquery ajax encoding problem!

    - by teMkaa
    hi, i send ajax requests with jquery, and i have a function: $('input').ajaxSuccess(function(e, xhr, settings) { console.log(xhr.responseText); }); Ajax response ara russian letters in utf-8, all server (apache, php) and files are in utf-8 but response text is something like this: \u0421\u043b\u0438\u0448\u043a\u043e\u043c \u043c\u0430\u043b\u043e \u0431\u0443\u043a\u0432! how could i decode this characters to normal words? Thanks for help!

    Read the article

  • wcf - jquery - gridview (webform) binding

    - by Abu Hamzah
    i am using WCF to return my data and not sure how sure how i will bind the gridview once i get the data on the clientside? any help? ContactServiceProxy.invoke({ serviceMethod: "Holidays", callback: function(response) { //how to bind gridview here? }, error: function(xhr, errorMsg, thrown) { postErrorAndUnBlockUI(xhr, errorMsg, thrown); } });

    Read the article

  • Exceptions thrown in jQuery AJAX callbacks swallowed?

    - by MikeWyatt
    Is there any way to handle exceptions thrown from AJAX callbacks in jQuery, other than adding a try..catch block to each callback? The error function is not called in this situation. $.ajax( { url: 'myurl.rails', success: function( data ) { throw 'Oh no!'; }, error: function ( xhr, textStatus, errorThrown ) { console.log( 'AJAX call failed', xhr, textStatus, errorThrown ); } } );

    Read the article

  • facebook connect error

    - by coure06
    I am getting error but empty statusText, here is my code var ajaxUrl = 'https://graph.facebook.com/me?access_token=' + accessToken $.ajax({ url: ajaxUrl, dataType: 'json', success: function(user){ alert('h'); }, error: function(xhr, ajaxOptions, thrownError){ alert(xhr.statusText); } });

    Read the article

  • jquery ajax callback out of the function scope

    - by vasion
    function checkauth(){ jQuery.getJSON("/users/checkauthjson", null, function(xhr){ if(xhr.success){ return true;}else{ return false;} }); } Obviously, that does not work, but it illustrates what i want to achieve. I want checkauth to return a value which is checked against an ajax server script. How do i do this?

    Read the article

  • Metro, Authentication, and the ASP.NET Web API

    - by Stephen.Walther
    Imagine that you want to create a Metro style app written with JavaScript and you want to communicate with a remote web service. For example, you are creating a movie app which retrieves a list of movies from a movies service. In this situation, how do you authenticate your Metro app and the Metro user so not just anyone can call the movies service? How can you identify the user making the request so you can return user specific data from the service? The Windows Live SDK supports a feature named Single Sign-On. When a user logs into a Windows 8 machine using their Live ID, you can authenticate the user’s identity automatically. Even better, when the Metro app performs a call to a remote web service, you can pass an authentication token to the remote service and prevent unauthorized access to the service. The documentation for Single Sign-On is located here: http://msdn.microsoft.com/en-us/library/live/hh826544.aspx In this blog entry, I describe the steps that you need to follow to use Single Sign-On with a (very) simple movie app. We build a Metro app which communicates with a web service created using the ASP.NET Web API. Creating the Visual Studio Solution Let’s start by creating a Visual Studio solution which contains two projects: a Windows Metro style Blank App project and an ASP.NET MVC 4 Web Application project. Name the Metro app MovieApp and the ASP.NET MVC application MovieApp.Services. When you create the ASP.NET MVC application, select the Web API template: After you create the two projects, your Visual Studio Solution Explorer window should look like this: Configuring the Live SDK You need to get your hands on the Live SDK and register your Metro app. You can download the latest version of the SDK (version 5.2) from the following address: http://www.microsoft.com/en-us/download/details.aspx?id=29938 After you download the Live SDK, you need to visit the following website to register your Metro app: https://manage.dev.live.com/build Don’t let the title of the website — Windows Push Notifications & Live Connect – confuse you, this is the right place. Follow the instructions at the website to register your Metro app. Don’t forget to follow the instructions in Step 3 for updating the information in your Metro app’s manifest. After you register, your client secret is displayed. Record this client secret because you will need it later (we use it with the web service): You need to configure one more thing. You must enter your Redirect Domain by visiting the following website: https://manage.dev.live.com/Applications/Index Click on your application name, click Edit Settings, click the API Settings tab, and enter a value for the Redirect Domain field. You can enter any domain that you please just as long as the domain has not already been taken: For the Redirect Domain, I entered http://superexpertmovieapp.com. Create the Metro MovieApp Next, we need to create the MovieApp. The MovieApp will: 1. Use Single Sign-On to log the current user into Live 2. Call the MoviesService web service 3. Display the results in a ListView control Because we use the Live SDK in the MovieApp, we need to add a reference to it. Right-click your References folder in the Solution Explorer window and add the reference: Here’s the HTML page for the Metro App: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>MovieApp</title> <!-- WinJS references --> <link href="//Microsoft.WinJS.1.0.RC/css/ui-dark.css" rel="stylesheet" /> <script src="//Microsoft.WinJS.1.0.RC/js/base.js"></script> <script src="//Microsoft.WinJS.1.0.RC/js/ui.js"></script> <!-- Live SDK --> <script type="text/javascript" src="/LiveSDKHTML/js/wl.js"></script> <!-- WebServices references --> <link href="/css/default.css" rel="stylesheet" /> <script src="/js/default.js"></script> </head> <body> <div id="tmplMovie" data-win-control="WinJS.Binding.Template"> <div class="movieItem"> <span data-win-bind="innerText:title"></span> <br /><span data-win-bind="innerText:director"></span> </div> </div> <div id="lvMovies" data-win-control="WinJS.UI.ListView" data-win-options="{ itemTemplate: select('#tmplMovie') }"> </div> </body> </html> The HTML page above contains a Template and ListView control. These controls are used to display the movies when the movies are returned from the movies service. Notice that the page includes a reference to the Live script that we registered earlier: <!-- Live SDK --> <script type="text/javascript" src="/LiveSDKHTML/js/wl.js"></script> The JavaScript code looks like this: (function () { "use strict"; var REDIRECT_DOMAIN = "http://superexpertmovieapp.com"; var WEBSERVICE_URL = "http://localhost:49743/api/movies"; function init() { WinJS.UI.processAll().done(function () { // Get element and control references var lvMovies = document.getElementById("lvMovies").winControl; // Login to Windows Live var scopes = ["wl.signin"]; WL.init({ scope: scopes, redirect_uri: REDIRECT_DOMAIN }); WL.login().then( function(response) { // Get the authentication token var authenticationToken = response.session.authentication_token; // Call the web service var options = { url: WEBSERVICE_URL, headers: { authenticationToken: authenticationToken } }; WinJS.xhr(options).done( function (xhr) { var movies = JSON.parse(xhr.response); var listMovies = new WinJS.Binding.List(movies); lvMovies.itemDataSource = listMovies.dataSource; }, function (xhr) { console.log(xhr.statusText); } ); }, function(response) { throw WinJS.ErrorFromName("Failed to login!"); } ); }); } document.addEventListener("DOMContentLoaded", init); })(); There are two constants which you need to set to get the code above to work: REDIRECT_DOMAIN and WEBSERVICE_URL. The REDIRECT_DOMAIN is the domain that you entered when registering your app with Live. The WEBSERVICE_URL is the path to your web service. You can get the correct value for WEBSERVICE_URL by opening the Project Properties for the MovieApp.Services project, clicking the Web tab, and getting the correct URL. The port number is randomly generated. In my code, I used the URL  “http://localhost:49743/api/movies”. Assuming that the user is logged into Windows 8 with a Live account, when the user runs the MovieApp, the user is logged into Live automatically. The user is logged in with the following code: // Login to Windows Live var scopes = ["wl.signin"]; WL.init({ scope: scopes, redirect_uri: REDIRECT_DOMAIN }); WL.login().then(function(response) { // Do something }); The scopes setting determines what the user has permission to do. For example, access the user’s SkyDrive or access the user’s calendar or contacts. The available scopes are listed here: http://msdn.microsoft.com/en-us/library/live/hh243646.aspx In our case, we only need the wl.signin scope which enables Single Sign-On. After the user signs in, you can retrieve the user’s Live authentication token. The authentication token is passed to the movies service to authenticate the user. Creating the Movies Service The Movies Service is implemented as an API controller in an ASP.NET MVC 4 Web API project. Here’s what the MoviesController looks like: using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using JWTSample; using MovieApp.Services.Models; namespace MovieApp.Services.Controllers { public class MoviesController : ApiController { const string CLIENT_SECRET = "NtxjF2wu7JeY1unvVN-lb0hoeWOMUFoR"; // GET api/values public HttpResponseMessage Get() { // Authenticate // Get authenticationToken var authenticationToken = Request.Headers.GetValues("authenticationToken").FirstOrDefault(); if (authenticationToken == null) { return new HttpResponseMessage(HttpStatusCode.Unauthorized); } // Validate token var d = new Dictionary<int, string>(); d.Add(0, CLIENT_SECRET); try { var myJWT = new JsonWebToken(authenticationToken, d); } catch { return new HttpResponseMessage(HttpStatusCode.Unauthorized); } // Return results return Request.CreateResponse( HttpStatusCode.OK, new List<Movie> { new Movie {Title="Star Wars", Director="Lucas"}, new Movie {Title="King Kong", Director="Jackson"}, new Movie {Title="Memento", Director="Nolan"} } ); } } } Because the Metro app performs an HTTP GET request, the MovieController Get() action is invoked. This action returns a set of three movies when, and only when, the authentication token is validated. The Movie class looks like this: using Newtonsoft.Json; namespace MovieApp.Services.Models { public class Movie { [JsonProperty(PropertyName="title")] public string Title { get; set; } [JsonProperty(PropertyName="director")] public string Director { get; set; } } } Notice that the Movie class uses the JsonProperty attribute to change Title to title and Director to director to make JavaScript developers happy. The Get() method validates the authentication token before returning the movies to the Metro app. To get authentication to work, you need to provide the client secret which you created at the Live management site. If you forgot to write down the secret, you can get it again here: https://manage.dev.live.com/Applications/Index The client secret is assigned to a constant at the top of the MoviesController class. The MoviesController class uses a helper class named JsonWebToken to validate the authentication token. This class was created by the Windows Live team. You can get the source code for the JsonWebToken class from the following GitHub repository: https://github.com/liveservices/LiveSDK/blob/master/Samples/Asp.net/AuthenticationTokenSample/JsonWebToken.cs You need to add an additional reference to your MVC project to use the JsonWebToken class: System.Runtime.Serialization. You can use the JsonWebToken class to get a unique and validated user ID like this: var user = myJWT.Claims.UserId; If you need to store user specific information then you can use the UserId property to uniquely identify the user making the web service call. Running the MovieApp When you first run the Metro MovieApp, you get a screen which asks whether the app should have permission to use Single Sign-On. This screen never appears again after you give permission once. Actually, when I first ran the app, I get the following error: According to the error, the app is blocked because “We detected some suspicious activity with your Online Id account. To help protect you, we’ve temporarily blocked your account.” This appears to be a bug in the current preview release of the Live SDK and there is more information about this bug here: http://social.msdn.microsoft.com/Forums/en-US/messengerconnect/thread/866c495f-2127-429d-ab07-842ef84f16ae/ If you click continue, and continue running the app, the error message does not appear again.  Summary The goal of this blog entry was to describe how you can validate Metro apps and Metro users when performing a call to a remote web service. First, I explained how you can create a Metro app which takes advantage of Single Sign-On to authenticate the current user against Live automatically. You learned how to register your Metro app with Live and how to include an authentication token in an Ajax call. Next, I explained how you can validate the authentication token – retrieved from the request header – in a web service. I discussed how you can use the JsonWebToken class to validate the authentication token and retrieve the unique user ID.

    Read the article

  • Improving long-polling Ajax performance

    - by Bears will eat you
    I'm writing a webapp (Firefox-compatible only) which uses long polling (via jQuery's ajax abilities) to send more-or-less constant updates from the server to the client. I'm concerned about the effects of leaving this running for long periods of time, say, all day or overnight. The basic code skeleton is this: function processResults(xml) { // do stuff with the xml from the server } function fetch() { setTimeout(function () { $.ajax({ type: 'GET', url: 'foo/bar/baz', dataType: 'xml', success: function (xml) { processResults(xml); fetch(); }, error: function (xhr, type, exception) { if (xhr.status === 0) { console.log('XMLHttpRequest cancelled'); } else { console.debug(xhr); fetch(); } } }); }, 500); } (The half-second "sleep" is so that the client doesn't hammer the server if the updates are coming back to the client quickly - which they usually are.) After leaving this running overnight, it tends to make Firefox crawl. I'd been thinking that this could be partially caused by a large stack depth since I've basically written an infinitely recursive function. However, if I use Firebug and throw a breakpoint into fetch, it looks like this is not the case. The stack that Firebug shows me is only about 4 or 5 frames deep, even after an hour. One of the solutions I'm considering is changing my recursive function to an iterative one, but I can't figure out how I would insert the delay in between Ajax requests without spinning. I've looked at the JS 1.7 "yield" keyword but I can't quite wrap my head around it, to figure out if it's what I need here. Is the best solution just to do a hard refresh on the page periodically, say, once every hour? Is there a better/leaner long-polling design pattern that won't put a hurt on the browser even after running for 8 or 12 hours? Or should I just skip the long polling altogether and use a different "constant update" pattern since I usually know how frequently the server will have a response for me?

    Read the article

  • Try/Catch with jquery ajax request

    - by Anthony
    I am trying to build a Google Chrome extension that makes an ajax request. Something similar to the GMail Checker extension. The problem is that when I do the request using jquery, and I put in the wrong username/password, it fails silently, with the error callback function ignored. If I move the ajax call out of the background.html script (where I can't see the requests in the developer window), to the options.html script, I get a dialog box to re-authenticate. If I hit cancel, THEN the jquery error callback fires. But in the original model extension (again, the Gmail checker), they use plain (non-jquery) ajax calls with a try/catch, and if I put in the wrong credentials, I get an alert saying as much. I tried wrapping the entire jquery call in a try/catch, like so: try { $.ajax({ type: "POST", url: someurl, contentType : "text/xml", data: somedata, username: user, password: pass, success: function(data,status,xhr){ alert("Hurrah!"); }, error: function(xhr, status, error){ alert("Error!" + xhr.status); }, dataType: "xml" }); } catch(e) { alert("You messed something up!"); } But still nothing. Is the error due to it being asynchronous, or is Chrome not returning the request as an error since it wants to re-prompt for credentials? Or do I just not know how to use try/catch? Update Here is a very slimmed down version of how the model code does the request: var req = new XMLHttpRequest(); req.onreadystatechange = function() { try { if ( req.readyState == 4 ) { //Do some stuff with results } } catch (ex) { alert('Error parsing response.'); } } try { req.send (data); } catch (ex) { alert ('Something went wrong with the request.'); }

    Read the article

  • Redirect on Ajax Jquery Call

    - by Mark Estrada
    Hi, I am newbie to ajax here and I know somebody would have encountered this problem already. I have a legacy app built on Spring MVC, it has a interceptor(filter) that redirects the user to the login page whenever there is no session. public class SessionCheckerInterceptor extends HandlerInterceptorAdapter { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(); // check if userInfo exist in session User user = (User) session.getAttribute("user"); if (user == null) { response.sendRedirect("login.htm"); return false; } return true; } } For non-xmlhttp request, this works fine.. but when I try to use ajax in my application, everything gets weird, it is not able to redirect to the login page correctly. As check the value of the xhr.status = 200 textStatus = parseError errorThrown = "Invalid JSON -Markup of my HTML Login Page- $(document).ready(function(){ jQuery.ajax({ type: "GET", url: "populateData.htm", dataType:"json", data:"userId=SampleUser", success:function(response){ //code here }, error: function(xhr, textStatus, errorThrown) { alert('Error! Status = ' + xhr.status); } }); }); I checked on my firebug that there is a 302 HTTP response but I am not sure how to catch the response and redirect the user to the login page. Any idea here? Thanks.

    Read the article

  • Using jQuery and AJAX works for all functions except one, really bizarre issue (from my perspective)

    - by CoreyT
    I am working on a classic asp form that has a number of dropdowns. Three of these are cascading, i.e. they rely in the previous dropdown. For almost everything this code works fine, one of them however is not playing nice. To start off I have a script tag with the following in it: $(document).ready(function () { $("#AcademicLevel").change(getList); $("#CourseDeliveryTime").change(updateLocation); $("#ProgramType").change(updateEntryTerm); }); This works just fine for the first two elements of the form, AcademicLevel and CourseDeliveryTime, the third however does not take effect however. If I use Firebug's Console and run that same line of code, $("#ProgramType").change(updateEntryTerm);, it starts to work, sort of. What happens is what confuses me. If the function it is pointing to, updateEntryTerm, has an alert() call in it, it works. If the alert is commented out, it does not work. The function is below: function updateEntryTerm() { $.ajax({ type: "POST", url: "../Classic ASP and AJAX/jQueryExample.asp", dataType: "application/x-www-form-urlencoded", data: "Action=UpdateEntryTerm&acadLevel=" + $("#AcademicLevel").val() + "&courseTime=" + $("#CourseDeliveryTime").val() + "&programType=" + $("#ProgramType").val(), async: false, success: function (msg) { $("#EntryTerm").remove(); $("#tdEntryTerm").append(msg); //alert(msg); } //, //error: function (xhr, option, err) { // alert("XHR Status: " + xhr.statusText + ", Error - " + err); //} }); } I am lost on two different issues here, First why is the call to $("#ProgramType").change(updateEntryTerm); not working unless I run it in Firebug Console? Second, why does the function itself, updateEntryTerm, not work unless the alert() call is present? Has anyone seem something like this before?

    Read the article

  • Another IE Issue with AJAX

    - by Nik
    Alright, This code works in every browser except IE (again, to be expected). The code is supposed to refresh based on setInterval, and does so normally in all other browsers except IE, which just doesn't refresh. Can you spot the problem? var nick = document.getElementById("chatnick").value; var sessid = document.getElementById("sessid").value; var room = document.getElementById("roomid").value; function user_read() { $.ajax({ type: "GET", url: "methods.php", data: {method: "u", room: room}, dataType: "html", success: function (data, status, xhr) { $("#userwindow").html(data); setTimeout(user_read, 10000); } }); } function ajax_read() { $.ajax({ type: "GET", url: "methods.php", data: {method: "r", room: room}, dataType: "html", success: function (data, status, xhr) { $("#chatwindow").html(data); setTimeout(ajax_read, 400); } }); } function submit_msg() { var msg = document.getElementById("chatmsg").value; $.ajax({ type: "GET", url: "methods.php", data: {method: "w", room: room, m: msg, n: nick, sessid: sessid}, dataType: "html", success: function (data, status, xhr) { } }); document.getElementById("chatmsg").value = ""; } function keyup(arg1) { if (arg1 == 13) submit_msg(); } setTimeout(function(){ajax_read();}, 400); user_read();

    Read the article

  • Chrome extension sendRequest from async callback not working?

    - by Eugene
    Can't figure out what's wrong. onRequest not triggered on call from async callback method, the same request from content script works. The sample code below. background.js ============= ... makeAsyncRequest(); ... chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { switch (request.id) { case "from_content_script": // This works console.log("from_content_script"); sendResponse({}); // clean up break; case "from_async": // Not working! console.log("from_async"); sendResponse({}); // clean up break; } }); methods.js ========== makeAsyncRequest = function() { ... var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { ... // It works console.log("makeAsyncRequest callback"); chrome.extension.sendRequest({id: "from_async"}, function(response) { }); } } ... }; UPDATE: manifest configuration file. Don't no what's wrong here. { "name": "TestExt", "version": "0.0.1", "icons": { "48": "img/icon-48-green.gif" }, "description": "write it later", "background_page": "background.html", "options_page": "options.html", "browser_action": { "default_title": "TestExt", "default_icon": "img/icon-48-green.gif" }, "permissions": [ "tabs", "http://*/*", "https://*/*", "file://*/*", "webNavigation" ] }

    Read the article

  • Pass object from JSON into MVC Controller - its always null ?

    - by SteveCl
    Hi I have seen a few questions on here related to the a similar issue, I have read them, followed them, but still i have the same problem. I am basically creating an object in javascript and trying to call a method on the controller that will return a string of html. Not JSON. I've been playing around with dataType and contentType but still no joy. So apologies if the code snippets are a bit messy. Build the object in JS. function GetCardModel() { var card = {}; card.CardTitle = $("#CardTitle").val(); card.TopicTitle = $("#TopicTitle").val(); card.TopicBody = $("#TopicBody").data("tEditor").value(); card.CardClose = $("#CardClose").val(); card.CardFromName = $("#CardFromName").val(); return card; } Take a look at the object - all looks good and as it should in JSON. var model = GetCardModel(); alert(JSON.stringify(GetCardModel())); Make the call... $.ajax({ type: "POST", url: "/Postcard/Create/Preview/", dataType: "json", //contentType: "application/json", date: GetCardModel(), processData: true, success: function (data) { alert("im back"); alert(data); }, error: function (xhr, ajaxOptions, error) { alert(xhr.status); alert("Error: " + xhr.responseText); //alert(error); } }); Always when I step into the controller, the object is ALWAYS there, but with null values for all the properties.

    Read the article

  • Couchdb failing test suite on Linux

    - by user52674
    Hi I've been trying to install CouchDB on my webfusion virtual server. I followed the latest instructions from the webfusion forum (see: http://forum.webfaction.com/viewtopic.php?id=2355 ) and it runs (just) Futon is very sluggish and I get 502 errors. Anyway when I run the test suite it fails on multiple tests. Webfaction support have been great but don't have erlang experience to interpret the error logs. Can anyone help me know what might be wrong? Test suite result: basics, all_docs, attachments, attachments_multipart, attachment_names, compact, config, conflicts, delayed_commits, design_docs, design_options all the errors are: Exception raised: {"error":"unknown","reason":"\u000d\u000a502 Bad Gateway\u000d\u000a\u000d\u000a<\h1502 Bad Gateway\u000d\u000a nginx\u000d\u000a\u000d\u000a\u000d\u000a"} except for 'compact; which also has: Assertion failed: xhr.responseText == "This is a base64 encoded text" Assertion failed: xhr.getResponseHeader("Content-Type") == "text/plain" I'm stumped. Anybody know what these indicate? AL

    Read the article

  • Passing multiple POST parameters to Web API Controller Methods

    - by Rick Strahl
    ASP.NET Web API introduces a new API for creating REST APIs and making AJAX callbacks to the server. This new API provides a host of new great functionality that unifies many of the features of many of the various AJAX/REST APIs that Microsoft created before it - ASP.NET AJAX, WCF REST specifically - and combines them into a whole more consistent API. Web API addresses many of the concerns that developers had with these older APIs, namely that it was very difficult to build consistent REST style resource APIs easily. While Web API provides many new features and makes many scenarios much easier, a lot of the focus has been on making it easier to build REST compliant APIs that are focused on resource based solutions and HTTP verbs. But  RPC style calls that are common with AJAX callbacks in Web applications, have gotten a lot less focus and there are a few scenarios that are not that obvious, especially if you're expecting Web API to provide functionality similar to ASP.NET AJAX style AJAX callbacks. RPC vs. 'Proper' REST RPC style HTTP calls mimic calling a method with parameters and returning a result. Rather than mapping explicit server side resources or 'nouns' RPC calls tend simply map a server side operation, passing in parameters and receiving a typed result where parameters and result values are marshaled over HTTP. Typically RPC calls - like SOAP calls - tend to always be POST operations rather than following HTTP conventions and using the GET/POST/PUT/DELETE etc. verbs to implicitly determine what operation needs to be fired. RPC might not be considered 'cool' anymore, but for typical private AJAX backend operations of a Web site I'd wager that a large percentage of use cases of Web API will fall towards RPC style calls rather than 'proper' REST style APIs. Web applications that have needs for things like live validation against data, filling data based on user inputs, handling small UI updates often don't lend themselves very well to limited HTTP verb usage. It might not be what the cool kids do, but I don't see RPC calls getting replaced by proper REST APIs any time soon.  Proper REST has its place - for 'real' API scenarios that manage and publish/share resources, but for more transactional operations RPC seems a better choice and much easier to implement than trying to shoehorn a boatload of endpoint methods into a few HTTP verbs. In any case Web API does a good job of providing both RPC abstraction as well as the HTTP Verb/REST abstraction. RPC works well out of the box, but there are some differences especially if you're coming from ASP.NET AJAX service or WCF Rest when it comes to multiple parameters. Action Routing for RPC Style Calls If you've looked at Web API demos you've probably seen a bunch of examples of how to create HTTP Verb based routing endpoints. Verb based routing essentially maps a controller and then uses HTTP verbs to map the methods that are called in response to HTTP requests. This works great for resource APIs but doesn't work so well when you have many operational methods in a single controller. HTTP Verb routing is limited to the few HTTP verbs available (plus separate method signatures) and - worse than that - you can't easily extend the controller with custom routes or action routing beyond that. Thankfully Web API also supports Action based routing which allows you create RPC style endpoints fairly easily:RouteTable.Routes.MapHttpRoute( name: "AlbumRpcApiAction", routeTemplate: "albums/{action}/{title}", defaults: new { title = RouteParameter.Optional, controller = "AlbumApi", action = "GetAblums" } ); This uses traditional MVC style {action} method routing which is different from the HTTP verb based routing you might have read a bunch about in conjunction with Web API. Action based routing like above lets you specify an end point method in a Web API controller either via the {action} parameter in the route string or via a default value for custom routes. Using routing you can pass multiple parameters either on the route itself or pass parameters on the query string, via ModelBinding or content value binding. For most common scenarios this actually works very well. As long as you are passing either a single complex type via a POST operation, or multiple simple types via query string or POST buffer, there's no issue. But if you need to pass multiple parameters as was easily done with WCF REST or ASP.NET AJAX things are not so obvious. Web API has no issue allowing for single parameter like this:[HttpPost] public string PostAlbum(Album album) { return String.Format("{0} {1:d}", album.AlbumName, album.Entered); } There are actually two ways to call this endpoint: albums/PostAlbum Using the Model Binder with plain POST values In this mechanism you're sending plain urlencoded POST values to the server which the ModelBinder then maps the parameter. Each property value is matched to each matching POST value. This works similar to the way that MVC's  ModelBinder works. Here's how you can POST using the ModelBinder and jQuery:$.ajax( { url: "albums/PostAlbum", type: "POST", data: { AlbumName: "Dirty Deeds", Entered: "5/1/2012" }, success: function (result) { alert(result); }, error: function (xhr, status, p3, p4) { var err = "Error " + " " + status + " " + p3; if (xhr.responseText && xhr.responseText[0] == "{") err = JSON.parse(xhr.responseText).message; alert(err); } }); Here's what the POST data looks like for this request: The model binder and it's straight form based POST mechanism is great for posting data directly from HTML pages to model objects. It avoids having to do manual conversions for many operations and is a great boon for AJAX callback requests. Using Web API JSON Formatter The other option is to post data using a JSON string. The process for this is similar except that you create a JavaScript object and serialize it to JSON first.album = { AlbumName: "PowerAge", Entered: new Date(1977,0,1) } $.ajax( { url: "albums/PostAlbum", type: "POST", contentType: "application/json", data: JSON.stringify(album), success: function (result) { alert(result); } }); Here the data is sent using a JSON object rather than form data and the data is JSON encoded over the wire. The trace reveals that the data is sent using plain JSON (Source above), which is a little more efficient since there's no UrlEncoding that occurs. BTW, notice that WebAPI automatically deals with the date. I provided the date as a plain string, rather than a JavaScript date value and the Formatter and ModelBinder both automatically map the date propertly to the Entered DateTime property of the Album object. Passing multiple Parameters to a Web API Controller Single parameters work fine in either of these RPC scenarios and that's to be expected. ModelBinding always works against a single object because it maps a model. But what happens when you want to pass multiple parameters? Consider an API Controller method that has a signature like the following:[HttpPost] public string PostAlbum(Album album, string userToken) Here I'm asking to pass two objects to an RPC method. Is that possible? This used to be fairly straight forward either with WCF REST and ASP.NET AJAX ASMX services, but as far as I can tell this is not directly possible using a POST operation with WebAPI. There a few workarounds that you can use to make this work: Use both POST *and* QueryString Parameters in Conjunction If you have both complex and simple parameters, you can pass simple parameters on the query string. The above would actually work with: /album/PostAlbum?userToken=sekkritt but that's not always possible. In this example it might not be a good idea to pass a user token on the query string though. It also won't work if you need to pass multiple complex objects, since query string values do not support complex type mapping. They only work with simple types. Use a single Object that wraps the two Parameters If you go by service based architecture guidelines every service method should always pass and return a single value only. The input should wrap potentially multiple input parameters and the output should convey status as well as provide the result value. You typically have a xxxRequest and a xxxResponse class that wraps the inputs and outputs. Here's what this method might look like:public PostAlbumResponse PostAlbum(PostAlbumRequest request) { var album = request.Album; var userToken = request.UserToken; return new PostAlbumResponse() { IsSuccess = true, Result = String.Format("{0} {1:d} {2}", album.AlbumName, album.Entered,userToken) }; } with these support types:public class PostAlbumRequest { public Album Album { get; set; } public User User { get; set; } public string UserToken { get; set; } } public class PostAlbumResponse { public string Result { get; set; } public bool IsSuccess { get; set; } public string ErrorMessage { get; set; } }   To call this method you now have to assemble these objects on the client and send it up as JSON:var album = { AlbumName: "PowerAge", Entered: "1/1/1977" } var user = { Name: "Rick" } var userToken = "sekkritt"; $.ajax( { url: "samples/PostAlbum", type: "POST", contentType: "application/json", data: JSON.stringify({ Album: album, User: user, UserToken: userToken }), success: function (result) { alert(result.Result); } }); I assemble the individual types first and then combine them in the data: property of the $.ajax() call into the actual object passed to the server, that mimics the structure of PostAlbumRequest server class that has Album, User and UserToken properties. This works well enough but it gets tedious if you have to create Request and Response types for each method signature. If you have common parameters that are always passed (like you always pass an album or usertoken) you might be able to abstract this to use a single object that gets reused for all methods, but this gets confusing too: Overload a single 'parameter' too much and it becomes a nightmare to decipher what your method actual can use. Use JObject to parse multiple Property Values out of an Object If you recall, ASP.NET AJAX and WCF REST used a 'wrapper' object to make default AJAX calls. Rather than directly calling a service you always passed an object which contained properties for each parameter: { parm1: Value, parm2: Value2 } WCF REST/ASP.NET AJAX would then parse this top level property values and map them to the parameters of the endpoint method. This automatic type wrapping functionality is no longer available directly in Web API, but since Web API now uses JSON.NET for it's JSON serializer you can actually simulate that behavior with a little extra code. You can use the JObject class to receive a dynamic JSON result and then using the dynamic cast of JObject to walk through the child objects and even parse them into strongly typed objects. Here's how to do this on the API Controller end:[HttpPost] public string PostAlbum(JObject jsonData) { dynamic json = jsonData; JObject jalbum = json.Album; JObject juser = json.User; string token = json.UserToken; var album = jalbum.ToObject<Album>(); var user = juser.ToObject<User>(); return String.Format("{0} {1} {2}", album.AlbumName, user.Name, token); } This is clearly not as nice as having the parameters passed directly, but it works to allow you to pass multiple parameters and access them using Web API. JObject is JSON.NET's generic object container which sports a nice dynamic interface that allows you to walk through the object's properties using standard 'dot' object syntax. All you have to do is cast the object to dynamic to get access to the property interface of the JSON type. Additionally JObject also allows you to parse JObject instances into strongly typed objects, which enables us here to retrieve the two objects passed as parameters from this jquery code:var album = { AlbumName: "PowerAge", Entered: "1/1/1977" } var user = { Name: "Rick" } var userToken = "sekkritt"; $.ajax( { url: "samples/PostAlbum", type: "POST", contentType: "application/json", data: JSON.stringify({ Album: album, User: user, UserToken: userToken }), success: function (result) { alert(result); } }); Summary ASP.NET Web API brings many new features and many advantages over the older Microsoft AJAX and REST APIs, but realize that some things like passing multiple strongly typed object parameters will work a bit differently. It's not insurmountable, but just knowing what options are available to simulate this behavior is good to know. Now let me say here that it's probably not a good practice to pass a bunch of parameters to an API call. Ideally APIs should be closely factored to accept single parameters or a single content parameter at least along with some identifier parameters that can be passed on the querystring. But saying that doesn't mean that occasionally you don't run into a situation where you have the need to pass several objects to the server and all three of the options I mentioned might have merit in different situations. For now I'm sure the question of how to pass multiple parameters will come up quite a bit from people migrating WCF REST or ASP.NET AJAX code to Web API. At least there are options available to make it work.© 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

  • Passing Custom Headers to Ajax request on Select2

    - by Sutikshan Dubey
    We are trying to implement Ajax Remote data loading in Select2:- $scope.configPartSelect2 = { minimumInputLength: 3, ajax: { url: "/api/Part", // beforeSend: function (xhr) { xhr.setRequestHeader('Authorization-Token', http.defaults.headers.common['Authorization-Token']); }, // headers: {'Authorization-Token': http.defaults.headers.common['Authorization-Token']}, data: function (term, page) { return {isStockable: true}; }, results: function (data, page) { // parse the results into the format expected by Select2. // since we are using custom formatting functions we do not need to alter remote JSON data return { results: data }; } } }; We are using AngularJS. With each Http request we have set it's default to have our Authtoken as header. But somehow it is not working in conjunction with Select2 Ajax request. In above code, commented code are my failed attempts.

    Read the article

  • Weird "406 not acceptable" error

    - by Horace Loeb
    When I try to hit this action via Javascript, I get a 406 Not Acceptable error: def show @annotation = Annotation.find_by_id(params[:id]) respond_to do |format| format.html { if @annotation.blank? redirect_to root_path else redirect_to inline_annotation_path(@annotation) end } format.js { if params[:format] == "raw" render :text => @annotation.body.to_s else render :text => @annotation.body.to_html end } end end This is from jQuery, but I'm doing the right beforeSend stuff: $.ajaxSetup({ beforeSend: function(xhr) { xhr.setRequestHeader("Accept", "text/javascript"); }, cache: false }); Here are my request headers: Host localhost:3000 User-Agent Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 Accept text/javascript Accept-Language en-us,en;q=0.5 Accept-Encoding gzip,deflate Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive 300 Connection keep-alive X-Requested-With XMLHttpRequest Content-Type application/x-www-form-urlencoded

    Read the article

  • Can you handle both json and html datatypes in the same ajax call?

    - by Prabhu
    Is there anyway I can handle both json and html return types when posting jquery ajax: For example, this ajax call expects html back $.ajax({ type: "POST", url: url data: data, dataType: "html", success: function (response) { var $html = "<li class='list-item'>" + response + "</li>"; $('#a').prepend($html); }, error: function (xhr, status, error) { alert(xhr.statusText); } }); but I wanted to modify it so that I can return a json object if there is a model error. so I can do something like this: success: function (response) { if (response.Error){ alert(response.Message); } else { var $html = "<li class='list-item'>" + response + "</li>"; $('#a').prepend($html); } Is this possible?

    Read the article

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