Search code examples
jqueryajaxrestdecodeencode

Embedding json to jquery ajax GET request


I want to use jQuery's ajax call with type 'GET' against my RESTful API running on Flask. In my request I want to post some data as JSON.

I'm doing the exact same thing for POST requests and they work like charm. But with GET Flask gives me 400 errors and looking deeper into it it seems that the JSON gets partly URIEncoded on the way ({%22email%22:%[email protected]%22}).

I've tried to use decodeURIComponent as I'm JSON.stringifying the json in the ajax data parameter but makes no difference.

sessiontoken = "123abc";
jsonData = {"email": email};

$.ajax({
    type: 'GET',
    crossDomain: true,
    url: 'http://someserver/sessions/' + sessiontoken,
    dataType: 'json',
    processData: false, //added this to see if it helps, it didn't 
    contentType: "application/json",
    async: false,
    data: JSON.stringify(jsonData),
    success: function(data){
        //I'd be happy
    },
    error: function(data){
        //This is where I get as my backend throws a 400 on me due to the screwed up json
    }
});

It's driving me nuts as I can't seem to find anyone on the planet who's had the same issue. I've been ajaxing requests before and never faced this silly thing in the past.

Edit: Ok it seems like I need to give up on my goal and just pass whatever parameters as query string instead of trying to add them to the request body. I guess there is nothing wrong with that as discussed for example here: REST API Best practices: Where to put parameters?


Solution

  • If you trying to set any data to GET request of ajax, it will be converted to parameters of URL string. Ofcourse any symbols like " will be represented as %URL_CODE (see all codes), and you will get query like next:

    http://someserver/sessions/sessiontoken?{%22email%22:%[email protected]%22}
    

    Best way to organize your restful service is descript queries in URI parts. Another way you could put json into URL parameters, and parse url codes for symbols on server-side.