jaffa
jaffa

Reputation: 27370

Why is an ajax post with json content type sending data url encoded?

Why is this call showing the values encoded onto the URL like so?

http://localhost:49597/api/auth?user=jon&password=123

Am using the following ajax call...

$.ajax({ url: "api/auth",
 type: "get", 
 data: { user: "jon", password: "123" },
 dataType: "json", 
 contentType: "application/json; charset=utf-8" 
});

I want the data to be sent as json...

Upvotes: 1

Views: 1580

Answers (3)

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

Because the code specifies a request of type GET. A GET request passes the parameters via a query string. You should switch to a post if you do not want to use a query string.

$.ajax({ url: "api/auth",
 type: "post", 
 data: { user: "jon", password: "123" },
 dataType: "json", 
 contentType: "application/json; charset=utf-8" 
});

Upvotes: 1

Shyju
Shyju

Reputation: 218962

Because it is a GET request.

GET will send data in the querystring. If you want to avoid that, you can change your type to POST POST will send the data in the request body.

$.ajax({ url: "api/auth",
 type: "post", 
  //other stuff
});

If it is a Login form, you should probably use POST method.

Upvotes: 1

thatidiotguy
thatidiotguy

Reputation: 9011

GET requests do not have a request body, therefore all info must be stored in url as query parameters. I would also recommend not authenticating users with Javascript, and would definitely make that a POST request.

Upvotes: 1

Related Questions