Problem with POST in Javascript + Ajax

Asked

Viewed 87 times

1

Guys I’m doing a test, and I need to develop a sign-up screen using the Github API https://developer.github.com/v3/repos/#create ... Follows 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);
  });
});

As follows it works.. however I want to receive the POST data and pass 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 so 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);
  });
});

Thus returns the same error, only the first example registers the repository, however I need to receive the data passed in the THANK form!

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.