How do i properly format JSON in Html code - html

I am new at Html coding and my goal here is to send a measurement (pH in this case) upon clicking a button. I keep getting the error, failed to parse JSON string. I am fairly sure it has something to do with the var ItemJSON and how I have it represented. Have tried different approaches but was hoping someone could point me in the right direction. thanks in advance.
<script type="text/javascript" language="javascript">
function send()
{
var ItemJSON;
ItemJSON = '[ {"c8y_ph":{"ph":{"value":11,"unit":"na"}},"time":"2020-06-30T12:46:14.000+02:00","source":{"id":"681700"},"type":"c8y_ph"} ]';
URL = "https://myurl.com/measurement/measurements" ; //Your URL
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
xmlhttp.open("POST", URL, false);
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.setRequestHeader("Accept", "application/json");
xmlhttp.setRequestHeader('Authorization', 'Basic ' + window.btoa('username:pw')); //in prod, you should encrypt user name and password and provide encrypted keys here instead
xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
xmlhttp.send(ItemJSON);
alert(xmlhttp.responseText);
document.getElementById("div").innerHTML = xmlhttp.statusText + ":" + xmlhttp.status + "<BR><textarea rows='100' cols='100'>" + xmlhttp.responseText + "</textarea>";
}
function callbackFunction(xmlhttp)
{
//alert(xmlhttp.responseXML);
}
</script>
<html>
<body id='bod'><button type="submit" onclick="javascript:send()">call</button>
<div id='div'>
</div></body>
</html>

Related

Read a text file using XMLHttpRequest?

I have been trying to use the XMLHttpRequest to read a text file and display the text. The text file I is going to be linked externally. So far I have the following code
<!DOCTYPE html>
<html>
<body>
<h2>Using the XMLHttpRequest object</h2>
<script>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", XMLHttpRequest.txt, true);
</script>
</script>
</body>
</html>
I do not see my text file showing up and I am completely lost. I looked around on stack overflow already for answers and I did not find anything.
You haven't specified where your text file is located.
Here's an example of a working XMLHttpRequest with a remote api (not a real api endpoint, just an example url). You could adapt this to use a text file instead of json. Remember to call your function in the end! findCity( city ) for instance.
function findCity(elem) {
let xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
document.getElementById("city").value = xmlhttp.responseText;
}
else if (xmlhttp.status == 400) {
alert('There was an error 400');
}
else {
alert('something else other than 200 was returned');
}
}
};
xmlhttp.open("GET", "https://api.example.com/api/postcodes.json?pnr=" + elem.value + '&clientUrl=http://localhost', true);
xmlhttp.send();
}

Cannot GET the requested API in express.js

Here is my express app code
app.get('/books',function(req,res){
var {keyword} =req.query;
connection.query('SELECT * from books', function (error, results, fields) {
if (error) throw error;
for(let result of results){
if(result.title === keyword){
res.send(result);
}
}
});
});
and the url i am requesting is http://......../books/keyword=intro. Where intro is the user input.
What i am trying to achieve here, is from an input in HTML, to take that info and send it to my API, so it can query my DB and get what i want.
But i get a 404 error, so i guess my api is configured incorrectly.
Is there a better way to implement what i am doing?
Is the keyword=intro even the correct way to query my db.
My html is like this
<!DOCTYPE html>
</head>
<body>
<div id="data">
<input type="button" id="button" value="Click"/>
<input type="text" id="search" >
</div>
<div id="search">
</div>
<script>
document.getElementById('button').addEventListener('click',getUserInput);
function getUserInput(event){
var userInput = document.getElementById("search").value;
if(userInput !== ""){
httpGetAsync(userInput);
}
}
function httpGetAsync(searchTerm){
var theUrl = 'books?keyword=' + searchTerm;
const xhttp = new XMLHttpRequest();
xhttp.open("GET", theUrl, true); // true for asynchronous
xhttp.send(null);
xhttp.onreadystatechange = processRequest;
function processRequest() {
if (xhttp.readyState == XMLHttpRequest.DONE);
var result = JSON.parse(xhttp.response);
console.log(result);
}}
</script>
</body>
In httpGetAsync function replace
var theUrl = 'books/keyword=' + searchTerm;
with:
var theUrl = window.location + '/books/keyword=' + searchTerm;
This answer is more of a comment unless it's acceptable. The statement that I want to write is too long for a comment.
In regards to my answer is that a valid way to write your prepared statement model? How I write my SQL models are like this and it works fine. Are you receiving any errors from your SQL syntax?
Notice the brackets after the ?.
selectBooks: function(data, callback) {
let keyword = "%" + req.query + "%";
connection.query("SELECT * FROM books WHERE title LIKE ?", [keyword], callback);
}

