Why is JSON Data Not Inserting Properly - javascript

I am trying to render local JSON data to the DOM using the following code, but it's not working. I'm not sure what I am doing wrong and would appreciate any help.
HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="model-controller.js"></script>
</head>
<body>
<button id="clickMe" style="background-color: #000; color: white;" onClick="myObj()">Click ME</button>
</div>
<div id="demo"></div>
</body>
</html>
model-controller.js
var myObj = JSON.parse("item-data.json", function(data) {return data});
document.getElementById("demo").innerHTML = data;
};
myObj();

The JSON.parse function gets a string that represents a json encoded object, and not a path to a file.
If you need to parse a file you can use jquery to access the file
$.getJSON('item-data.json', function(data) {
document.getElementById("demo").innerHTML = data;
});
Or get the content of the file using vanilla javascript and then JSON.parse it:
var request = new XMLHttpRequest();
request.open("GET", "item-data.json", false);
request.send(null)
var json_obj = JSON.parse(request.responseText);
document.getElementById("demo").innerHTML = json_obj;

JSON.parse parses a given string into a JS object. It doesn't load an external file though. See this page for more info on the JSON.parse method
What you want to do is fetch the file with e.g. jQuery.getJSON, jQuery.get or axios.
jQuery.get( 'https://api.coinbase.com/v2/prices/spot?currency=USD', ( data ) => {
$( '#result' ).text( JSON.stringify( data, null, 2 ) );
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="result"></pre>

Related

Convert input textfield to plain text and use it as PHP variable

I am trying to convert an input textfield to plain text and use it as a PHP variable but I don't know how to do it.
Here's my sample code to convert input to plain text:
HTML
<input type="text" id="fileserver"> <button onclick="disable_all();">SUBMIT</button>
And here's my JavaScript code:
function disable_all(){ $( "body" ).html($( "#fileserver" ).val()); }
Is there any way that I can use the converted text to hold as PHP variable? I hope someone can help me. Thank you so much. :)
FIDDLE FOR REFERENCE
As PHP runs on the server and has finished before the client ( browser ) gets the webpage and because javascript runs in the client ( browser ) you need to send the javascript variable to PHP via some means. You can use a form submission - PHP would process the submitted data but this does mean you leave the current thread. The more common way to send data to the backend is via Ajax or Fetch
The example below sends a simple Ajax request to the same page ( can be any php script not just same page ), does some tasks ( modifies the POST array data here for illustration ) and sends a response which the ajax callback can process.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST'){
/* Allow PHP to process the request, perform whatever tasks it has to do and then send reply */
$_POST['time']=time();
$_POST['date']=date( DATE_ATOM );
$_POST['ip']=$_SERVER['REMOTE_ADDR'];
$_POST['reversed']=strrev( $_POST['fileserver'] );
exit( json_encode( $_POST ) );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<script>
/* ajax callback - this can do lots more than simply display response in the console. */
const callback=function( r ){
console.info( r )
};
/* ultra simple ajax function to send a POST request to the same page */
const ajax=function(data,callback){
let xhr=new XMLHttpRequest();
xhr.onload=function(){
if( this.status==200 && this.readyState==4 )callback( this.response )
};
xhr.open( 'POST', location.href, true );
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send( data );
};
/* invoke the ajax function when the button is pressed */
const disable_all=function(){
let data={
fileserver:document.querySelector( 'input[ name="fileserver" ]' ).value
};
let payload=Object.keys( data ).map( k=>{
return [ k, data[ k ] ].join('=')
})
ajax( payload, callback );
};
</script>
</head>
<body>
<input type='text' name='fileserver' id='fileserver' value='Open the console to view the result' />
<button onclick='disable_all();'>SUBMIT</button>
</body>
</html>
is this what you mean?
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<script>
const convert_to_text=function(e){
let input=document.querySelector( 'input[ name="fileserver" ]' );
let text=document.createTextNode( input.value );
input.replaceWith( text );
};
</script>
</head>
<body>
<input type='text' name='fileserver' id='fileserver' />
<button onclick='convert_to_text()'>Convert</button>
</body>
</html>

jQuery getJson no response when searching solr

I am trying to search a local Solr core and am getting no response using getJSON. I know the URL works and returns a response but the getJson function seems to return null.
<!DOCTYPE html>
<html>
<head>
<title>Ray Search</title>
</head>
<body>
Document ID:<br>
<input id="query" type="text" name="document_ID"><br>
<button onclick="searchSolr();">Search</button>
<div id="results">
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type='text/javascript'>
function searchSolr() {
var searchStr = $('#query').val();
if (searchStr.length == 0) {
return;
}
var searchURL = "http://localhost:8983/solr/Ray-Docs/select?q=*&wt=json&json.wrf=on_data";
$.getJSON(searchURL, function (result) {
var docs = result.response.docs;
var total = 'Found ' + result.response.numFound + ' results';
$('#results').prepend('<div>' + total + '</div>');
});
}
</script>
</html>
Did you try invoking getJSON like below?
jQuery.getJSON(sourceURL).done(function(returnData){
//Data Processing
});

How to get json using .getjson

I have an endpoint https://api.iextrading.com/1.0/tops?symbols=aapl but when I try to use .getjson with that url I get a 404 error. In the api documentation it mentions that it may be a jsonp request and if so how do I get .getjson to be able to read this call. Thank you in advance.
The code I have tried is...
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
</head>
<body>
<h2>Create Object from JSON String</h2>
<p id="demo"></p>
<script>
$.getJSON('https://api.iextrading.com/1.0/stock/tsla', function(data) {
var obj = JSON.parse(data);
document.getElementById("demo").innerHTML = obj.id;
});
</script>
</body>
</html>
The API or remote resource must set the header. You can try
function(xhr) {
xhr.setRequestHeader('X-Test-Header', 'test-value');
}
The URL you are using doesn't match your description's URL, and the URL actually returns a 404.
Using your description's URL works, however getJSON parses the data so we don't need to do JSON.parse(data);.
Finally, your data doesn't actually have a id attribute so that will return undefined.
I have changed it to symbol which returns AAPL.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
</head>
<body>
<h2>Create Object from JSON String</h2>
<p id="demo"></p>
<script>
$.getJSON('https://api.iextrading.com/1.0/tops?symbols=aapl', function(data) {
var obj = data[0];
document.getElementById("demo").innerHTML = obj.symbol;
});
</script>
</body>
</html>

Load external JSON file

I can't seem to get JSON when it's from an external file. When I write it inline, it works fine. But when I created a file called test.json and copied the JSON in to it, I never get the contents.
Here's my HTML and JavaScript. I should note that both HTML and JSON files are within the same folder.
What am I doing wrong?
<!DOCTYPE html>
<html>
<head>
<title>JSON Sandbox</title>
</head>
<body>
<h2>JSON Sandbox</h2>
<p id="demo"></p>
<script type="text/javascript">
var text = $.getJSON({
dataType : "json",
url : "test.json",
data : data,
success : window.alert("JSON Aquired.")
});
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.name + "<br>" + obj.street + "<br>" + obj.phone;
</script>
</body>
</html>
Here's my test.json file
{
"name":"John Johnson",
"street":"Oslo West 1",
"phone":"111 1234567"
}
Change the file extension to js.
and change the html file as below:
<!DOCTYPE html>
<html>
<head>
<title>JSON Sandbox</title>
<script src="jquery-1.8.2.min.js"></script>
</head>
<body>
<h2>JSON Sandbox</h2>
<p id="demo"></p>
<script type="text/javascript">
var obj = new Object();
var error = new Object();
$.getJSON('test.js').done(function (data) {
obj = data;
document.getElementById("demo").innerHTML = obj.name + "<br>" + obj.street + "<br>" + obj.phone;
}).error(function (err) {
error = err;
});
</script>
</body>
</html>
Your success handler is defined incorrectly.
Replace:
success : window.alert("JSON Aquired.")
With:
success : function(data){
window.alert("JSON Aquired.")
// `data` is the returned object:
document.getElementById("demo").innerHTML = data.name + "<br>" + data.street + "<br>" + data.phone;
}
You need to do what you want to do with the data, in the success handler, because $.getJSON is an AJAX call, which means it's asynchronous.

get element Tag value from the xml

this is my JavaScript code:-
<!DOCTYPE html>
<html>
<head>
<title>Geolocation API with Google Maps API</title>
<meta charset="UTF-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body onload="getlg()">
<script>
function getlg(){
var region = $('#region').val();
var xml;
$.ajax({
url: "http://maps.googleapis.com/maps/api/geocode/xml?address="+$("#region").html()+"&sensor=true",
async: false,
dataType:'text/xml',
success: function(data){
xml=data;
$('#Div_Get').html('');
}
});
xmlDoc = $.parseXML( xml );
$xml = $( xmlDoc );
var abc= xmlDoc.getElementsByTagName("lat")[1].firstChild.nodeValue;
}
</script>
<div id="region">Rajkot</div>
<div id = "Div_Get"></div>
</body>
</html>
here i am try to set value in url and get the xml file.
now i try to get from this xml lat and long value.
i am try getElementsByTagName but not success nothing is output and give me error xmlDoc is null on this line var abc= xmlDoc.getElementsByTagName("lat")[1].firstChild.nodeValue;
please help me out of this.
thanks.
Change you datatype from
dataType:'text/xml',
To
dataType:'xml',
And Please have a look at documentation for Specifying the Data Type for AJAX Requests.

Categories