view data and manipulate date from json using jquery or ajax - json

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

Related

Retrieving response of POST (with custom header in HTML) request and use it as variable in front-end page

I need to write a web-page in which I embed a chart.
The page I wrote is the following:
<html>
<head>
<script language="JavaScript" type="text/javascript">
function makeFrame() {
ChartToken = "XXXXXXX";
ifrm = document.createElement("IFRAME");
ifrm.setAttribute("src", "https://url.com/charts/"+ ChartToken +"#/embedded");
ifrm.style.width = 640+"px";
ifrm.style.height = 480+"px";
document.body.appendChild(ifrm);
}
</script>
</head>
<body>
<p>GO! </p>
</body>
</html>
If I manually set ChartToken with the correct string this is working. However, the value of ChartToken should be retrieved via a POST request.
I have been told that the POST request should go in the back-end server. However, I don't even know how to write in the back-end server and how to write the POST request. Also, I'm not sure if I really need to write in the back-end or I could simply make the POST request in the front-end page above.
At the moment, in order to obtain the ChartToken I use Advanced REST client. I fill in the Advanced REST client fields the values for the url:
https://url.com/1/embeddedCharts
for the RAW headers:
Authorization: Token YYYYYYYY
Content-Type: application/json
and for the RAW payload:
{"apiToken": "YYYYYYYY",
"chartId": "ZZZZZZZ"}
(notice that the Athorization: Token and the apiToken are the same) and I receive as response:
{
"token": "KKKKKKK"
}
This is the value that I put in the ChartToken in order to be able to embed the chart. However, this value can only be used once and at each page load I need to obtain a new token to put in ChartToken.
Therefore I wrote a page to retrieve the token (that I wanted to use to send the value of the token to ChartToken):
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Title Goes Here</title>
</head>
<body>
<p>This is my web page</p>
<form action="https://url.com/1/embeddedCharts" method="post" enctype="application/json">
<input name="apiToken" value="YYYYYYYY">
<input name="chartId" value="ZZZZZZZ">
<button>Send my data</button>
</form>
</body>
</html>
However, this page doesn't work. Maybe because I don't send the RAW header:
Authorization: Token YYYYYYYY
as I do in the Advanced REST client? I have read in some other forum that this is not possible in html, because I cannot define a custom header. Is this true?
Or maybe because
enctype="application/json"
doesn't actually replace
Content-Type: application/json
that I use the Advance REST client?
Or maybe because I don't write this page in the back-end server? How would I do that?
So, the solution to my problem would be to know:
1) How to write the POST request to obtain the token for the chart.
2) Where to write the request, if in the back-end.
3) How to pass the value to my front-end page, essentially to ChartToken.
Please, consider that I can only write a bit of html for front-end pages and I don't know much about web architectures. The easiest for me would be to have a full example with all the indications.
Thanks a lot.
I found a way to make the POST request from a jquery script within the html front-end page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script>
var reportId = "XXXXXXXXXXXX", // Required
apiToken = "YYYYYYYYYY", // Required
containerId = "embeddedReport", // Required
documentId = "", // Optional
dateRange = {"mode": "LAST_7_DAYS"}, // Optional
slicer = {
}, // Optional
// Report size
width = 1000,
height = 400,
// leave that variable NULL
ReportToken = null;
function getReportTokenJS(apiToken, reportId, width, height, containerId) {
var payLoadData = createPayLoadData();
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState != 4) {
}
if (xmlhttp.readyState == 4 && xmlhttp.status >= 200 && xmlhttp.status < 300) {
var data = JSON.parse(xmlhttp.responseText);
ReportToken = data.token;
var iframe = document.createElement('iframe');
iframe.style.width = width + 'px';
iframe.style.height = height + 'px';
iframe.src = 'https://app.somepage.com/reports/' + ReportToken;
document.getElementById(containerId).appendChild(iframe);
}
}
xmlhttp.open("POST", "https://app.somepage.com/1/embeddedReports", true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.send(JSON.stringify(payLoadData));
};
function createPayLoadData() {
if (apiToken == "" || apiToken == null || reportId == "" || reportId == null) {
console.log("ERROR: apiToken Or reportId is missing");
return false;
} else {
var payLoadData = {};
payLoadData.apiToken = apiToken;
payLoadData.reportId = reportId;
}
if (documentId != "" && documentId != null) {
payLoadData.documentId = documentId;
}
if (Object.keys(dateRange).length > 0) {
payLoadData.dateRange = dateRange;
}
if (Object.keys(slicer).length > 0) {
payLoadData.slicer = slicer;
}
return payLoadData;
};
</script>
</head>
<body>
<button type="button" onclick="getReportTokenJS(apiToken, reportId, width, height, containerId);">generate embedded report</button>
<div id="embeddedReport"></div>
</body>
</html>
Now, I would need to know how to pass values for reportId and apiToken to the jquery script variables. Please, consider that I found this example somewhere, so I don't really know how to program in jquery. A full working example modifying the code I provide here would be to only way to show me how to do.

HTML5 Local save/load