Couldn't make ASPJAX working

I want to make a demo on how to combine ASP and AJAX. I have found snippets from http://www.aspjax.com and implemented it in my project. However, the text that should be displayed cannot be output properly.
Here's the code. Basically the same as the one in the original:
In index.asp
<script language="javascript" type="text/javascript">
/** XHConn - Simple XMLHTTP Interface - bfults#gmail.com - 2005-04-08 **
** Code licensed under Creative Commons Attribution-ShareAlike License **
** http://creativecommons.org/licenses/by-sa/2.0/ **/
function XHConn()
{
var xmlhttp, bComplete = false;
try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) { try { xmlhttp = new XMLHttpRequest(); }
catch (e) { xmlhttp = false; }}}
if (!xmlhttp) return null;
this.connect = function(sURL, sMethod, sVars, fnDone)
{
if (!xmlhttp) return false;
bComplete = false;
sMethod = sMethod.toUpperCase();
try {
if (sMethod == "GET")
{
xmlhttp.open(sMethod, sURL+"?"+sVars, true);
sVars = "";
}
else
{
xmlhttp.open(sMethod, sURL, true);
xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
xmlhttp.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && !bComplete)
{
bComplete = true;
fnDone(xmlhttp);
}};
xmlhttp.send(sVars);
}
catch(z) { return false; }
return true;
};
return this;
}
// doAJAXCall : Generic AJAX Handler, used with XHConn
// Author : Bryce Christensen (www.esonica.com)
// PageURL : the server side page we are calling
// ReqType : either POST or GET, typically POST
// PostStr : parameter passed in a query string format 'param1=foo&param2=bar'
// FunctionName : the JS function that will handle the response
var doAJAXCall = function (PageURL, ReqType, PostStr, FunctionName) {
// create the new object for doing the XMLHTTP Request
var myConn = new XHConn();
// check if the browser supports it
if (myConn) {
// XMLHTTPRequest is supported by the browser, continue with the request
myConn.connect('' + PageURL + '', '' + ReqType + '', '' + PostStr + '', FunctionName);
}
else {
// Not support by this browser, alert the user
alert("XMLHTTP not available. Try a newer/better browser, this application will not work!");
}
}
// launched from button click
var getMessage = function () {
// build up the post string when passing variables to the server side page
var PostStr = "";
// use the generic function to make the request
doAJAXCall('ajaxtest.asp', 'POST', '', showMessageResponse);
}
// The function for handling the response from the server
var showMessageResponse = function (oXML) {
// get the response text, into a variable
var response = oXML.responseText;
// update the Div to show the result from the server
document.getElementById("responseDiv").innerHTML = response;
};
</script>
<body>
<button onclick="javascript:getMessage();">Get Message From Server</button>
<div id="responseDiv">Original Text</div>
</body>
So, the code tells it to replace the Original Text in the div with the one in ajaxtest.asp
In ajaxtest.asp
<%# Language=VBScript %>
Response.Write "The Server time is " & Now()
The problem is when I click the button Get Message From Server, the stuff in ajaxtest.asp is rendered as plain text, but not in ASP. How to fix this? Is it because of the extension used is wrong?
EDIT: by plain text I mean exactly as Response.Write "The Server time is " & Now()
You probably want the contents of your ASP page to be:
<%# Language=VBScript %>
The Server time is <%=Now()%>

Parse JSON from twitter using JQUERY

