nihulus
nihulus

Reputation: 1495

To POST value of GET by using jQuery

I need to POST a user name from a list of users that used GET from a server, but how to POST that user name as a string. Any help is appreciated, thanks in advance!

  //get a list of users from server side
$.getJSON(
  '/userlist',
  function(data) {
    var user = data.users;
    $("#utbildning").text(user[1].username);
    $("#tekniker").text(user[2].username);
  }
);

//post user name and password at login  
$(document).ready(function() {
  $("#knapp").click(function(){

    //name of the user should be a name from the user list comes from server
    var name=$.getJSON(
      '/userlist',
      function(data) {
        var user = data.users;
        user[1].username;
      }
    );
    var pass=$("#kod").val(); //password from input field
    var data = new Object();
    data["username"] = name;
    data["password"] = pass;

    $.ajax(
      {
         url: "/login",
         data: JSON.stringify(data),
         processData: false,
         type: 'POST',
         contentType: 'application/json',
      }
    );
  });
})

Upvotes: 0

Views: 301

Answers (1)

Michael Laffargue
Michael Laffargue

Reputation: 10304

Multiple errors:

  • Unless big changes you won't get anything using var name = $.getJson(...
  • Then as $.getJSON is asynchronous, you should do whatever uses variable set from the ajax call in the $.getJSON callback method. as you do in your first call.

Here is a "corrected" version (well if your code is correct though):

  //get a list of users from server side
$.getJSON(
  '/userlist',
  function(data) {
    var user = data.users;
    $("#utbildning").text(user[1].username);
    $("#tekniker").text(user[2].username);
  }
);

//post user name and password at login  
$(document).ready(function() {
  $("#knapp").click(function(){

    //name of the user should be a name from the user list comes from server
    $.getJSON(
      '/userlist',
      function(data) {
        var user = data.users;
        var name = user[1].username;
        var pass=$("#kod").val(); //password from input field
        var data = new Object();
        data["username"] = name;
        data["password"] = pass;

        $.ajax(
          {
             url: "/login",
             data: JSON.stringify(data),
             processData: false,
             type: 'POST',
             contentType: 'application/json',
          }
        );
      }
    );
  });
})

Upvotes: 1

Related Questions