Im trying to follow tutorial from this site " Link to Tutorial " to make a idle game.
It shows easy way to make simple local save function, but I can't make it work for some reason. He tells to make a function this and that, but doesn't show how it should look like.
I searched google and saw many different ways, I got some to work but not fully and they weren't simple enough for my lack of knowledge in HTML.
Any help is welcome and appreciated :) thanks in advance.
function save(){
var save = {
cookies: cookies,
cursors: cursors
}
localStorage.setItem("save",JSON.stringify(save));
};
function load(){
var savegame = JSON.parse(localStorage.getItem("save"));
if (typeof savegame.cookies !== "undefined") cookies = savegame.cookies;
};
var cookies = 0;
function cookieClick(number) {
cookies = cookies + number;
document.getElementById("cookies").innerHTML = cookies;
};
var cursors = 0;
function buyCursor() {
var cursorCost = Math.floor(10 * Math.pow(1.1, cursors)); //works out the cost of this cursor
if (cookies >= cursorCost) { //checks that the player can afford the cursor
cursors = cursors + 1; //increases number of cursors
cookies = cookies - cursorCost; //removes the cookies spent
document.getElementById('cursors').innerHTML = cursors; //updates the number of cursors for the user
document.getElementById('cookies').innerHTML = cookies; //updates the number of cookies for the user
};
var nextCost = Math.floor(10 * Math.pow(1.1, cursors)); //works out the cost of the next cursor
document.getElementById('cursorCost').innerHTML = nextCost; //updates the cursor cost for the user
};
function save() {
var save = {
cookies: cookies,
cursors: cursors
}
localStorage.setItem("save", JSON.stringify(save));
};
function load() {
var savegame = JSON.parse(localStorage.getItem("save"));
if (typeof savegame.cookies !== "undefined") cookies = savegame.cookies;
}
window.setInterval(function() {
cookieClick(cursors);
}, 1000);
<html>
<head>
<link rel="stylesheet" type="text/css" href="interface.css" />
</head>
<body>
<button onclick="cookieClick(1)">Click Me!</button>
<br />Cookies: <span id="cookies">0</span>
<br />
<button onclick="buyCursor()">Buy Cursor</button>
<br />Cursors: <span id="cursors">0</span>
<br />Cursor Cost: <span id="cursorCost">10</span>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
Your browser may not support localstorage.
You can check broswer's localstorage support using Modernizr.
Read about it here: http://diveintohtml5.info/detect.html
Also make sure, that you are calling save() method in your code (I don't see it in your code)

How to Parse RSS Data with JSON

As a noob, I'm trying to parse a weather.com RSS feed for display on my site. The code below successfully retrieves the data and displays it as an alert. My question is how to take this further and parse the resulting feed instead of just displaying it? The goal is to take parts of the response and embed it into the HTML on the page. For example, if I wanted to output a table that has a row with the current temperature, what would be the syntax?
<script>
function parseRSS(url, callback) {
$.ajax({
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
success: function(data) {
callback(data.responseData.feed);
}
});
}
parseRSS('http://rss.weather.com/weather/rss/local/USAK0012?cm_ven=LWO&cm_cat=rss&par=LWO_rss',
function(json)
{
alert("Result: " + JSON.stringify(json));
});
</script>
If it helps anyone, here is how I ended up doing it. I went with the feed from accuweather.com, instead of weather.com, just because I happened to get it working first.
1) Obtained the value of the feed "title" field, which contained the current weather values that I needed.
var weatherFeed = json;
var currentConditions = weatherFeed.entries[0].title;
2) Extracted the specific elements, for example currentTemperature:
var firstColonIndex = currentConditions.indexOf(":");
var secondColonIndex = currentConditions.indexOf(":", firstColonIndex + 1);
var currentTemperature = currentConditions.substring(secondColonIndex + 1);
3) Built the HTML using jQuery and embedded the extracted weather values, then put the whole thing within a Div element on my page:
<div class="tile-content" id="MyCityWeather">
<script type="text/javascript">
var weatherElement = "#MyCityWeather";
var temperatureElement = $("<h2/>",
{
style: "margin-left: 25px!important; font-size: 46px!important;"
});
temperatureElement.append(currentTemperature);
temperatureElement.appendTo(weatherElement);
</script>
</div>

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

Playing WebAudio API automatically in iOS 6

I was performing some tests with the WebAudio API in iOS6. It seems that when you click on a button, the AudioBufferSourceNode will be created correctly and connected to the Contexts destination.
I was simply wondering if there was any way of playing a sound automatically when a page is loaded, as iOS6 devices seem to build the SourceNode correctly, but no sound comes out.
I have posted my code below:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML 5 WebAudio API Tests</title>
<script type="text/javascript">
var audioContext,
audioBuffer;
function init() {
try {
audioContext = new webkitAudioContext();
initBuffer('resources/dogBarking.mp3');
} catch(e) {
console.error('webkitAudioContext is not supported in this browser');
}
}
function initBuffer(desiredUrl) {
var url = desiredUrl || '';
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "arraybuffer";
request.onload = function() {
audioContext.decodeAudioData(request.response, function(buffer) {
audioBuffer = buffer;
}, onError);
}
request.send();
}
function playSound(startTime, endTime) {
var audioSource = audioContext.createBufferSource();
audioSource.buffer = audioBuffer;
audioSource.connect(audioContext.destination);
audioSource.noteOn(0);
audioSource.noteOff(10);
}
</script>
</head>
<body onload="init()">
<script type="text/javascript">
(function() {
var buttonNode = document.createElement('input');
buttonNode.setAttribute('type', 'button');
buttonNode.setAttribute('name', 'playButton');
buttonNode.setAttribute('onclick', 'playSound(0, 1)')
buttonNode.setAttribute('value', 'playSound()');
document.body.appendChild(buttonNode);
document.write('<a id="test" onclick="playSound(0, 2)">hello</a>');
var testLink = document.getElementById('test');
var dispatch = document.createEvent('HTMLEvents');
dispatch.initEvent("click", true, true);
testLink.dispatchEvent(dispatch);
}());
</script>
</body>
</html>
I hope this makes sense.
Kind regards,
Jamie.
This question is very similar to No sound on iOS 6 Web Audio API . WebAudio API needs user input to be initialized and after first sound plays in this way WebAudioAPI works greatly without any actions needed during current session.
You can initialize API by adding listener to first window touchstart event, like this:
w.addEventListener('touchstart', myFunctionThatPlaysAnyWebAudioSound);