0

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.

3 Answers3

1

I suggest to use a FormData to wrap the data you are going to send:

var formData = new FormData();
formData.append('Username', $("#username").val());
formData.append('Password', $("#password").val());

And later, you call the ajax post like this:

var settings = {
    "async": true,
    "crossDomain": true,
    "url": "...",
    "method": "POST",
    "contentType": 'application/x-www-form-urlencoded',
    "processData": false,
    "data": formData
};

$.ajax(settings).done(function(response)
{
    console.log(response);
});

If you need to send data as JSON then you can give a try to next code:

var data = {};
data.Username = $("#username").val();
data.Password = $("#password").val();

var settings = {
    "async": true,
    "crossDomain": true,
    "url": "...",
    "method": "POST",
    "headers": {
        "Content-Type": "application/json",
        "cache-control": "no-cache"
    },
    "processData": false,
    "data": JSON.stringify(data)
};

$.ajax(settings).done(function(response)
{
    console.log(response);
});
Shidersz
  • 16,846
  • 2
  • 23
  • 48
  • @BeistBeistson I added another alternative, and updated the first one, just in case. – Shidersz Apr 20 '19 at 20:26
  • Tried the alternative also, now I do not get any error, but I aslo don't get any response at all, the page just refreshes as if nothing happened. The only change I did compared to the working code was replace the weird string with the new data variable you set up. But hey, no error message, which probably means the fault lies somewhere else? – Beist Beistson Apr 20 '19 at 20:50
  • Maybe you can try to setup a `success` and `error` callback on the settings, as documented [here](http://api.jquery.com/jquery.ajax/), and log the responses in both cases to check what you get. – Shidersz Apr 20 '19 at 21:01
  • I'm sorry I don't have time to try that out tonight, deadline coming up. But I'm pretty sure I had success and error callbacks in my (the same) code yesterday, and nothing got logged, it just refreshed the page like now. Earlier today I stumbled upon Alnitaks answer (the one under the solution) and decided not to go for success and error callbacks: https://stackoverflow.com/questions/14754619/jquery-ajax-success-callback-function-definition – Beist Beistson Apr 20 '19 at 21:18
1

I'm wondering how to put my variables into the string using valid syntax

settings.data = settings.data.replace("username123", usname);
settings.data = settings.data.replace("password123", uspassword);
0xnoob
  • 937
  • 5
  • 7
  • This actually worked, so simple! I'm so grateful, thank you very much! :) – Beist Beistson Apr 20 '19 at 20:13
  • But hey, it worked! If I may, I'd like to ask a follow up question to this "solution". If I'd like to replace something inside the header of the (almost) same settings variable, how would I do that? I've tried settings.headers.Authorization = settings.headers.Authorization.replace("example", newVariable);. Would this be the correct way/syntax? Right now I get "undefined" as result, but it may be because I did something wrong elsewhere in the script. @0xnoob – Beist Beistson Apr 20 '19 at 20:42
  • According to your example of the `settings` variable, Authorization isn't defined in the headers object right now, so you can't replace it. simply do `settings.headers.Authorization = newVariable;`, but also keep in mind that this is *realy* hacky. @BeistBeistson – 0xnoob Apr 20 '19 at 20:51
  • This is for a new function, I'm doing GET this time and I need the Authorization header containing the token I got from the POST request we just did. It is defined in this new function. I don't mind it being really hacky right now, I just need it to work so I can move on to the next step of my project. I can come back and try another solution when I don't have a deadline coming up :) @0xnoob – Beist Beistson Apr 20 '19 at 20:58
  • @0xnoob I got it working. I had the right syntax, but my new function ran before I had finished getting the token. So after setting a small timeout on the new function, it works :) – Beist Beistson Apr 20 '19 at 21:09
1

For formatting the data as JSON and the be able to use its properties for different purposes:

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}"
            };

    //remove line breaks
    settings.data = settings.data.replace('/\r?\n|\r/', '');

    //convert to properties
    settings.data = JSON.parse(settings.data);

    //re-assign properties as needed
    settings.data.Username = 'newUsername';
    settings.data.Password = document.getElementById('password').value;

    console.log(settings.data);
<input type="password" id="password" name="password" placeholder="Password" value="newPassword"/>
Mihai
  • 371
  • 3
  • 14