I am new to JavaScript and I want to use send_request
function twice, but with different behaviour. Element with name button1
should show response on the element, whereas button2
not.
function send_request(url) {
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.send('data=test');
xhr.onload = function () {document.getElementById('reply').innerHTML = xhr.responseText;};
}
document.getElementById('button1').addEventListener('click', function() { send_request("/data.php"); });
document.getElementById('button2').addEventListener('click', function() { send_request("/clear_data.php"); });
Is it possible?
You could give send_request
another parameter, a function that's called with the responseText
, so you could pass one function that assigns to reply
, and another function that does whatever you want instead:
function send_request(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.send('data=test');
xhr.onload = () => callback(xhr.responseText);
}
document.getElementById('button1').addEventListener('click', function() {
send_request("/data.php", (responseText) => {
document.getElementById('reply').innerHTML = responseText;
});
});
document.getElementById('bitton2').addEventListener('click', function() {
send_request("/clear_data.php", (responseText) => {
console.log('bitton 2 response: ' + responseText);
});
});
There are a number of ways to accomplish this, but if we just start with your basic requirement, you could have send_request
simply take an argument that determines if the element should show the response.
function send_request(url, showResponse) {
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.send('data=test');
xhr.onload = function () {
// If showResponse is true, log the response. If not, don't
showResponse ? document.getElementById('reply').innerHTML = xhr.responseText : null;
};
}
document.getElementById('button1').addEventListener('click', function() {
// Call the function and indicate that the response should be shown
send_request("/data.php", true);
});
document.getElementById('bitton2').addEventListener('click', function() {
// Call the function and indicate that the response should not be shown
send_request("/clear_data.php", false);
});