Trying to display Json response in HTML using JS - javascript

I'm trying to display json on web page and i'm using the following code but it doesn't work, who can help me understand what am i doing wrong?
<button type="submit" onclick="javascript:send()">call</button>
<div id="div"></div>
<script type="text/javascript" language="javascript">
function send()
{
var xmlhttp = new XMLHttpRequest();
//xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
xmlhttp.open("GET", "http://stam/1.1/json/url=https://www.google.co.il");
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.send();
xmlhttp.responseType = 'json';
xmlhttp.setRequestHeader("Content-Type", "application/json");
//xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
var requestDoneAndOK = false;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4) {
if (xmlhttp.status === 200) {
//requestDoneAndOK = true;
var jsonResponse = JSON.parse(xmlhttp.responseText);
document.getElementById("div").innerHTML = xmlhttp.statusText + ":" + xmlhttp.status + "<BR><textarea rows='100' cols='100'>" + jsonResponse + "</textarea>";
}
}
};
}
</script>

Your url is not correct. Also you should removed the commented out lines mentioned in the code to make it work.
You can use this dummy url to check if it's working:
https://reqres.in/api/users?page=2
function send()
{
var xmlhttp = new XMLHttpRequest();
//xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
xmlhttp.open("GET", "http://stam/1.1/json/url=https://www.google.co.il");
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.send();
// Remove the below commented lines and change the url
// xmlhttp.responseType = 'json';
// xmlhttp.setRequestHeader("Content-Type", "application/json");
// xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
var requestDoneAndOK = false;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4) {
if (xmlhttp.status === 200) {
//requestDoneAndOK = true;
var jsonResponse = JSON.parse(xmlhttp.responseText);
document.getElementById("div").innerHTML = xmlhttp.statusText + ":" + xmlhttp.status + "<BR><textarea rows='100' cols='100'>" + jsonResponse + "</textarea>";
}
}
};
}

The URL you provided does not seem to work. Open the browser console (F12 and switch to the console tab). If you try http://date.jsontest.com/, for example, the browser console will log any errors.
For some reason, Firefox allowed me to make the request, but Chromium did not. Chromium's console provided the exact line numbers where there were issues.
I removed the second xmlhttp.setRequestHeader("Content-Type", "application/json");.
It also told me that the response type in xmlhttp.responseType = 'json'; should be text.
Here is the final product. Notice that I have to specify the key of the JSON object in order to get its value: jsonResponse.time
<button type="submit" onclick="javascript:send()">call</button>
<div id="div"></div>
<script type="text/javascript" language="javascript">
function send() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://date.jsontest.com/");
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.send();
xmlhttp.responseType = 'text';
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4) {
if (xmlhttp.status === 200) {
var jsonResponse = JSON.parse(xmlhttp.responseText);
document.getElementById("div").innerHTML = xmlhttp.statusText + ":" + xmlhttp.status + "<br><textarea rows='100' cols='100'>" + jsonResponse.time + "</textarea>";
}
}
};
}
</script>
To print out the entire JSON object:
// var jsonResponse = JSON.parse(xmlhttp.responseText); No need for this.
document.getElementById("div").innerHTML = xmlhttp.statusText + ":" + xmlhttp.status + "<br><textarea rows='100' cols='100'>" + xmlhttp.responseText + "</textarea>";
Also, the concept of unobtrusive JavaScript is worth taking a look at.

Related

I've got "The object's state must be OPENED."

