Simplest way to write this AJAX call - javascript

I need to send an ajax request to a webserver "http://examples.com/ajax" the response will be the html of a <div> and it will be inserted to an existing <div id="holder">. What's the simplest, smallest way to write this in javascript? without using jQuery?
It only needs to support the latest version of chrome.

var req = new XMLHttpRequest();
req.onreadystatechange = function() {
//Is request finished? Does the requested page exist?
if(req.readyState==4 && req.status==200) {
//Your HTML arrives here
alert(req.responseText);
}
}
req.open("GET","http://examples.com/ajax.php",true) //true indicates ASYNCHRONOUS
req.send(null);
This solution uses get, so you've got to add variables using ? and & to your URL (e.g. http://examples.com/ajax.php?foo=bar&blah=blee.
If you want to do it using post, run a few with get and then this article is useful.

Related

Adblocker blocks XMLHttpRequest

I understand the fact, that adblockers try to deny loading (image) data later on. Anyway, I want to send some data to a php script (/log.php) to save it in a sql database. So in fact I don't care about the responsetext. This is my current js function I use to call the php script:
function log(id, unix_ms, frameid, eventtype, targetid, value){
var parameters = "";
parameters = parameters.concat("id=", encodeURI(id), "&unix_ms=", encodeURI(unix_ms), "&frameid=", encodeURI(frameid), "&eventtype=", eventtype, "&targetid=", targetid, "&value=", value);
var httprequest = new XMLHttpRequest();
httprequest.open("POST", "/scripts/log.php", true);
httprequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
httprequest.onreadystatechange = function() {
if(httprequest.readyState == 4 && http.status == 200) {
console.log(httprequest.responseText);
}
}
httprequest.send(parameters);
}
What can I change to pass the adblocker? I mean facebook uses things like ajax in masses to load text and even images in the timeline.
Is there maybe a way to use frames in the background since I don't care about the answer?
After analysing the log as suggested in a comment I found out that log.php seems to be in the blocklist, even if it's on the same server. So name you php files a little more complex to avoid this.
log.php -> submitlog.php

How to update value on input change in JSP? [duplicate]

I have session key that is a JavaScript variable which I got from a REST API call. I need to call my Java code in a servlet and pass that key as a parameter. What JavaScript function can I use to do that?
Several ways:
Use window.location to fire a GET request. Caveat is that it"s synchronous (so the client will see the current page being changed).
window.location = "http://example.com/servlet?key=" + encodeURIComponent(key);
Note the importance of built-in encodeURIComponent() function to encode the request parameters before passing it.
Use form.submit() to fire a GET or POST request. The caveat is also that it"s synchronous.
document.formname.key.value = key;
document.formname.submit();
With
<form name="formname" action="servlet" method="post">
<input type="hidden" name="key">
</form>
Alternatively you can also only set the hidden field of an existing form and just wait until the user submits it.
Use XMLHttpRequest#send() to fire an asynchronous request in the background (also known as Ajax). Below example will invoke servlet"s doGet().
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://example.com/servlet?key=" + encodeURIComponent(key));
xhr.send(null);
Below example will invoke servlet"s doPost().
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://example.com/servlet");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("key=" + encodeURIComponent(key));
Use jQuery to send a crossbrowser compatible Ajax request (above xhr code works in real browsers only, for MSIE compatibility, you"ll need to add some clutter ;) ).
$.get("http://example.com/servlet", { "key": key });
$.post("http://example.com/servlet", { "key": key });
Note that jQuery already transparently encodes the request parameters all by itself, so you don"t need encodeURIComponent() here.
Either way, the key will be just available by request.getParameter("key") in the servlet.
See also:
How to use Servlets and Ajax?
Access Java / Servlet / JSP / JSTL / EL variables in JavaScript
No JavaScript function per se, but browsers usually* provide an XMLHttpRequest object and you can go through that.
Libraries such as YUI and jQuery provide helper functions to simplify its usage.
* for a value of "usually" that includes pretty much any browser that supports JavaScript and was released since Netscape 4 died
When sending POST add header
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
The code looks like
Client:
function executeRequest(req) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
document.getElementById("response").value = xhttp.responseText;
}
};
xhttp.open("POST", "execute/cardbrowser", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("lorem=ipsum&name=binny");
}
Server:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(req.getParameter("lorem"));
}

