Read textfile (Json) from server and send to client (Javascript) - javascript

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.

Related

Azure's Cognitive Services Emotion API returns 404

I am trying to build a web application which is supposed to use Microsoft Azures Cognitve Services Emotion API.
I use JavaScript (jQuery) to send a AJAX-request to my assigned endpoint-server.
This is my attempt:
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<h2>Face Rectangle</h2>
<ul id="faceRectangle">
</ul>
<h2>Emotions</h2>
<ul id="scores">
</ul>
<body>
<script type="text/javascript">
$(function() {
var params = { };
$.ajax({
url: "https://westus.api.cognitive.microsoft.com/emotion/v1.0?" + $.param(params),
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","<key>");
},
type: "POST",
data: '{"url": "<some picture's URL>"}',
}).done(function(data) {
var faceRectangle = data[0].faceRectangle;
var faceRectangleList = $('#faceRectangle');
for (var prop in faceRectangle) {
faceRectangleList.append("<li> " + prop + ": " + faceRectangle[prop] + "</li>");
}
var scores = data[0].scores;
var scoresList = $('#scores');
for(var prop in scores) {
scoresList.append("<li> " + prop + ": " + scores[prop] + "</li>")
}
}).fail(function(err) {
alert("Error: " + JSON.stringify(err));
});
});
</script>
</body>
</html>
The exact error response from the server is:
Error: {"readyState":4,"responseText":"{ \"error\": { \"code\": \"ResourceNotFound\", \"message\": \"resource not found.\" } }","status":404,"statusText":"Resource Not Found"}
obviously the server cannot answer my request. Can somebody interpret the server's error response or see a flaw in my code?
Based on the official documentation, the request URL of Emotion API should be:
https://westus.api.cognitive.microsoft.com/emotion/v1.0/recognize

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
});

JavaScript inside of PHP not working [duplicate]

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>';?>

jQuery Ajax Post - 404 error - Local server

I am trying to create an API using a local server for testing. The ROUTES are working and I can add data to the OBJ using the URL from the browser. The issue is when I try to 'POST' the data through the HTML. I am getting back a 404 error. I developing using node.js and Express. What am I doing wrong?
JS on the server side
app.get('/add/:word/:score?', addWord);
//Function to request and send back the data
function addWord(request, response) {
var data = request.params;
var word = data.word;
var score = Number(data.score);
var reply;
if (!score) {
var reply = {
msg: 'Score is required'
}
response.send(reply);
} else {
words[word] = score;
// Transforms javascript object into raw data correctly idented with null, 2
var data = JSON.stringify(words, null, 2);
fs.writeFile('words.json', data, finished);
function finished(err) {
console.log('Writting');
var reply = {
word: word,
score: score,
status: 'Success'
}
response.send(reply);
}
}
}
POST method JS
$('#submit').on('click', function submitWord() {
var word = $('#fieldWord').val();
var score = $('#fieldScore').val();
$.ajax({
type: 'POST',
url: '/add/' + word + "/" + score,
success: function (newOrder) {
$list.append('<li>name: ' + newOrder.word + newOrder.score + '</li>');
},
error: function (err) {
console.log('Error saving order', err);
}
});
});
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tutorial API with node.js</title>
<script type="text/javascript" src ="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<p>
Word: <input type="text" id="fieldWord"><br/>
Score:<input type="text" id="fieldScore"><br/>
<button type="button" id ="submit">Submit</button>
<ul id="list">
</ul>
</p>
</body>
<script type="text/javascript" src="sketch.js"></script>
</html>
Thank you in advance.

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.

Categories