I've tried to perform AJAX request, but I've got this kind of error, that ajax call should be opened. But it is opened already. Trying to send the XMLHttpRequest header, but getting this kinda error. Guys, help me!
let del_btn = document.querySelectorAll('.delete');
for(let i = 0; i < del_btn.length; i++)
{
del_btn[i].addEventListener('click', function(){
let xhr = new XMLHttpRequest();
let book_title = del_btn[i].parentElement.children[1].children[1].children[0].children[0].textContent;
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
if(this.responseText.includes('Deleted'))
{
let books = this.responseText.split('.')[1];
if(books == '0')
{
del_btn[i].parentElement.parentElement.innerHTML = 'You have no books in your list. Go to the ' + ' ' + ' main page ' + ' ' + 'and start your ride!';
}
else
{
del_btn[i].parentElement.parentElement.removeChild(del_btn[i].parentElement);
document.querySelector('.amount-b').textContent = 'Количество книг: ' + books;
}
}
}
}
xhr.open("POST", "../operations/delete_book.php", true);
xml.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('title=' + book_title);
}, false);
}```

How to use global function with return in React-Native?

I want to create a global helper file as most of the page will call to same function but with different parameters. I have try several ways and all did not return the value as if I place the script within the same screen.
I'm testing to get response from SOAP WSDL.
URL: 'http://mytesting.justdummy.com/android.asmx'
Content-Type: text/xml
SOAPAction: http://tempuri.org/GetServerTime
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetServerTime xmlns="http://tempuri.org/" />
</soap:Body>
</soap:Envelope>
I have test it using Postman and I get the server time response.
Below is what I currently tried:-
Method 1:
const soapAPI= {
fetchSOAPRequest: function (soapFunction, soapBody) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', global.valServerURL, true);
// build SOAP request
var soapRequest =
'<?xml version="1.0" encoding="utf-8"?>' +
'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' +
'<soap:Body>' +
`<${soapFunction} xmlns="http://tempuri.org/">` +
soapBody +
`</${soapFunction}>` +
'</soap:Body>' +
'</soap:Envelope>';
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
return xmlhttp.responseText;
}
}
}
// Send the POST request
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.setRequestHeader('SOAPAction', `http://tempuri.org/${soapFunction}`);
xmlhttp.send(soapRequest);
}
}
export default soapAPI;
Method 2:
export const fetchSOAPRequest = async (soapFunction, soapBody) => {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', global.valServerURL, true);
// build SOAP request
var soapRequest =
'<?xml version="1.0" encoding="utf-8"?>' +
'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' +
'<soap:Body>' +
`<${soapFunction} xmlns="http://tempuri.org/">` +
soapBody +
`</${soapFunction}>` +
'</soap:Body>' +
'</soap:Envelope>';
console.warn(soapRequest);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
return xmlhttp.responseText;
}
}
}
// Send the POST request
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.setRequestHeader('SOAPAction', `http://tempuri.org/${soapFunction}`);
xmlhttp.send(soapRequest);
};
Method 3 from here:
function fetchSOAPRequest(soapFunction, soapBody) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', global.valServerURL, true);
// build SOAP request
var soapRequest =
'<?xml version="1.0" encoding="utf-8"?>' +
'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' +
'<soap:Body>' +
`<${soapFunction} xmlns="http://tempuri.org/">` +
soapBody +
`</${soapFunction}>` +
'</soap:Body>' +
'</soap:Envelope>';
console.warn(soapRequest);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
return xmlhttp.responseText;
}
}
}
// Send the POST request
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.setRequestHeader('SOAPAction', `http://tempuri.org/${soapFunction}`);
xmlhttp.send(soapRequest);
}
function fetchAnotherAPI(date) {
// your logic
}
export {
fetchSOAPRequest,
};
Method 1 and 2 is on the same '../components/services/soapAPI' file
On main class where the return should happen.
import { fetchSOAPRequest, soapAPI} from '../components/services/soapAPI';
onTestingRetrieve = async () => {
try {
// call from export constant
var myfirst = await fetchSOAPRequest('GetServerTime', '');
// call from object and function
var mysecond = await soapAPI.fetchSOAPRequest('GetServerTime', '');
// call from function within same class file
var mythird = await this.fetchSOAP('GetServerTime', '');
// alert to show response for confirmation only
Alert.alert('Response', JSON.stringify(resp));
} catch (e) {
Alert.alert('Error', 'SOAP request failed!\n' + e);
}
}
//On render
<TouchableOpacity style={styles.buttonContainer} onPress={this.onTestingRetrieve}>
<Text style={styles.buttonText}>Get server time</Text>
</TouchableOpacity>
But if I put the XMLHttpRequest within onTestingRetrieve, it will show the responseText without any problem as below.
onTestingRetrieve = async () => {
try {
const soapFunction = 'GetServerTime';
const soapBody = '';
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', global.valServerURL, true);
// build SOAP request
var soapRequest =
'<?xml version="1.0" encoding="utf-8"?>' +
'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' +
'<soap:Body>' +
`<${soapFunction} xmlns="http://tempuri.org/">` +
soapBody +
`</${soapFunction}>` +
'</soap:Body>' +
'</soap:Envelope>';
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
Alert.alert('Response', xmlhttp.responseText);
}
}
}
// Send the POST request
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.setRequestHeader('SOAPAction', `http://tempuri.org/${soapFunction}`);
xmlhttp.send(soapRequest);
} catch (e) {
Alert.alert('Error', 'SOAP request failed!\n' + e);
}
}
I have search for tutorial, example and SO question but I still failed to get the server time. Can anyone go through the script and point on which part I'm missing?

