Due to some reason, I don't want to use jQuery in this JavaScript code:
$(function() {
var url = ; //webhook URL here
var content = "Hiii";
var username = "Hi";
$.post(url, {"content": content, "username": username});
});
Is there any way to convert this into a code that doesn't require jQuery?
First off, you can replace the $() with something like
document.addEventListener('DOMContentLoaded', (e) => {})
Secondly if you're only targeting newer browsers you can make use of fetch.
document.addEventListener('DOMContentLoaded', (e) => {
var url = ; //webhook URL here
var content = "Hiii";
var username = "Hi";
fetch(url, {
method: 'POST',
body: JSON.stringify({
content: content,
username: username,
})
});
});
or fallback to using plain XHR
var oReq = new XMLHttpRequest();
oReq.open("POST", url, true);
oReq.send({
content: content,
username: username,
});
var content = "Hiii";
var username = "Hi";
var http = new XMLHttpRequest();
var url = "your API url";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send({"content": content, "username": username});
You can use XMLHttpRequest to make AJAX call like above.
Related
I am trying to develop a component in Joomla 4. I have a simple button that should fire of a script to update the database.
I can make the call to the JavaScript ok, but the JavaScript does not appear to open the request URL, if anything it opens the current URL or refreshes the page. The script works fine outside of Joomla but not inside.
I have tried both the following, and the same thing happens:
*function buttonLike()
{
var xhr = new XMLHttpRequest();
var parentEl = this.parentElement;
//var url = 'index.php?com_reflect&format=raw;
var url = 'liked.php';
console.log('Get Here OK' + parentEl.id);
xhr.open('GET', 'liked.php', true);
// Form data is sent appropriately as a POST request
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onreadystatechange = function ()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
var result = xhr.responseText;
console.log('Never Here Result: ' + result);
}
if(xhr.readyState == 4 && xhr.status == 0)
{
console.log('Always Here');
}
};
xhr.send("id=" + parentEl.id);
}*
OR
function buttonLike()
{
//var url = 'index.php?com_reflect&format=raw;
var url = 'liked.php';
var request = new Ajax(url, {
method: 'post',
update: some_div,
data: options,
onComplete: function (){
$('some_field').setHTML('I am finished!');
}
}).request();
Been going round in circles on this one, any help would be appreciated.
Hello i now using this php code for get steam nicknames
function EchoPlayerName($steamid){
$xml = simplexml_load_file("http://steamcommunity.com/profiles/$steamid/?xml=1");//link to user xml
if(!empty($xml)) {
$username = $xml->steamID;
echo $username;
}
}
or
$steam = file_get_contents("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={API_KEY}&steamids=$steamid64", true);
$steamarray = json_decode($steam, true);
$name = $steamarray['response']['players'][0]['personaname'];
but i this using for listing players and loading page is slow
so i want this data load via javascript after full load page
any ideas?
API example
{"response":{"players":[{"steamid":"76561197964477177","communityvisibilitystate":3,"profilestate":1,"personaname":"The [G]amerX #ππ¨π‘π£πππ¬.π½πΏπΌ","lastlogoff":1558765863,"commentpermission":1,"profileurl":"https://steamcommunity.com/id/gamerxcz/","avatar":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/66/6673d6df066386d232164e8f9a5d9b36cad1d013.jpg","avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/66/6673d6df066386d232164e8f9a5d9b36cad1d013_medium.jpg","avatarfull":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/66/6673d6df066386d232164e8f9a5d9b36cad1d013_full.jpg","personastate":0,"realname":"Community Owner","primaryclanid":"103582791433644720","timecreated":1076786008,"personastateflags":0,"loccountrycode":"CZ"}]}}
First, you should get Data using ajax of pure javascript or jquery. Then you should target an HTML element that you want to fill it using this retrieved data. Imagine element with ID target.
jQuery:
$(document).ready(function () {
$.ajax({
url: "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={API_KEY}&steamids=$steamid64",
}).done(function (data) {
var json = JSON.parse(data);
$('#target').text(json['response']['players'][0]['personaname']);
});
});
pure javascript:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={API_KEY}&steamids=$steamid64');
xhr.onload = function () {
if (xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
document.getElementById('target').innerHTML = json['response']['players'][0]['personaname'];
} else {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
Remember to place these scripts at the end of your document.
I want to run a this code only if a visitor is from a specific country
window.onload=function(){
document.getElementById("buy").click();
};
I tried this but didn't work :
var requestUrl = "http://ip-api.com/json";
var xhr = new XMLHttpRequest();
xhr.open('POST', requestUrl, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onload = function () {
var json = JSON.parse(xhr.responseText)
if(json.country == 'France'){
document.getElementById("buy").click();
};
};
xhr.send(null);
Here's an easy way to do it with that same API:
fetch('http://ip-api.com/json').then(response => {
return response.json();
}).then(data => {
if (data.country == "France") {
document.getElementById("buy").click();
}
});
Or if you prefer jQuery:
$.getJSON("http://ip-api.com/json", function(data) {
if (data.country == "France") {
$("#buy").click();
})
});
I am trying to modify the "likes" of a xml file. How do I do that?
What I'm trying now:
var likes = +1;
formData.append("likes", likes);
var xhr = new XMLHttpRequest();
xhr.addEventListener("loadstart", showLoading, false);
var url = "linkishere";
xhr.open('POST', url, true);
xhr.onload = function (e) {
var response = $.parseJSON(e.target.response);
if (response.success == true) {
console.log('success: '+response.success);
hideLoading();
showThankyou();
console.log('Het stemmen is gelukt');
}else {
alert(response.error.message);
console.log(response.error.message);
console.log(agreeTermsAndConditions);
console.log('Er ging iets fout.');
}
};
xhr.send(formData); // multipart/form-data
}
Hope someone can help me with this. Do I use append for this? Sorry I'm new to this.
I would like to convert this ajax function to a jquery function but im not sure how it would be done in jquery
function ajax_posta() {
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "javas.php";
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function () {
if (hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById('status').innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send("num=" + (--num)); // Actually execute the request
document.getElementById('status').innerHTML = "<img src = 'loading.gif' height = '30' width = '30'>";
}
$(document).ready(function()
{
$('.eventer.button').click(function () {
var self = this;
$.post('javas.php', function (data) {
$(self).parent('div').find('.status').html(data);
})
});
}
)
;
</script>
You're pretty much there
$.ajax('javas.php', {
success: function(response) {
$(".status").html(response);
},
data: "num=" + (--num)
});
If these are the only two pieces of data you need to send to your request, you could just use $.post, but the advantage here is that if you ever want to specify more options, like contentType, all you'd have to do is add it to the existing options object.