QSpider QSpider - 8 months ago 36
Ajax Question

Using ajax in Servant

I use Haskell with

fo realisation server.Below is my source code:

type UserRestAPI
= "rest" :> "users" :> Get '[JSON] [User]
:<|> "rest" :> "user" :> ReqBody '[JSON] User :> Post '[PlainText] Text

serverUserRestAPI :: ServerT UserRestAPI AppM
serverUserRestAPI = usersGet :<|> userPost

userPost :: User -> AppM Text
userPost user = do
newUser <- runDb $ do insert user
liftIO $ putStrLn $ show newUser
return $ append (toPathPiece newUser) "\r\n"

The model of

let mongoSettings = (mkPersistSettings (ConT ''MongoContext)) {mpsGeneric = False}
in share [mkPersist mongoSettings, mkMigrate "migrateAll"] [persistLowerCase|
fam String
im String
ot String
email String
login String
pswd String
deriving Show

$(deriveJSON defaultOptions ''User)

For testin
was used, as shown below.

curl --verbose --request POST --header "Content-Type: application/json" \
--data '{"userFam": "Fam", "userIm": "Im", "userOt": "Ot", "userEmail": "mail@mail.ru", "userLogin": "test", "userPswd": "test"}' \

Everything is working. The data added to the database.But when I use
from backend, as shown below.

var formElement = $("#id_form");
var formData = formElement.serializeArray();

var objectData = {};

for(var i = 0; i < formData.length; i++)
objectData[formData[i].name] = formData[i].value;

type: "POST",
async: true,
url: "/rest/user",
dataType: "text",
cache : false,
contentType : "application/json",
data: objectData,
success: function(result){
error: function(jqXHR, status, err) {

I get an error!

jquery.js:4 POST 400 (Bad Request)

The debugger checked object
. All right (
Object {userFam: "qqq", userIm: "www", userOt: "eee", userEmail: "rrr", userLogin: "ttt"…}
I can not understand what was going on.


it's really a problem with your ajax call as you don't provide a valid JSON object but just objectData.toString() as data: - the common solution is to use JSON.stringify:

    type: "POST",
    async: true,
    url: "/rest/user",
    dataType: "json",
    cache : false,
    data: JSON.stringify(objectData),
    success: function(result){
         // ...
    error: function(jqXHR, status, err) {

another great example what is wrong with untyped languages ;)