Ajax request: undefined

Hello there i wanted to request an api with ajax.
The api has plain json (what i thought)
now i set up an ajax request in javascript but i get an undefined error for the variables.I think i know the problem but I dont know an answer yet.
<script type="text/javascript">
document.getElementById("button").addEventListener('click', loadUsers);
// Load Github USers
function loadUsers(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "dontKnowtheUrl", true);
xhr.onload = function()
{
if(this.status == 200){
var stats = JSON.parse(this.responseText)
var output = "";
for(var i in stats){
output +=
'<div class="user">' +
'<ul>' +
'<li>p_level: '+stats[i].p_level+'</li>'+
'<li>p_currentmmr: '+stats[i].p_currentmmr+'</li>' +
'</ul>' +
'</div>';
}
document.getElementById("users").innerHTML = output;
}
}
xhr.send();
}
This was the javascript part
the json file from the api looks like this
{"results":
[{"p_id":"test",
"p_name":"test",
"p_level":"test",
"p_platform":"test",
"p_user":"test",
"p_currentmmr":"test",
"p_currentrank":"test",
"kd":"test"},
{"p_id":"test",
"p_name":"test",
"p_level":"test",
"p_platform":"test",
"p_user":"test",
"p_currentmmr":"test",
"p_currentrank":"test",
"kd":"test"}],
"totalresults":2}
My Guess is that the json file isnt a normal array because it contains the "results": and "totalresults" property.
Does Anyone know how to fix it without getting into the json file?
You're going to want to loop through stats.results instead of just stats, see the following example:
function loadUsers(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "dontKnowtheUrl", true);
xhr.onload = function()
{
if(this.status == 200){
var stats = JSON.parse(this.responseText)
var output = "";
for(var i in stats.results){
var row = stats.results[i];
output +=
'<div class="user">' +
'<ul>' +
'<li>p_level: '+row.p_level+'</li>'+
'<li>p_currentmmr: '+row.p_currentmmr+'</li>' +
'</ul>' +
'</div>';
}
document.getElementById("users").innerHTML = output;
}
}
xhr.send();
}

XMLHttpRequest. WSDL request. readyState == 4, but status == 0

