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 Answers 3

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);
Sign up to request clarification or add additional context in comments.

5 Comments

This actually worked, so simple! I'm so grateful, thank you very much! :)
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
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
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
@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 :)
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"/>

Comments

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

4 Comments

@BeistBeistson I added another alternative, and updated the first one, just in case.
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?
Maybe you can try to setup a success and error callback on the settings, as documented here, and log the responses in both cases to check what you get.
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: stackoverflow.com/questions/14754619/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.