Good day! I am trying to master ajax without any jquery, i.e. pure ajax operation with an XMLHttpRequest object, etc. I'm trying to send data like this.

//Кроссбраузерное создание Ajax объекта function getXmlHttp(){ var xmlhttp; try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { xmlhttp = false; } } if (!xmlhttp && typeof XMLHttpRequest!='undefined') { xmlhttp = new XMLHttpRequest(); } return xmlhttp; } //Добавляем товар в корзину function productAddToBasket(Action,ProductID,Quantity,AjaxBasket) { var CurrPagePath = window.location.pathname; //Текущая страница var AjaxObject = getXmlHttp(); //Получаем объект XMLHttpRequest //Настройка обработчика AjaxObject.onreadystatechange = function() { alert("Товар добавлен в корзину!"); } //Открываем соединение AjaxObject.open('POST', CurrPagePath, true); //Отправляем данные var Data = "action="+Action+"&id="+ProductID+"&quantity="+Quantity+"&ajax_basket="+AjaxBasket+""; AjaxObject.send(Data); } 

The function call productAddToBasket is implemented like this (this is in the template body):

  <span onClick="productAddToBasket('ADD2BASKET',<?=$Item['ID']; ?>,1,'Y')" > Купить </span> 

The data that go away but like this http://joxi.ru/SsrTU4wyTJCsLtlN7d8 as one line, but I wanted to be like this http://joxi.ru/ccrTU_3JTJAtGic2x9c Parameter-> Value . So I don’t understand how I can form the Data variable that I send here AjaxObject.send (Data); to get the data right? And one more moment, the productAddToBasket () function does not stop after a call via onClick, but it would be necessary for it to work out correctly, 1 click - 1 call.

Thank you in advance!

  • one
    and you do not confuse POST c GET th? - nörbörnën
  • one
    What is the reason for not using jQuery? There is clearly not self-development, but a specific task. Wouldn’t it be better to make tools that are easy to maintain, and not to do cycling? - dlarchikov
  • @ dimka3210, judging by the code, a person still needs to smoke a lot before “having full right” to use something like jQuery, although yes, I agree, if this is a “working task” it is unreasonably silly to solve it. As for the code itself - at least there is no header (at least xhr.setRequestHeader ("Content-type", "application / x-www-form-urlencoded");) - Zowie
  • one
    @AlexWindHope so what's the point, here you are on the calculator bc programmed? in the sense of inventing programs and codes them? How do you like the statement that it’s still too early to use the full-text screen to everyone who has not passed a couple of years on a calculator? If it is normal to approach the question, then jquery and other libraries are just getting used to the right solutions. A couple of years of such bydlokoding on "pure" js and we get another monster with completely unimaginable patterns in the head. A couple of years with the framework gives an understanding not only of how to use it, but also how it works. - zb '
  • @eicto - I have no desire to argue with you on this issue. And, if that - I do not think that such things as ajax should be felt with my own hands, nevertheless, I am convinced that it would be, at least - useful. But, in the general case, it is enough just to carefully read and understand once to what it is, nothing more. But about the "gives understanding" - also, let's say, at least not always true (I'm talking about "jQuery programmers"). Although yes, partly you are right, but it was not a little bit about that - Zowie

2 answers 2

and you do the analysis of the parameters

 $params = array(); parse_str($_POST, $params); 

    With jQuery and other libraries, we completely forgot what clean code looks like. Why load extra kilometers of useless library code when you can do a dozen lines of simple code.

    Here is the code: (do not kick the pain, wrote literally in a few minutes)

    this is a typical function

      /* Данная функция создаёт кроссбраузерный объект XMLHTTP */ function getXmlHttp(){ var xmlhttp; try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { xmlhttp = false; } } if (!xmlhttp && typeof XMLHttpRequest!='undefined') { xmlhttp = new XMLHttpRequest(); } return xmlhttp; } 

    And this is the function itself that sends POST to the server.

     function sendingForm (formname) { var xmlhttp = getXmlHttp(); // Создаём объект XMLHTTP var p = 'ajax=1'; for(var i=0;i<document.forms[formname].elements.length;i++){ p += "&"+document.forms[formname].elements[i].name+"="+encodeURIComponent(document.forms[formname].elements[i].value) ;//присваиваем значение } alert( p ) ; // проверяем что отправляем xmlhttp.open('POST', 'ajax/', true); // Открываем асинхронное соединение xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // Отправляем кодировку xmlhttp.send(p); // Отправляем POST-запрос xmlhttp.onreadystatechange = function() { // Ждём ответа от сервера if (xmlhttp.readyState == 4) { // Ответ пришёл if(xmlhttp.status == 200) { // Сервер вернул код 200 alert( 'Ответ получен, Значит данные отправлены успешно !' ) ; // проверяем что отправляем /* Место для кода обработчика событий */ } } } ; } 

    This form is what we send:

     <form name="panelcontent" method="POST" id="panelcontent"> <input type="text" id="id1" name="name1" /> <input type="text" id="id1" name="name2" /> <div class="fieldInput"> <button type="button" class="blue-pill" id="panelContentButton" onClick="sendingForm ('panelcontent')">Сохранить</button> </div> </form> 

    Somehow, it is advisable to save the js file in UTF-8 encoding.

    • What kind of clean code are we talking about? What is your document.getElementByClassName() ? More precisely, how many characters is the js specification? And the w3c specification actually describes the interfaces to the browser, not necessarily javascript. - zb '
    • Well, the DOM method is not an external library, after all, and I actually answered essentially the question asked. - Vas
    • DOM is an external library regarding js, for example, if jQuery is implemented natively, do you immediately change your mind? (minus removed, because here at least there is an answer now) - zb '
    • Yeah thanks! I will try. - maler1988