I try to parse WSDL information from http://rates.kazpost.kz/postratesprodv2/postratesws.wsdl
But when I try it, I have nothing.
xmlhttp.readyState == 4, but xmlhttp.status == 0.
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'http://rates.kazpost.kz/postratesprodv2/postratesws.wsdl', true);
// build SOAP request
var sr =
'<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:pos="http://webservices.kazpost.kz/postratesws">' +
'<soapenv:Header/>' +
'<soapenv:Body>' +
'<pos:GetPostRateRequest>' +
'<pos:GetPostRateInfo>' +
'<pos:SndrCtg>1</pos:SndrCtg>' +
'<pos:Product>P102</pos:Product>' +
'<pos:MailCat>1</pos:MailCat>' +
'<pos:SendMethod>2</pos:SendMethod>' +
'<pos:Weight>750</pos:Weight>' +
'<pos:Dimension>s</pos:Dimension>' +
'<pos:Value>100</pos:Value>' +
'<pos:From>050031</pos:From>' +
'<pos:To>010001</pos:To>' +
'<pos:ToCountry>au</pos:ToCountry>' +
'</pos:GetPostRateInfo>' +
'</pos:GetPostRateRequest>' +
'</soapenv:Body>' +
'</soapenv:Envelope>';
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert('done. use firebug/console to see network response');
} else {
alert('ERROR. Status: ' + xmlhttp.status + " " + xmlhttp.statusText);
}
}
}
// Send the POST request
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send(sr);
// send request
// alert("Ready.");
Seems like you're trying to make http request under https connection, so request is blocked by browser for security reasons.
HTTP Ajax Request via HTTPS Page for more details

Get Particular node value in array from xml

I have one variable name as result in javascript Function.
The result variable's value is xml,
I need to form an Array with the opportunityid(which is highlighted in Image) values only.
how to get from the particular node value and form a array.?
I was used following Function,
function guid(){
var xml = "<?xml version='1.0' encoding='utf-8'?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
GenerateAuthenticationHeader() +
"<soap:Body>" +
"<RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
"<query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" +
"<q1:EntityName>opportunity </q1:EntityName>" +
"<q1:ColumnSet xsi:type='q1:ColumnSet'>" +
"<q1:Attributes>" +
"<q1:Attribute>opportunity id</q1:Attribute>" +
"</q1:Attributes>" +
"</q1:ColumnSet>" +
"<q1:Distinct>false</q1:Distinct>" +
"</query></RetrieveMultiple>" +
"</soap:Body></soap:Envelope>";
var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);
var result = xmlHttpRequest.responseXML.xml;
var doc = new ActiveXObject("MSXML2.DOMDocument");
doc.async = false;
doc.loadXML(result);
}
As I can see the structure of your xml, it is as follows:
<soap:Body>
<RetrieveMultipleResponse>
<RetrieveMultipleResult>
<BusinessEntities>
<BusinessEntity>
<q1:oppourtunityid>
</q1:oppourtunityid>
</BusinessEntity>
</BusinessEntities>
</RetrieveMultipleResult>
</RetrieveMultipleResponse>
</soap:Body>
for this you can make use of DOM Element as follows:
var businessEntites = result.getElementsByTagName('BusinessEntity');
var oppidArr = [];
for(var i=0; i<businessEntities.length; i++)
{
var oppid = businessEntites.item(i).getElementsByTagName('q1:oppourtunityid').item(0).childNodes[0].nodeValue;
oppidArr[i] = oppid;
}
I guess, you should try below code, I have copied some of it from Mozilla's site as it's having best practice code with conditions :)
function guid(){
var xml = "<?xml version='1.0' encoding='utf-8'?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
GenerateAuthenticationHeader() +
"<soap:Body>" +
"<RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
"<query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" +
"<q1:EntityName>opportunity </q1:EntityName>" +
"<q1:ColumnSet xsi:type='q1:ColumnSet'>" +
"<q1:Attributes>" +
"<q1:Attribute>opportunity id</q1:Attribute>" +
"</q1:Attributes>" +
"</q1:ColumnSet>" +
"<q1:Distinct>false</q1:Distinct>" +
"</query></RetrieveMultiple>" +
"</soap:Body></soap:Envelope>";
var xmlHttpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xmlHttpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!xmlHttpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
xmlHttpRequest.onreadystatechange = getContents;
xmlHttpRequest.open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);
function getContents() {
if (xmlHttpRequest.readyState === 4) {
if (xmlHttpRequest.status === 200) {
var xmldoc = xmlHttpRequest.responseXML;
var root_node = xmldoc.getElementsByTagName('q1:Attributes').item(0);
alert(root_node.firstChild.data);
} else {
alert('There was a problem with the request.');
}
}
}
}

Categories