0

I am sending a json in my server using vanilla JS and it returns a bad request, it seems the server only wants a key value pair like 'page=pageData&action=act', when i do this it works, but i would want to send data that way. Is there a way to make it possible? When i try to make it in jquery it works fine.

$('.more-headlines').on('click', function() {
  var pageData = $(this).data('page');
  var pageURL = $(this).data('url');
  var act = 'load_more';
  var jsondata = {
    page : pageData,
    action : act
  }
  var xhr = new XMLHttpRequest();
  xhr.open('POST', pageURL, true);
  xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  xhr.onload = function() {
    if (xhr.status >=200 && xhr.status < 400) {
      var data = JSON.parse(xhr.responseText);
      console.log(data);
    } else {
      console.log('sad');
    }
  };
  xhr.send(JSON.stringify(jsondata));
});

This is my code in jquery

$('.more-headlines').on('click', function () {
    var that = $(this);
        pageData = $(this).data('page');
        newPage = pageData+1;
        pageURL = $(this).data('url');
        act = 'load_more';
        that.addClass('icon-spin');
        that.find('span').html('loading headline');
        jsondata = {
          page : pageData,
          action : act
        }
    $.ajax ({
      type: 'POST',
      url: pageURL,
      data: jsondata,
      success: function(response) {
        setTimeout( function () {

          that.data('page', newPage);
          $('#featureOnDemand ul').append(response);
          that.removeClass('icon-spin');
          that.find('span').html('See more headlines');

        }, 500);
      }
    });
});

I looked at the network tab in chrome and i saw that the send request becomes a key value pair like 'page=pageData&action=act'. I am stuck in this part because i want to make a vanilla js ajax request in my project. Any idea would be much appreaciated. Many thanks!

1
  • Whats say in cosole log?? Commented May 2, 2019 at 18:58

1 Answer 1

1

You want to serialize your object data. Here's a helper function you can pass your object into:

var serializeObject = function (obj) {
    var serialized = [];
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            serialized.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
        }
    }
    return serialized.join('&');
};
Sign up to request clarification or add additional context in comments.

Comments

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.