unable to get response from rest api using XMLHttpRequest - javascript

i want to call get rest api using XMLHttpRequest, but I'm getting error -
"Uncaught SyntaxError: Unexpected end of JSON input".
rest api json response data
{
"timestamp": "2018-06-08T16:52:50.509Z",
"dataFrame": "AQAAKCoAAQgFKgABBg==",
"fcnt": 825,
"freq": 865572000,
"port": 2,
"rssi": -115,
"snr": -16,
"sf_used": 12,
"id": 1528476770509,
"dr_used": "SF12BW125",
"decrypted": true
}
code
<script>
function UserAction() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "url", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.setRequestHeader("Authorization", "Basic a2Vyb==");
xhttp.send();
var response = JSON.parse(xhttp.responseText);
}
</script>
Edit:
code
<script>
function userAction() {
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
let response = JSON.parse(xhttp.responseText);
var dataFrame = response.dataFrame;
/** code that handles the response **/
}
};
xhttp.open("GET", "url", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.setRequestHeader("Authorization", "Basic a2VybmVsc==");
xhttp.send();
</script>
HTML
<button type="submit" onclick="userAction()">Search</button>
<h1 id="data"></h1>

You should listen to the XMLHTTPRequest.onreadystatechange event for your request, so that the result is only parsed once the request is done:
functio userAction() {
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let response = JSON.parse(xhttp.responseText);
document.getElementById("data").innerHTML = response.dataFrame;
}
};
xhttp.open("GET", "filename", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.setRequestHeader("Authorization", "Basic a2Vyb==");
xhttp.send();
}

You need to set the xhttp.onreadystate property to a callback function to handle the various states and then process the response when it's been received.
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange

You should check the status of the request before outputting it.
function UserAction() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "url", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.setRequestHeader("Authorization", "Basic a2Vyb==");
xhttp.onload = function(){
if(xhttp.status ==200){
var response = JSON.parse(xhttp.responseText);
}
}
xhttp.send();
}

Related

Need help getting a response from API

I formulated this XHR request by converting it from curl.
the curl request works but can't get this one working. plz help.
var url = "https://networkappers.com/api/port.php?ip=172.217.13.238&port=80";
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("Referer", "https://www.networkappers.com/tools/open-port-checker");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
}
};
xhr.send();

Not able to echo POST paramenters sent in ajax, inside PHP

I am sending two parameters inside the send method to index.php. But the PHP returns an error "Undefined index". echo $_POST['fname'];
submit.addEventListener("click", function(e){
e.preventDefault();
var xhr = new XMLHttpRequest();
xhr.open("POST", "index.php", true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.onreadystatechange = function () {
if(xhr.readyState == 4 && xhr.status == 200) {
var result = xhr.responseText;
console.log(result);
}
}
xhr.send("fname=Henry&lname=Ford");
});
In order to send form data through Ajax, you have to specify the content type of the request. In you case it will be 'application/x-www-form-urlencoded:
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
So your code will be:
submit.addEventListener("click", function(e){
e.preventDefault();
var xhr = new XMLHttpRequest();
xhr.open("POST", "index.php", true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.onreadystatechange = function () {
if(xhr.readyState == 4 && xhr.status == 200) {
var result = xhr.responseText;
console.log(result);
}
}
xhr.send("fname=Henry&lname=Ford");
});

JQuery Ajax call working but not native JavaScript

I have two AJAX calls, one in native JavaScript and another with JQuery, which call a PHP Script. The JQuery one is working, but the JavaScript one not. Here goes the code:
JQuery:
$.ajax({
url: "/Tests/index.php",
method: "POST",
data: {'Id': "2"}
});
Native JavaScript:
var Data = {Id: "2"};
XHR = new XMLHttpRequest();
XHR.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(XHR.responseText);
}
}
XHR.open("POST", "/Tests/index.php", true);
XHR.setRequestHeader("Content-Type", "application/json");
XHR.send(JSON.stringify(Data));
PHP Script:
echo var_dump($_POST);
The one with JQuery returns 2, but the JavaScript one, doesn't return anything. All the data is seen through the console of the web browser.
Try this code:
var Data = {"Id": "2"};
var XHR = new XMLHttpRequest(); // declared XHR var
XHR.open("POST", "/Tests/index.php", true);
XHR.setRequestHeader("Content-Type", "application/json");
XHR.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(XHR.responseText);
}
}
XHR.send(Data); // sending data without converting to string
Reference: https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp

XMLHttpRequest is sending "null" content type

I have following javascript code which is sending a null in content type
<script>
var xhttp;
if (window.XMLHttpRequest){
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var clientToken;
xhttp.onreadystatechange = function(){
if (xhttp.readyState == 4 && xhttp.status == 200){
clientToken = xhttp.responseText.content;
}
};
xhttp.open("GET", "http://localhost:8080/client/123/token", true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.send();
braintree.setup(clientToken, "dropin", {
container: "payment-form"
});
</script>
I am accessing this file outside of any server i.e., in browser I am putting

How to display POST values which are coming from javascript XMLHttpRequest() in php

I am sending parameters using XMLHttpRequest() javascript function to another php page in Json formate, but $_POST['appoverGUID'] not getting post values.
Here is my Javascript code.
function loadPage(href){
var http = new XMLHttpRequest();
var url = json.php;
var approverGUID = "Test";
var params = JSON.stringify({ appoverGUID: approverGUID });
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/json; charset=utf-8");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
document.getElementById('bottom').innerHTML = http.responseText;
}
}
http.send(params);
}
And here is my json.php file code.
if(isset($_POST['appoverGUID'])){
echo $_POST['appoverGUID'];
}
First of all remove these headers since they will be send automatically by the browser and it's the right way to do it.
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
This code is a cross browser solution and it's tested.
// IE 5.5+ and every other browser
var xhr = new(window.XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0');
var params = "appoverGUID="+approverGUID;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.setRequestHeader("Accept", "application/json");
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
console.log(JSON.parse(this.responseText));
}
}
}
xhr.send(params);
xhr = null;
You need use json_decode. Some like this:
if ("application/json" === getallheaders())
$_JSON = json_decode(file_get_contents("php://input"), true) ?: [];
Fill params this way (did no escaping/encoding of approverGUID content, here..):
params = "appoverGUID="+approverGUID;
Also see:
http://www.openjs.com/articles/ajax_xmlhttp_using_post.php

Categories

Resources