I recently tested A LOT of different syntax for sending an ajax post request, and the only one which actually worked was the one I got from my Postman testing. The only problem I have now is the Postman code snippet is "hardcoded" and features a weird string syntax I have never seen before. I want to replace parts of that weird string with values from HTML inputs. Any ideas how I can achieve this?
I have two simple HTML inputs:
<input type="text" id="username" name="username" placeholder="Username" autofocus />
<input type="password" id="password" name="password" placeholder="Password" />
And here is the part I got from Postman (JavaScript):
var settings = {
"async": true,
"crossDomain": true,
"url": "...",
"method": "POST",
"headers": {
"Content-Type": "application/json",
"cache-control": "no-cache"
},
"processData": false,
"data": "{ \r\n\"Username\":\"username123\",\r\n\"Password\":\"password123\"\r\n}"
}
$.ajax(settings).done(function(response) {
console.log(response);
});
Specifically, the part I'm asking about is the "data" line. I want to be able to take the values from the two HTML inputs, and replace "username123" and "password123" with them respectively. I have tried playing around with the data string, like removing \r\n and some " and \ , but then I get an error from the API I'm trying to call to. Do I really need all those? To be clear, I'm wondering how to put my variables into the string using valid syntax, not how to get the values like for example:
var usname = document.getElementById("username").val();
or
var usname = $('#username').val();
And these JSON syntax are tested and recieves an error:
"data": {"Username": "username123","Password": "password123"}
"data": "{"Username": "username123", "Password": "password123"}"
"data": {"Username": usname, "Password": pword}
"data": {"Username": $('username').val(), "Password": $('password').val()}
I feel like at least the first one should work, but it just comes back with error 500. For reference, here's what the body (data) looks like in Postman (working):
{
"Username":"username123",
"Password":"password123"
}
Could it be an issue with whitespace or something? I sadly don't have access to the source code of the API I'm calling.