unable to retrieve data using getJSON - javascript

Here is my code for a page...
<html>
<head>
<script src="jquery-1.7.2.js"></script>
</head>
<body>
<script>
var url = "https://natiweb-natiweb.rhcloud.com/game.php";
$.getJSON(url,function(data){
$.each(data,function(i,user){
alert("inside json");
alert(user.appname);
});
}
);
</script>
</body>
</html>
I'm unable to get data from server.... alert does not gets popped up
it works fine if I write the script code inside a js file. but i need to dynamically populate a page, hence I need to write this query inside body.
I added alert inside the json function. even that is not getting popped. I think json isn't getting executed

Try This.....
var url = "https://natiweb-natiweb.rhcloud.com/game.php";
$.getJSON(url,function(data){
$.each(data,function(i,user){
alert(user.appname[i]);
});
}
);

try this one,Becoz you are getting array in that array your json is present
alert(user[0].appname);

Try to auto-execute your code, that's what the example says on the jquery doc.
<script>
(function() {
var url = "https://natiweb-natiweb.rhcloud.com/game.php";
$.getJSON(url,function(data){
$.each(data,function(i,user){
alert("inside json");
alert(user.appname);
});
}
);
})();
</script>

Related

Receiving returned message from web socket server to other html Page in same Tab

I am new to java. I have a task to complete.
I have two Html files
page1.html
<html>
<head>
</head>
<body>
<a onclick="send('hello');"><li>Hello</li></a>
<script>
var ws;
ws = new WebSocket("ws://localhost:8080/Test/actions");
function send(text){
ws.send(text);
}
</script>
</body>
</html>
I want to show this text in other html file (Page2.html), when it is clicked in Page1.html.
And I have to implement it using Java WebSocket Only.
First you need to implement websocket callback method in your first html
<script>
var ws;
ws = new WebSocket("ws://localhost:8080/Test/actions");
function send(text){
ws.send(text);
}
ws.on('message', function incoming(data) {
console.log(data);
url = 'http://your_html_file_path/second.html?value='+
encodeURIComponent(data);
document.location.href = url;
});
</script>
Then you can try below methods to pass your data to another page
url = 'http://your_html_file_path/second.html?value='+ encodeURIComponent(data);
document.location.href = url;
There are different ways. Please check below answers too.
Passing Variable through JavaScript from one html page to another page
Transfer data from one HTML file to another

Get text from a txt file in the url

When I go to a url like this: http ://my.url.com/file.txt, the browser shows text.
I would like a simple javscript command that does the following:
1. go to the url
3. take the text that shows up on the screen
4. store it in a variable for further processing
so something like
var url = http: //my.url.com/file.txt;
//some code here that goes to the url
//some code that takes said info and does something like:
var fileInfo = ---content of file.txt---
Note that the info I seek from the txt file is in html tags
<p>Text I need in Variable</p>
Any assistance would be greatly appreciated!
Thank you!
Use the Fetch API.
Play with it at jsfiddle.net.
var url = 'https://fiddle.jshell.net/robots.txt';
var storedText;
fetch(url)
.then(function(response) {
response.text().then(function(text) {
storedText = text;
done();
});
});
function done() {
document.getElementById('log').textContent =
"Here's what I got! \n" + storedText;
}
Here's a smaller ES6 example that separates fetching from storing and showing off the result.
fetch('https://fiddle.jshell.net/robots.txt')
.then((response) => response.text().then(yourCallback));
function yourCallback( retrievedText ) { /* . . . */ }
Adoption is already across the board.
You don't have to wait. Most people don't. You shouldn't.
GitHub provides a polyfill of those who can't upgrade.
What's better about fetch than XHR? ... Lots.
Make an AJAX call to the url. Here is using the jQuery library:
$.get( "http: //my.url.com/file.txt", function( data ) {
var text = data;
});
To extract what you need from your text string in between the paragraph tags, try regex:
var pText = text.match(/<p>([^<]+)<\/p>/)[1];
Using vanilla JS :
From the MDN doc :
function reqListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "http://www.example.org/example.txt");
oReq.send();
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
Read the doc and ndcomix SO link to go further (error checking and such)
Just use jquery. It's easy fun and extensible. Don't try bizzare uses. Be sure all the time to be compatible through all the browser. If you copy this and run it under a local or remote webserver will work like a charm.
Cheers.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({url: "test.txt", success: function(result){
$("#div1").html(result);
}});
});
});
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>
</body>
</html>

Get document information where ajax is loaded

