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.
Related
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
});
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 5 years ago.
I'm sorry if I'm missing something obvious like having " instead of ' but I tried many different ways and it still does the same thing, i.e. displays the actual javascript code, instead of the functionality, when I put it inside a .html file or gives me this error:
Parse error: syntax error, unexpected '<' in E:\XAMPP\htdocs\website2\test.php on line 9
When I place it inside of a php file.
Here's the code:
<!DOCTYPE html>
<html>
<head>
<script src="js.js" type="text/javascript"></script>
<title>TEST</title>
</head>
<body>
<?php
echo '<script type="text/javascript">
var https = require("https");
var username = "04d2ac7f76a0fbc0eee9dc5ef96b9259";
var password = "dc70ffc7ad911236bc2e0822855e2d42";
var auth = "Basic " + new Buffer(username + ':' + password).toString('base64');
var request = https.request({
method: "GET",
host: "api.intrinio.com",
path: "/companies?ticker=AAPL",
headers: {
"Authorization": auth
}
}, function(response) {
var json = "";
response.on('data', function (chunk) {
json += chunk;
});
response.on('end', function() {
var company = JSON.parse(json);
console.log(company);
});
});</script>';
?>
</body>
</html>
Why just not do without the php tag?
The error is because you not escape the single quotes in your code.
Example without php:
<!DOCTYPE html>
<html>
<head>
<script src="js.js" type="text/javascript"></script>
<title>TEST</title>
</head>
<body>
<script type="text/javascript">
var https = require("https");
var username = "04d2ac7f76a0fbc0eee9dc5ef96b9259";
var password = "dc70ffc7ad911236bc2e0822855e2d42";
var auth = "Basic " + new Buffer(username + ':' + password).toString('base64');
var request = https.request({
method: "GET",
host: "api.intrinio.com",
path: "/companies?ticker=AAPL",
headers: {
"Authorization": auth
}
}, function(response) {
var json = "";
response.on('data', function (chunk) {
json += chunk;
});
response.on('end', function() {
var company = JSON.parse(json);
console.log(company);
});
});</script>
</body>
</html>
Example with php:
<!DOCTYPE html>
<html>
<head>
<script src="js.js" type="text/javascript"></script>
<title>TEST</title>
</head>
<body>
<?php
echo '<script type="text/javascript">
var https = require("https");
var username = "04d2ac7f76a0fbc0eee9dc5ef96b9259";
var password = "dc70ffc7ad911236bc2e0822855e2d42";
var auth = "Basic " + new Buffer(username + ':' + password).toString(\'base64\');
var request = https.request({
method: "GET",
host: "api.intrinio.com",
path: "/companies?ticker=AAPL",
headers: {
"Authorization": auth
}
}, function(response) {
var json = "";
response.on(\'data\', function (chunk) {
json += chunk;
});
response.on(\'end\', function() {
var company = JSON.parse(json);
console.log(company);
});
});</script>';
?>
</body>
</html>
But more important this is a node.js code and not a client-side javascript.
I recommend you get some node and javascript tutorials.
You should escape ' in with \' in your code.
You're right in suspecting you've placed ' and " in improper places without escaping, as pointed out by Ivan.
<!DOCTYPE html>
<html>
<head>
<script src="js.js" type="text/javascript"></script>
<title>TEST</title>
</head>
<body>
<?php
echo '<script type="text/javascript">
var https = require("https");
var username = "04d2ac7f76a0fbc0eee9dc5ef96b9259";
var password = "dc70ffc7ad911236bc2e0822855e2d42";
var auth = "Basic " + new Buffer(username + \':\' + password).toString(\'base64\');
var request = https.request({
method: "GET",
host: "api.intrinio.com",
path: "/companies?ticker=AAPL",
headers: {
"Authorization": auth
}
}, function(response) {
var json = "";
response.on(\'data\', function (chunk) {
json += chunk;
});
response.on(\'end\', function() {
var company = JSON.parse(json);
console.log(company);
});
});</script>';
?>
</body>
Echo function is used to output the string and you are echoing a code statement which is not a valid string. Put it as in single line as:
<?php echo '<script type="text/javascript">var https = require("https");var username = "04d2ac7f76a0fbc0eee9dc5ef96b9259";var password = "dc70ffc7ad911236bc2e0822855e2d42";var auth = "Basic " + new Buffer(username + ':' + password).toString(\'base64\');var request = https.request({method: "GET",host: "api.intrinio.com",path: "/companies?ticker=AAPL",headers: {"Authorization": auth}}, function(response) {var json = "";response.on(\'data\', function (chunk) {json += chunk;});response.on(\'end\', function() {var company = JSON.parse(json);console.log(company);});});</script>';?>
I am facing problem by using "JSON.stringify" and "Json.parse" for string. The application uses client broweser via Javascript to read a textfile (JSON string) from server via PHP.
The problem is that after I used "stringify", the output of the string printed as follow:
"\r\n\r\n\r\n\t\r\n\r\n\r\n\r\n\r\n{\"employees\":[{\"firstName\":\"John\",\"lastName\":\"Doe\" },{\"firstName\":\"Anna\",\"lastName\":\"Smith\" },{\"firstName\":\"Peter\",\"lastName\":\"Jones\" }]}\r\n\r\n"
If not using "stringify", it printed as same as the original text in
the text file.
If I use "JSON.stringify" then "Json.parse" it show error as below:
Unexpected token < in JSON at position 0
at JSON.parse ()
The code are the following:
Sample of textfile:
{"employees":[{"firstName":"John","lastName":"Doe" },{"firstName":"Anna","lastName":"Smith" },{"firstName":"Peter","lastName":"Jones" }]}
HTML with Javascript page:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
var text = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';
function printEmployee() {
obj = JSON.parse(text);
var selEmployee = document.getElementById("selEmployee");
document.getElementById("demo").innerHTML =
obj.employees[selEmployee.selectedIndex].firstName + " " + obj.employees[selEmployee.selectedIndex].lastName;
}
function postToPhp() {
var dataString = JSON.stringify(text);
$.post("processJson.php",
{
dataString
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
}
function postAsyncGet()
{
getToPhp()
.then(viewGetResult);
}
function getToPhp() {
var dataString;
$.get("readJson.php",
{
dataString
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
viewGetResult(data);
});
}
function viewGetResult(dataString) {
var jsonstr = JSON.stringify(dataString.trim());
//var obj = JSON.parse(dataString);
document.getElementById("demo").innerHTML = dataString;
var selEmployee = document.getElementById("selEmployee");
//document.getElementById("demo").innerHTML =
//obj.employees[selEmployee.selectedIndex].firstName + " " + //obj.employees[selEmployee.selectedIndex].lastName;
}
</script>
</head>
<body>
<h2>Create Object from JSON String</h2>
<label>
Select an Employee:
</label>
<select id = "selEmployee">
<option value = "1" selected="selected">1</option>
<option value = "2">2</option>
<option value = "3">3</option>
</select>
<p>Print Me!</p>
<p>Post Me to PHP!</p>
<p>Get from PHP!</p>
<p id="demo"></p>
</body>
</html>
PHP Code
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<?php
$obj = json_decode($_POST["dataString"]);
echo $obj->var;
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
fwrite($myfile, $obj );
fclose($myfile);
?>
</body>
</html>
You may find complete solution at https://github.com/kehkok/php_server-json-javascript_client#php_server-json-javascript_client
Happy sharing.
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
</head>
<body>
<div id="div1">dv1</div>
<div id="div2">dv2</div>
<script type="text/javascript">
function getData(){
$.ajax({
type:"GET",
url:"j.json",
dataType:"json",
success: function(jsondata){
output(jsondata);
}
});
}
function output(json){
//var Data = eval('(' + json + ')');
var html = '';
//alert(Data.length);
for(var i=0;i<json.length;i++){
html += ' name:' + json[i].name + ' age:' + json[i].age;
}
document.getElementById('div1').innerHTML = html;
document.getElementById('div2').innerHTML = json[0].name;
}
setTimeout(getData, 3000);
</script>
</body>
</html>
j.json file is
[{"name":"aaa","age":18},{"name":"bbb","age":19}]
The aim of above code is to update div content with data in local json file. I've tried that in IE & Chrome, but neither worked. I've googled a lot but still can't figure it out.
Anyone got any hints? Thanks in advance.
Do you use web server?
AJAX calls doesnt work with URL starting with file://. This because of the same-origin requirements which were instituted to help deal with cross-site scripting (XSS). See here for more details.
And as I noticed, you should use $(document).ready(function(){ your code }) instead of setTimeout(getData, 3000);
Javascript newbie here. I have a javascript function that works nested in an html file, I import an external library abaaso, then declare the function and then call it:
<!DOCTYPE html>
<html>
<head>
<title>title</title>
<script src="abaaso.js"></script>
</head>
<body>
<script>
var baseurl = "https://example.com";
var baseapi = baseurl + "/api/v1/";
var api_username = "user";
var api_key = "key";
var credentials = "?api_username=" + api_username + "&api_key=" + api_key;
var rawdata = {};
(function ($$) {
/* login */
login = function(username, password) {
var calledUrl = baseapi + "user/login/" + credentials;
calledUrl.post(
function (content) {
/*console.log("success" + JSON.stringify(content, null, 4));*/
},
function (e) {
console.log("it failed! -> " + e);
},
{
"username": username,
"password": password
},
{"Accept" : "application/json"}
);
}
})(abaaso);
login('test#example.com', 'passwd');
</script>
</body>
</html>
I want to put it in an external .js file and import it and only use the call to the function login('test#example.com', 'passwd');. I don't want to import abaaso from the html file but from the new .js.
How can I do that? Is there a particular structure to respect? Do I need to create a global function to the js file?
I don't want to import abaaso from the html file but from the new .js.
You can't do that. However, you can import both abaaso and the new .js:
<head>
<title>title</title>
<script src="abaaso.js"></script>
<script src="new.js"></script>
</head>