Having this API:
http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1
How can I write using pure JS request that downloads me different data after button click event?
All I get from this code is the same quote all the time:
function getQuote (cb) {
var xmlhttp = new XMLHttpRequest();
var quoteURL = "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand"
xmlhttp.onreadystatechange = function() {
if (xmlhttp.status == 200 && this.readyState==4) {
cb(this.responseText);
}
};
xmlhttp.open("GET", quoteURL, true);
xmlhttp.send();
}
document.querySelector('button').addEventListener("click", function() {
getQuote(function(quote) {
console.log(quote);
});
})
I tried xmlhttp.abort() and stuff but it didnt want to cooperate.
Thanks in advance!
Your response is being cached by the browser. A common trick to avoid this is to perform a request to
http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&r={random_number}
Notice how the r={random_number} will make the URL different each time.
This is a caching problem. Add a timestamp as a query parameter and you should be able to bust the cache.
Related
I have a JavaScript function that is attempting to closely emulate a form submit.
function fopen() {
var xhr = new XMLHttpRequest();
xhr.open("POST", open_url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
create: 0,
jobtype: jobtype,
name: document.getElementById("file-selector").value
}));
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
document.write(xhr.responseText);
}
else {
console.log('ErR0r')
}
}
}
The behavior is close to identical, but the URL is not being updated after the response. I see there is an xhr.responseURL attribute but how can I actually get this to show in the address bar? And is there an exact full JavaScript implementation of form submit I can refer to in order to keep things as similar as possible?
To change the page's URL, set window.location.href.
I ctrl+c the part of Max Payne Wiki article(it's just an exmaple of any text):
just a screenshot of how I copy part of the article
Then I ctrl+v this stuff into <textarea> in my site(not in the code, but literally in the site-rendered <textarea>)
The the runs the next javascript code:
SomeParagraphElement.innerText=document.getElementById('my_txtarea').value;
requestp("aga.php?data="+SomeParagraphElement.innerText, callback_function);
where requestp is
function requestp(path, run)
{
var request = new XMLHttpRequest();
request.open('GET', path, true);
request.addEventListener('readystatechange' ,function()
{
if ((request.readyState==4) && (request.status==200))
run( request.responseText);
}
);
request.send(null);
}
After this there should be a data uploaded to sever, but it doesn't happen and if I just write stuff from keyboard by my fingers and even insert emojis - all works fine.
Google Chrome debug window says, that I make a 400 HTTP error. I tried
var str= SomeParagraphElement.innerHTML.replace(/(?:\r\n|\r|\n)/g, '%0A'); and another %blahblah symbol, but it doesn't change anything.
If I make a new line by myself by pressing 'enter', via keyboard it works fine.
What should I do?
Yeah, if I pass data more the 2048 bytes, I have to use POST request. Here is a function, maybe it will be helpfull for someone
function requestp(path, data, callback)
{
var request = new XMLHttpRequest();
request.open('POST', path, true);
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');//specify this!
request.addEventListener('readystatechange' ,function()
{
if ((request.readyState==4) && (request.status==200))
callback( request.responseText);
}
);
request.send(data);
}
I'm trying to have a div refresh after a callback using ajax functions. Basically, I want /includes/view_game/achievements.inc.php to be reloaded in the div #achievements_tab. The callback (I didn't include it in codes below) works well and triggers the AchievementRefresh function found below (the opacity of the div changes to 0.5, but it remains like this and the refresh is not made).
Those two functions are used for another similar ajax refresh on my site that works well. So I tried to modify the code, but since it's for a slightly different purpose, maybe I have the wrong approach.
function AjaxPost(url, success_function) {
xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert("Your browser doesn't support AJAX. You should upgrade it!")
return
}
xmlHttp.onreadystatechange = success_function;
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
This AjaxPost function is used in the other function below:
function AchievementRefresh() {
div('achievements_tab').style.opacity = 0.5;
div('highscore_pages').innerHTML = '<img src="'+site_url+'/images/loader.gif" />';
AjaxPost(site_url+"/includes/view_game/achievements.inc.php?", '',
function () {
div('achievements_tab').innerHTML = xmlHttp.responseText;
div('achievements_tab').style.opacity = 1;
}
)
}
Use load
$('#achievements_tab').load('/includes/view_game/achievements.inc.php');
See: http://api.jquery.com/load/
Edit
E.g.
function AchievementRefresh() {
$('#achievements_tab').css('opacity', 0.5);
$('#highscore_pages').html('<img src="'+site_url+'/images/loader.gif" />');
$('#achievements_tab').load('/includes/view_game/achievements.inc.php')
.success(function() {
$('#achievements_tab').css('opacity', 1);
});
}
Try this.
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
div('achievements_tab').innerHTML = xmlHttp.responseText;
div('achievements_tab').style.opacity = 1;
}
}
};`
Name and id is example.
Also, some changes:
AjaxPost(site_url+"/includes/view_game/achievements.inc.php");
var params= 'name'+encodeURIComponent(name)+'&id='+encodeURIComponent(id)
Parameters shouldn't be in URL.
xmlhttp.send(params);
I need a script that triggers a URL(go to the URL and that's it).
What's the shortest way to write this script?
Use window.location.
window.location = 'http://stackoverflow.com';
Or shorter (not recommend though).
location = 'http://stackoverflow.com';
No ajaxical magic needed.
window.location='http://www.google.com';
Of course you could code-golf out the url and the semicolon.
Thanks:
Use window.location.
window.location = 'http://stackoverflow.com';
This is a sample AJAX code sample that can be used to fire a silent query to the browser and fetch the response and act on it.
var xmlhttp;
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// Do something with the result, like post a notification
$('#notice').html('<p class="success">'+xmlhttp.responseText+'</p>');
}
}
xmlhttp.open('GET',url, true);
xmlhttp.send();
I've some problem with requesting an URL when finishing (exit) the widget. I try to use it via window.widget.onexit on request then an logout URL which makes some logs in the backend. I tried it by the following ways:
window.widget.onexit = function() {
xhr = new XMLHttpRequest;
xhr.open("GET", "http://new-ken.de/alwaysOn/php/logout.php", false );
xhr.send("");
}
AND
window.widget.onexit = function() {
window.location.href = "http://new-ken.de/alwaysOn/php/logout.php";
}
Does somebody have an idea to solve this little problem?
Thanks!
Try to use this code:
widget.openURL("http://new-ken.de/alwaysOn/php/logout.php");