[[oktatas:web:javascript:javascript_ajax|< AJAX]] ====== AJAX POST kérés ====== * **Szerző:** Sallai András * Copyright (c) 2015, Sallai András * Szerkesztve: 2015, 2021, 2024 * Licenc: [[https://creativecommons.org/licenses/by-sa/4.0/|CC BY-SA 4.0]] * Web: https://szit.hu ===== Adatok szervernek POST metódussal ===== function uploadData(data) { var xhr = new XMLHttpRequest(); xhr.responseType = 'text'; xhr.open("POST", "php/index.php", true); xhr.send(JSON.stringify(data)); } let data = { nev: 'Nagy János', telepules: 'Szolnok', fizetes: 8480000 }; uploadData(data); Ha szeretnénk választ is: function uploadData(data) { var xhr = new XMLHttpRequest(); xhr.responseType = 'text'; xhr.open("POST", "php/index.php", true); xhr.send(JSON.stringify(data)); xhr.onload = function() { if(xhr.readyState === xhr.DONE) { if(xhr.status === 200) { console.log(xhr.responseText); } } } } let data = { nev: 'Nagy János', telepules: 'Szolnok', fizetes: 8480000 }; uploadData(data); Az adatok fogadása PHP-val: nev; error_log(json_encode($data)); error_log($data->nev); ===== URL kódolással ===== httpRequest.open("POST","feldolgoz.php",true); httpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded"); httpRequest.send("vnev=Nagy&knev=Joska"); ===== Dolgozó hozzáadása ===== const addButton = document.querySelector('#addButton'); addButton.addEventListener('click', () => { var emp = { name: 'Csend Iván', city: 'Hatvan', salary: 392 } addProduct(emp); }); function addProduct(emp) { let url = 'http://localhost:8000/employees'; let http = new XMLHttpRequest(); http.open('post', url, true); http.setRequestHeader('Content-type', 'application/json'); http.onload = function() { if(http.readyState === http.DONE) { if(http.status === 200) { console.log(http.responseText) } } } let empStr = JSON.stringify(emp) http.send(empStr); }