Display response(xml) by making a HTTP GET request using javascript? - javascript

I have very new to JS and I have done my research but I guess I'm kind of using the wrong technique or something.
Like in python to make GET request we do:
request_text = requests.get(url).text
I want to do the same thing but using JS i.e. display the content from "http://synd.cricbuzz.com/j2me/1.0/livematches.xml" in the raw(xml) format and I have found this script somewhere but it doesn't work.
<h2>AJAX</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "http://synd.cricbuzz.com/j2me/1.0/livematches.xml", false);
xhttp.send();
}
</script>
</body>
</html>
I just need the direction on how to do the same i.e. how to send a GET/POST request using JS and render it on a webpage?

When I use
function test(url) {
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
var section = document.createElement('section');
var h2 = document.createElement('h2');
h2.textContent = 'Received from ' + url;
section.appendChild(h2);
var pre = document.createElement('pre');
pre.textContent = req.responseText;
section.appendChild(pre);
document.body.appendChild(section);
};
req.onerror = function(evt) {
document.body.insertAdjacentHTML('beforeEnd', '<p>Error requesting ' + url + '.<\/p>');
};
req.send();
}
document.addEventListener('DOMContentLoaded', function() {
test('http://home.arcor.de/martin.honnen/cdtest/test2011060701.xml');
test('http://synd.cricbuzz.com/j2me/1.0/livematches.xml');
},
false);
the first URL works as the server is set up to allow the CORS request for that directory while the second fails as the server does not allow it. So unless you serve your HTML with the script from synd.cricbuzz.com or unless you can change the configuration of synd.cricbuzz.com to allow a CORS request you won't be able to request the XML from that server.
Note also that in modern browsers (current versions of Mozilla, Chrome, Edge) you can use the Promise based fetch method instead of XMLHttpRequest, as shown below. But the same origin policy is not different for fetch, so the same as stated above holds.
function test(url) {
fetch(url).then(function(response) {
if(response.ok) {
response.text().then(function(text) {
var section = document.createElement('section');
var h2 = document.createElement('h2');
h2.textContent = 'Received from ' + url;
section.appendChild(h2);
var pre = document.createElement('pre');
pre.textContent = text;
section.appendChild(pre);
document.body.appendChild(section);
});
}
else {
document.body.insertAdjacentHTML('beforeEnd', '<p>Error requesting ' + url + '; status: ' + response.status + '.<\/p>');
}
})
.catch(function(error) {
document.body.insertAdjacentHTML('beforeEnd', '<p>Error "' + error.message + '" requesting ' + url + '.<\/p>');
});
}
document.addEventListener('DOMContentLoaded', function() {
test('http://home.arcor.de/martin.honnen/cdtest/test2011060701.xml');
test('http://synd.cricbuzz.com/j2me/1.0/livematches.xml');
},
false);

Related

How to obtain the body response in the client-side?

I am new in web, I am serving an html when a button is clicked on the client side through a request, the body response of that request is the html. How can I retrieve the html or body response from the client side?
I am trying with this code but everything is empty:
var xhr = new XMLHttpRequest();
xhr.open(signedRequest.method, signedRequest.url, true);
console.log('xhr.response: ', xhr.response);
console.log('xhr.responseText: ', xhr.responseText);
console.log('xhr.responseXML: ', xhr.responseXML);
document.write('<p>xhr: ' + xhr + '</p>');
xhr.send();
Any idea on how to obtain the body response in the client-side?
Try to add a div or any input element with the id "demo" and try to run the code below.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = "<strong>The response from the test URL is: </strong>" + this.responseText;
console.log(JSON.parse(this.response));
}
};
xhttp.open("GET", "https://httpbin.org/get", true);
xhttp.send();
<div id="demo"></div>

How to parse json using ajax script in ESP32 app