Understanding of ajax complete call

I'm struggling with stabilizing Selenium automation for jQuery/AJAX application hence referred to
https://www.swtestacademy.com/selenium-wait-javascript-angular-ajax/
and it has ajaxComplete() method which has following code -
var callback = arguments[arguments.length - 1];
var xhr = new XMLHttpRequest();
xhr.open('GET', '/Ajax_call', true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
callback(xhr.responseText);
}
};
xhr.send();
);
I haven't work on JavaScript before and this code which I'm not able to understand completely. I've following questions with this, if someone can help to understand it -
What is Ajax_call in this? Is it generic call to check ajax completion? Or do I need to have my own endpoint there? If yes, does single end point enough or do I need to identify all calls and add them in the method?
Please check the documentation for XMLHttpRequest.open. If you do, you will the second argument listed is
url
A DOMString representing the URL to send the request to.
This means that it is simply the URL you want to request. I can be anything you want. The / prefix means that you are request relative to the root of the website (so if you are requesting from https://example.com/somedir/somepage the request will be made to https://example.com/Ajax_call.

JavaScript: How to access to a given URL without opening its web page in a browser

I would like to know if it is possible in JavaScript to access to a given URL without opening its web page in a browser . Actually, what I'm really trying to do is parsing through a page (given its URL) and clicking on the first link that it contains without even opening that web page in my browser. Is that doable with JavaScript. In case it is, how should I do that? What function (or functions) should I use? In case it is not, what would the alternative solutions be?
What you need is to make an HTTP request to the URL and process the results. You can do that in JavaScript using the XMLHttpRequest object. Example:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xhttp.open("GET", "put_the_URL_here", true);
xhttp.send();
However, it is easier to use a library like jQuery.Ajax for that:
$.ajax({
url: "put_the_URL_here",
context: document.body
}).success(function(data) {
console.log(data);
});
For this to work, the URL that you're trying to access must have CORS enabled.

Using JavaScript Ajax to retrieve content from another site

I'm currently experimenting with replacing a number of function I currently use jQuery for with a Vanilla Javascript alternative. This is to:
Increase my understanding of JavaScript as a whole
Make me a better front-end developer (ties into the above)
Improve the speed and responsiveness of my web applications by negating the need for a library such as jQuery for simple tasks.
My aim today is to produce a JavaScript function that allows me to make an Ajax call to another site to retrieve a specific Div and use the content from that Div within my page. I can do this pretty easily with jQuery by filtering the response from an Ajax call with the .find() method to retrieve the specific Div I require then use the .html() function to strip the content and append it to the Div on my site. However, I cannot see an alternative method of doing this using Vanilla JavaScript.
My code so far can be found below:
function fireAjaxRequest(requestType,requestUrl,contentPlaceholder){
var ajaxRequest;
if(window.XMLHttpRequest){
ajaxRequest = new XMLHttpRequest();
}else{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
contentPlaceholder.innerHTML = ajaxRequest.responseText;
}
}
ajaxRequest.open(requestType,requestUrl, true);
ajaxRequest.send();
}
I call my function as follows:
var contentArea = document.getElementById('news');
fireAjaxRequest('GET', 'http://www.bbc.co.uk',contentArea);
When I load my page, I can see in Firebug that the request completes successfully and I get
a 200 Success response from the Ajax call however, nothing is displayed in my target element. At first I thought this was because you cannot store a whole page within a single element but after altering my code slightly I found the the following snippet of code does not seem to be executed upon the success of the Ajax call:
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
contentPlaceholder.innerHTML = ajaxRequest.responseText;
}
}
Am I doing something incorrectly here?
You really need to look into XSS. I think you'll understand why there are serious restrictions with what you're trying to do.
If you control both domains, you can use JSONP or CORS.
You could also write send an ajax request to your own server that acts as a proxy. Your server would "forward" the request to the destination server, and relay the response to the client.

Categories

Resources