A
A
Alex-19172019-09-09 19:03:39
JavaScript
Alex-1917, 2019-09-09 19:03:39

What is the correct way to upload data from the API via XMLHttpRequest?

Is it correct to call the showProduct() function inside the ajax request and add an element to the DOM inside this function?
Or should it be split into two or three functions? Then you can not do without Promise?

var app = document.getElementById('app');
function getProduct(id) {
  var formData = new FormData();
  formData.append('product_id', id);
  var request = new XMLHttpRequest();
  request.responseType =	"json";
  request.open('POST', '/api.php', true);
  request.addEventListener('readystatechange', function() {
    if (this.readyState == 4 && this.status == 200) {
      var item = this.response;
      showProduct(item);
    }
  });
  request.send(formData);
}
function showProduct(item) {
  var product = document.createElement('a');
  product .href = 'product/' + item.href;
  product .textContent = item.name;
  product .addEventListener('click', product_rout);//функция роутинга, не
  app.appendChild(product );
}
function product_rout {
...
}
//и сам вызов функции, вызывается по клику на карточку товара в списке товаров
getProduct(id);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Melodin, 2019-09-12
@melodyn

1. XMLHttpRequest, like var, is a little bit outdated. If you really do, do it so that it's good - on fetch and ES6 syntax.
2. showProduct should apparently display the product on the screen, but it creates new elements in the dom, changes links, hooks handlers, and adds the product to the app from the global scope.
3. snake_case after camelCase?
4. Writing synchronous code on the front is a great mortal sin. Watch this video to understand the problem: https://www.youtube.com/watch?v=8cV4ZvHXQL4
5. If you are the author of this code, get rid of your tutorials :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question