I am working on a project using ESP32, I get some data from some sensors and send it to a webpage hosted in the same board.
I read some info on the web and understood that is "better" to send all data from several sensors using json method, so my function to get and send data is this:
void handle_leituras()
{
String results_json = "{ \"data\": " + Data +
"," + "\"hora\": " + Hora +
"," + "\"temp_amb1\": " + Tout + " }";
server.send(200, "application/json", results_json);
}
Testing above function in serial monitor I have this data:
{"data": Domingo, 12/4/2020,"hora": 20:53,"temp_amb1": 25.75}
I found a script that can get only one data and print it on that page, this is the script:
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("DATA").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "leituras", true);
xhttp.send();
}
Its my index page code that shows data on webpage:
const char pag_inicial[] PROGMEM = R"=====(
<!DOCTYPE html>
<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\">
<title>My 1st test</title></head>
<html>
<body>
<div id="pagina">
<h1>System XPTO</h1>
<div>
Data: <span id="DATA">ND</span><br>
Hora: <span id="HORA">ND</span><br>
Temperatura Ambiente: <span id="TEMPAMB1">ND</span>
</div>
<div id="botoes">
<button type="button" onclick="sendData(0)" style="width: 80px; height: 30px; margin: 30px;">ON</button>
<button type="button" onclick="sendData(1)" style="width: 80px; height: 30px; margin: 30px;">OFF</button><BR>
</div>
<script>
setInterval(function() {
// Call a function repetatively with 1 Second interval
getData();
}, 1000); //2000mSeconds update rate
//function to set on / off a LED on my board
function sendData(led) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("LEDState").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "setLED?LEDstate="+led, true);
xhttp.send();
}
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "leituras", true);
xhttp.send();
xhttp.onload = function() {
if (this.status == 200) {
var jsonResponse = JSON.parse(this.responseText);
document.getElementById("DATA").innerHTML = jsonResponse.data;
document.getElementById("HORA").innerHTML = jsonResponse.hora;
document.getElementById("TEMPAMB1").innerHTML = jsonResponse.temp_amb1;
}
else {
console.log(this.status);
}
};
}
</script>
</div>
</body>
</html>
)=====";
My problem is...I don't know how to modify this script to get more sensors values from the described above function.
Anybody can save me please?
Thanks in advance ;)
The standard XMLHttpRequest only supports responseText and responseXML, it does not support responseJSON property. However, as long as your server is sending a valid serialised JSON string, the responseText should contain the JSON code as text, so all you've got to do is to parse it with JSON.parse(), and then you can access each JSON element with dot notation:
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "leituras", true);
xhttp.send();
xhttp.onload = function() {
if (this.status == 200) {
var jsonResponse = JSON.parse(this.responseText);
document.getElementById("DATA").innerHTML = jsonResponse.data;
document.getElementById("HORA").innerHTML = jsonResponse.hora;
document.getElementById("TEMPAMB1").innerHTML = jsonResponse.temp_amb1;
}
else {
console.log(this.status);
}
};
}
This piece of code works for all browsers that supports XMLHttpRequest and JSON as long as the server is sending a valid JSON object.

How i call controller function from below javascript code in view page(Codeigniter)