This might not be a well formulated question, what I need is the metadata from the document where the script is begin executed not from where the data is extracted...
We have foo.com/some_title_article.html
inside of it, we have an script
<script>
(function($) {
$(document).ready(function(){
var id = data.qids;
var theTime = new Date().getTime();
$.ajax({
url: "http://foo.com/apis/shares/api.php?ids="+id+"&time="+theTime
}).done(function(data) {
$('#showData').html(data); // This will show a basic html form...
});
});
})(jQuery);
</script>
inside the file api.php I call a few other java scripts that are related to where that file is stored, as it is right now is working fine, but what I need is to get metadata from some_title_article.html into my other java scripts that is loaded via ajax... sortof like var currentURL = window.location.href; which is declared inside and a java script inside the api.php file, it load the full url as foo.com/some_title_article.html and not foo.com/apis/shares/api.php ...get it?., So, how can get information from the url where the ajax is executed and pass it to the other scripts that are called after the ajax script...
Does this help:
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<div id="showData"></div>
<script type="text/javascript">
$.ajax({
url: "http://foo.com/apis/shares/api.php?ids="+id+"&time="+theTime
}).done(function(data) {
var content = data.content;
var metadata = data.metadata;
$('#showData').html(content); // This will show a basic html form...
//Then, do whatever you want to with metadata
});
</script>
You make api.php return an object where the first key is the content and the second key is the meta data.
Otherwise, if api.php returns a string that already contains meta tags in it, you would need to parse them or add them to the dom and access them that way.
Can you share a sample of what is returned by api.php?

jQuery.getJSON() Not working

I'm trying to get JSON array from my php-script. Following is my Jquery code written in my jsp file-
$(document).ready(function()
{
alert("Inside Ready");
$.getJSON('http://example.com/root_dir/test_json.php', function(data)
{
alert(data);
});
});
but, above code showing only outer alert (i.e. alert("Inside Ready");) and not showing inner alert (i.e. alert(data); ). I'm getting expected json when I hit URL in browser. So definitly there is no problem in URL and php-script.
following is test_json.php
<?php
//Create an array
$json_response = array();
$row_array['label'] = 'A';
$row_array['value'] = $row['0 to 2'];
$row_array['color'] = '#FA2020';
array_push($json_response,$row_array);
$row_array['label'] = 'B';
$row_array['value'] = $row['2 to 3'];
$row_array['color'] = '#2BD95A';
array_push($json_response,$row_array);
$row_array['label'] = 'C';
$row_array['value'] = $row['above 3'];
$row_array['color'] = '#F7F739';
//push the values in the array
array_push($json_response,$row_array);
echo json_encode($json_response);
?>
Getting following json when I hit URL in browser-
[{"label":"A","value":"19","color":"#FA2020"},{"label":"B","value":"1","color":"#2BD95A"},{"label":"C","value":"2","color":"#F7F739"}]
I'm using jquery-1.10.2.js. Thank You..!
Try This one...Hope so it is useful to you
$(document).ready(function()
{
$.ajax({
type:'POST',
url:'http://example.com/root_dir/test_json.php',
dataType:'JSON',
data:{
},
success:function(data1){
alert(data)
},
error:function(XMLHttpRequest,textStatus,errorThrown){
alert("error");
}
});
});
Your code seems to be working fine -
I just created a test page with your code and it works -
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
alert("Inside Ready");
$.getJSON('http://<<CHANGE SERVER NAME>>/zz-test/get_json.php', function(data)
{
alert(data);
});
});
</script>
</head>
<body>
</body>
</html>
Your jQuery and PHP code looks fine so, in my experience, it is usually an error caused by calling your PHP script from a different domain (i.e.: file:///). If you can access your browser's console, you should be able to see if this is in fact the error causing the data not to be displayed.
One solution for this is to add at the top of your PHP code:header('Access-Control-Allow-Origin: *');. There are however some security concerns with this, so it should not be used permanently.
Alternatively, you could upload all your HTML, CSS, JS, jQuery, etc. code to the web server hosting the PHP file, which is a far better option.
Finally, if the option above is not possible you could use JSON-P (although this does not work with POST requests), there is a question about this at Simple jQuery, PHP and JSONP example?

Trouble getting json back

I'm using the current json structure of this:
jsonp = {"game":[
{"id":"1","gameImage":"qqq.jpg"}
],
"game":[
{"id":"2","gameImage":"hhh.jpg"}
]
}
I'm trying to just get back all the gameImage values. I tried the following but it just won't work. Any ideas?
<html>
<head></head>
<body>
<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript" language="javascript" src="gameData.json"></script>
<script>
$(document).ready(function() {
var obj = $.parseJSON(jsonp);
$.each(obj, function() {
alert(this['gameImage']);
});
});
</script>
</body>
</html>
Assuming the first code you show is in the file (incorrectly) named "gameData.json", what you're trying to parse isn't JSON (or JSONP), it's plain JavaScript.
So don't parse it.
Change
var obj = $.parseJSON(jsonp);
to
var obj = jsonp;
Notes :
JSON is a text based data interchange format. Your confusion might come from the many young developers using non-sensical expressions like "JSON object"...
You should avoid naming jsonp a variable holding a plain JavaScript object.
If you prefer to load a JSON file instead of executing a JavaScript file, then
remove the "jsonp = part to make it a real JSON file
remove the script element (as it's not JavaScript anymore)
load the JSON file using ajax
Here's how the JavaScript would be like :
$(document).ready(function() {
$.getJSON("gameData.json", function(obj){
$.each(obj, function() {
alert(this['gameImage']);
});
});
});
or, if you can afford not supporting IE8 :
$(document).ready(function() {
$.getJSON("gameData.json", function(arr){
arr.forEach(function(item){
console.log(item.gameImage); // yes, prefer the console over alert
});
});
});

Categories