1

Possible Duplicate:
Convert form data to JS object with jQuery

I need to login my users to external website, but there's a problem, this website processes only json-data POST values, ex. {"username":"user","password":"12345"}

<form action="https://external.com/login" method="POST">
<input name="username" value="user" />
<input name="password" value="12345" />
<input type="submit" />
</form>

This above only sends average key=value data, how can I use to POST json-data to external https?

Community
  • 1
  • 1
user1482261
  • 191
  • 3
  • 15
  • Have you check this : https://stackoverflow.com/questions/1184624/convert-form-data-to-javascript-object-with-jquery/39248551#39248551 – Bhavik Hirani Mar 26 '18 at 08:01

1 Answers1

0

Here is a simple jquery example using jQuery.ajax()

HTML:

<form action="https://external.com/login" method="POST" onsubmit="return postJson(this)">
<input name="username" value="user" />
<input name="password" value="12345" />
<input type="submit" />
</form>

JQ:

function postJson(form) {
    var action = $(form).attr('action');
    var user = $('[name="username"]', form).val();
    var pass = $('[name="password"]', form).val();

    console.log('action=' + action + ', user=' + user + ', pass=' + pass);

    $.ajax({
        url: action,
        type: 'POST',
        data: JSON.stringify({ username: user, password: pass }),
        success: function(data, status) {
            // do something after login
            console.log('success');
        },
        error: function() {
            console.log('error');
        }
    });

    return false;
}

JSFiddle

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198