This is the javascript code that which used in core PHP for saving data entered in google map.
I want to pass the values in the variable 'url' to controller function in Codeigniter. what should i do?
function saveData() {
var name = escape(document.getElementById('name').value);
var address = escape(document.getElementById('address').value);
var type = document.getElementById('type').value;
var latlng = marker.getPosition();
var url = 'phpsqlinfo_addrow.php?name=' + name + '&address=' + address +
'&type=' + type + '&lat=' + latlng.lat() + '&lng=' + latlng.lng();
downloadUrl(url, function(data, responseCode) {
if (responseCode == 200 && data.length <= 1) {
infowindow.close();
messagewindow.open(map, marker);
}
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing () {
}
To fetch the parameters from a GET request use the CI library input. Documentation HERE.
Here's a simplified version for demonstration purposes starting with the view file viewMap.php
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button value="test" id='mapsave'>Click Me</button>
<div id="response"></div>
<script>
var el = document.getElementById("mapsave");
el.addEventListener("click", saveData, false);
function saveData() {
var res = document.getElementById("response");
var request = new XMLHttpRequest();
var name, url;
name = "Stevin";
url = "<?= base_url('maps/insert_church_details?name='); ?>" + name;
request.onreadystatechange = function () {
if (request.readyState == 4) {
res.innerHTML = request.responseText;
}
};
request.open('GET', url, true);
request.send();
}
</script>
</body>
</html>
Here is the controller. I've renamed it simply Maps instead of mapController because it simplifies URLs. Who want's to go http://example.com/mapController ? Also, mapController violates CodeIgniter class naming conventions. (Better explained HERE)
class Maps extends CI_Controller
{
public function index()
{
$this->load->view('viewMap');
}
public function insert_church_details()
{
echo $this->input->get('name');
//exit; <- Bad idea for CodeIgniter
}
}
In this example we only have the one item in the query string and we use input->get('name') to fetch it. The parameter passed to get() is the name of item. If we have several items we can fetch them one at a time or use get() without a parameter and capture all the items in an array. (See the docs if that doesn't make sense.)
Calling exit or die in CodeIgniter is a bad habit - not recommended. We're not doing procedural programming here. Using them will short-circuit the framework's normal execution path and, in this case, bypass several "hook" points that might be defined. Let functions return and have CI follow its normal execution path.
It's important to know that the call to base_url() only works because the JavaScript is included inline. If you load the js from an external file (e.g. <script src="assets/js/maps.js"></script>) it will not evaluate correctly.
You'll have to find another way to create a full URL, or use a relative URL.
Here's how to use an external js file, send and fetch a couple of parameters, use a relative URL, and respond with and utilize json.
The view
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button value="test" id='mapsave'>Click Me</button>
<div id="response"></div>
<script src="assets/js/maps.js"></script>
</body>
</html>
The Controller
class Maps extends CI_Controller
{
public function index()
{
$this->load->view('viewMap');
}
public function insert_church_details()
{
$name = $this->input->get('name');
$addr = $this->input->get('address');
echo json_encode(['name' => $name, 'addr' => $addr]);
}
}
The javascript
var el = document.getElementById("mapsave");
el.addEventListener("click", saveData, false);
function saveData() {
var res = document.getElementById("response");
var request = new XMLHttpRequest();
var name, url, address;
name = "Stevin";
address = 'Home';
url = '/maps/insert_church_details?name=' + name + '&address=' + address;
request.onreadystatechange = function () {
var out;
if (request.readyState == 4) {
out = JSON.parse(request.responseText);
res.innerHTML = out.name + ", " + out.addr;
}
};
request.open('GET', url, true);
request.send();
}
Just try use and replace {controllerName} into your controller name and replace {functionName} into controller method name:
var url = '<?php echo base_url(); ?>{controllerName}/{functionName}?name=' + name + '&address=' + address +
'&type=' + type + '&lat=' + latlng.lat() + '&lng=' + latlng.lng();

XMLHttpRequest response status based on posted value

I have my JavaScript function which does XMLHttpRequest. Here is my code.
function addbilldetails() {
// Cancel the form submit
event.preventDefault();
// The URL to POST our data to
var postUrl = 'http://example.com/post.php';
// Set up an asynchronous AJAX POST request
var xhr = new XMLHttpRequest();
xhr.open('POST', postUrl, true);
// Prepare the data to be POSTed
var clientId = "clientid",
submittype = "a",
name = encodeURIComponent(document.getElementById('name').value),
billno = encodeURIComponent(document.getElementById('billno').value),
mobileno = encodeURIComponent(document.getElementById('mobileno').value),
phoneno = encodeURIComponent(document.getElementById('phoneno').value),
netAmount = encodeURIComponent(document.getElementById('netAmount').value);
var params = 'clientId=' + clientId +
'&billno=' + billno +
'&mobileno=' + mobileno +
'&phoneno=' + phoneno +
'&netAmount=' + netAmount +
'&type=' + submittype +
'&name=' + name;
// Replace any instances of the URLEncoded space char with +
params = params.replace(/%20/g, '+');
// Set correct header for form data
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// Handle request state change events
xhr.onreadystatechange = function() {
// If the request completed
if (xhr.readyState == 4) {
statusDisplay.innerHTML = '';
if (xhr.status == 200) {
// If it was a success, close the popup after a short delay
statusDisplay.innerHTML = 'Saved!';
document.getElementById('save').disabled = false;
// window.setTimeout(window.close, 1000);
} else {
// Show what went wrong
statusDisplay.innerHTML = 'Error saving: ' + xhr.statusText;
}
}
};
// Send the request and set status
xhr.send(params);
statusDisplay.innerHTML = 'Saving...';
document.getElementById('save').disabled = true;
}
Now, the above code works perfectly and returns 200 on POST. But I want it to return custom message on the UI based on the value posted.
If the value POSTed is less than the value in the database, I want it to give "Enter Valid number" or something like this.
I am quiet new to XMLHttpRequest . I do not know how to achieve that. Any help would be highly appreciated.
Instead of statusDisplay.innerHTML = 'Saved!'; have you considered:
statusDisplay.innerHTML = xhr.responseText;
If you do this, then your statusDisplay will be equal to whatever your post.php echos out.
For example, in post.php
<?php
//handling $_POST['clientId'] ... etc
if (error)
echo "Enter Valid Number";
else
echo "Saved!";

XMLHttpRequest.responseText doesnt write the value when calling a URL

There may be a small error in my code. please advice me.
I want to call a URL and display the value in div on pageload.I wrote this code from SO but the responseText doesnt write the value in the div element's innerhtml
Code
<script type="text/javascript" >
var req ;
// Browser compatibility check
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
var req = new XMLHttpRequest();
req.open("GET", "www.example.com/Default.aspx?usrname=john",true);
req.onreadystatechange = function () {
document.getElementById('divTxt').innerHTML = "My Status: " + req.responseText;
}
req.send(null);
</script>
<html>
<head/>
<body>
<div id="divTxt"></div></body>
</html>
The output I get is
My status :
PS: I want this to be done after pageload and The url returns a value "online" when called manually
EDIT
This is the code I referred : code
You cannot ajax a url from another domain unless it has implemented CORS
If you need to get data from somewhere which is not same origin you need to use JSONP
Also to debug, try calling the url from the locationbar to see if you receive valid data for your request
req.onreadystatechange = function () {
document.getElementById('divTxt').innerHTML = "My Status: " + req.responseText;
}
you have to check, if the request was successful:
if (req.readyState === 4) {
// what should be done with the result
}
finally, it has to look like this:
req.onreadystatechange = function () {
if (req.readyState === 4) {
document.getElementById('divTxt').innerHTML = "My Status: " + req.responseText;
}
}

Categories