Can anyone please point me in the right direction? I am new to AJAX.
I want to add the ID of a post to this simple request.
Anyone? Thanks Martin
<!DOCTYPE html>
<html>
<body>
<h1>Postback to webhook incl PostID</h1>
<button type="button" onclick="loadDocs()">Postback</button>
<p id="testID"></p>
<script>
function loadDocs() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("testID").innerHTML = this.responseText;
}
};
xhttp.open("POST", "https://hook.integromat.com/h17qasnzptr4lo7cs6br1vmrv28t11ji", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("url=POSTIDHERE");
}
</script>
</body>
</html>
Here's a working example based on what was mentioned in the comments:
function loadDocs() {
var element = document.querySelectorAll("[data-elementor-id]")[0];
var testId = element.dataset.elementorId;
var URL =
"https://hook.integromat.com/h17qasnzptr4lo7cs6br1vmrv28t11ji";
var http = new XMLHttpRequest();
var params = "url=" + testId;
http.open("POST", URL, true);
http.setRequestHeader(
"Content-Type",
"application/x-www-form-urlencoded"
);
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) {
console.log("success!");
}
};
http.send(params);
}
<h2>Postback to webhook incl PostID</h2>
<button type="button" onclick="loadDocs()">Postback</button>
<!-- This can be any element, but let's assume it's a DIV-->
<div data-elementor-id="228">
<h2>228</h2>
</div>
As you can see, I have an element (div
in this case) that has the data-elementor-id
attribute which holds the testId
you want to POST
to your Webhook.
I grab this element with document.querySelectorAll("[data-elementor-id]")[0]
and extract the ID
by using element.dataset.elementorId
, which I then use for the POST
request by using string concatenation - "url=" + testId
.
Note that document.querySelectorAll
returns an array - in my case there's only one element on the page with the data-elementor-id
attribute, so I picked the first one, hence [0]
. If you had more elements on your page with the same attribute and the first element wasn't the one with appropriate ID, make sure you specify the right index, i.e. [2]
.
Hope this helps.
</div>