Problem with POST in Javascript + Ajax

1

I'm taking a test, and I need to develop a signup screen using the GitHub API link . .. Here is the code:

//Add repositories on GitHub
$('#add-repository').submit(function(e){
  e.preventDefault();

  $.ajax({
    method: 'post',
    url: 'https://api.github.com/user/repos',
    beforeSend: function(xhr) {
      xhr.setRequestHeader("Authorization", "token mytoken");
    },
    data: '{"name": "test","description":"repos test","homepage": "https://test.com","auto_init":true}'
  }).done(function(e){
    console.log(e);
  });
});

The following way it works .. however I want to get the POST data and pass on the date ..

//Add repositories on GitHub
$('#add-repository').submit(function(e){
  e.preventDefault();
  var form = $(this).serialize();

  $.ajax({
    method: 'post',
    url: 'https://api.github.com/user/repos',
    beforeSend: function(xhr) {
      xhr.setRequestHeader("Authorization", "token mytoken");
    },
    data: form
  }).done(function(e){
    console.log(e);
  });
});

I tried this way but it returns error 400 (Bad Request).

//Add repositories on GitHub
$('#add-repository').submit(function(e){
  e.preventDefault();
  var name = $("#name").val();
  var description = $("#description").val();
  var homepage = $("#homepage").val();

  $.ajax({
    method: 'post',
    url: 'https://api.github.com/user/repos',
    beforeSend: function(xhr) {
      xhr.setRequestHeader("Authorization", "token mytoken");
    },
    data: '{"name": '+name+',"description": '+description+',"homepage": '+homepage+',"auto_init":true}'
  }).done(function(e){
    console.log(e);
  });
});

So the same error returns, only the first example registers the repository, but I need to receive the data passed in the form THANKS!

    
asked by anonymous 14.07.2017 / 21:00

1 answer

0

Problem was solved as follows:

//Add repositories on GitHub
$('#add-repository').submit(function(e){
e.preventDefault();
var name = $("#name").val();
var description = $("#description").val();
var homepage = $("#homepage").val();

  $.ajax({
    method: 'post',
    url: 'https://api.github.com/user/repos',
    beforeSend: function(xhr) {
      xhr.setRequestHeader("Authorization", "token mytoken");
    },
    data: '{"name": "'+name+'",' +
    '"description":"'+description+'",' +
    '"homepage": "'+homepage+'",' +
    '"auto_init":true}'
  }).done(function(e){
    console.log(e);
  });
});
    
14.07.2017 / 21:14