I want to search a tweet from twitter, it will depend on text or hashtag. Then Show it on <div id="result"> . but i get confused because my code doesn't show the tweet.
Here is my code to read JSON from twitter search :
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#btn').click(function()
{
$.getJSON("http://search.twitter.com/search.json?q="+$('#search').val(),function(data)
{
$.each(data.results, function(i,data){
var from = data.from_user;
var tw_content = data.text;
$('#result').append("<p>User : "+from+"<br>Tweet : "+tw_content+"</p>");
});
});
});
});
</script>
<input type="text" id="search"/><input type="button" id="btn" value="cari">
<div id="result">
</div>
And while I run this, nothing happen. anyone can help me ?
I would do something like below:
$(document).ready(function() {
// Declare variables to hold twitter API url and user name
var twitter_api_url = 'http://search.twitter.com/search.json';
var twitter_user = 'behudinnystrom';
// Enable caching
$.ajaxSetup({ cache: true });
// Send JSON request
// The returned JSON object will have a property called "results" where we find
// a list of the tweets matching our request query
$.getJSON(
twitter_api_url + '?callback=?&rpp=5&q=from:' + twitter_user,
function(data) {
$.each(data.results, function(i, tweet) {
// Uncomment line below to show tweet data in Fire Bug console
// Very helpful to find out what is available in the tweet objects
//console.log(tweet);
// Before we continue we check that we got data
if(tweet.text !== undefined) {
// Calculate how many hours ago was the tweet posted
var date_tweet = new Date(tweet.created_at);
var date_now = new Date();
var date_diff = date_now - date_tweet;
var hours = Math.round(date_diff/(1000*60*60));
// Build the html string for the current tweet
var tweet_html = '<div class="tweet_text">';
tweet_html += '<a href="http://www.twitter.com/';
tweet_html += twitter_user + '/status/' + tweet.id + '">';
tweet_html += tweet.text + '<\/a><\/div>';
tweet_html += '<div class="tweet_hours">' + hours;
tweet_html += ' hours ago<\/div>';
// Append html string to tweet_container div
$('#tweet_container').append(tweet_html);
}
});
}
);
});
DEMONSTRATION
You should use jsonp to get the result, because jsonp provides a method to request data from a server in a different domain
Check this FIDDLE
I use $.ajax function with dataType: jsonp here
Check this and this for JSONP

view data and manipulate date from json using jquery or ajax

First of All i'm a beginner in jquery and ajax,
what i'm trying to do is view a sample from a whole json file in the link
http://soap.madarat.jo/Services/BusinessApplication1-DomainService1.svc/json/gettasks
and what is the possibility of editing the sample,
<!DOCTYPE HTML>
<html>
<head>
<title>json test</title>
<script src="js/json2.js" type="text/javascript"></script>
<script src="js/jquery-1.4.2.js" type="text/javascript"></script>
<script src="jtip.js" type="text/javascript"></script>
<script type="text/javascript">
function query() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://soap.madarat.jo/Services/BusinessApplication1- DomainService1.svc/json/gettasks", false);
xmlhttp.send();
var results = JSON.parse(xmlhttp.responseText);
var html = '<ol>';
alert(results.GetTasksResult);
if (results.GetTasksResult != null) {
var title;
alert(results);
for (var i = 0; i < results.GetTasksResult.RootResults.length; i++ ) {
entity = results.GetTasksResult.RootResults[i];
html += '<li>'+entity.DoctorID +' by <b>'+ entity.TaskNote +'</b></li> <br><br> ';
}
document.getElementById('results').innerHTML = html;
}
}
</script>
</head>
<body>
<button type="button" onclick="query()">jquery</button>
<div id="results" />
</body>
</html>
but nothing happens when i click the button,
why is this happening
thank you
You're not using your requester object correctly. All you did is issue a request but didn't wait for its reply. This code works asynchronously but you thought it's synchronous that's why you started processing data bfore you even got it.
Use jQuery to make an Ajax request
$.ajax({
type: "GET",
url: "http://soap.madarat.jo/Services/BusinessApplication1-DomainService1.svc/json/gettasks",
success: function(data, status, xhr){
data = data + "" == data ? $.parseJSON(data) : data;
var el = $("#results").append("<ol></ol>").children("ol").first();
if (data.GetTaskResult) {
$.each(data.GetTaskResult.RootResult, function() {
el.append("<li>" + this.DoctorID + " by <b>" + this.Tasknote + "</b></li>");
});
}
}
});
This may have bugs but it shoudl roughly do the same as your code.
Additionally, you son't need to add json2 library, and I don't know about your jtip.
Best tip I can give you
Try to first get acquainted with libraries you're using. In your case that would be jQuery. It makes it much simpler for you to write browser independent Ajax code. You haven't used even one bit of it even though it's there. Learn it, use it. It shouldn't take you a day to get through all its docs to see how to use it and why it's wise to do so.
jQuery documentation