try to get data fro json - javascript

I will try to get data from url json but nothing append
this is my code vere simple:
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#driver").click(function(event){
$.getJSON('http://api.walmartlabs.com/v1/items/54732749?format=json&apiKey=fc5cku3vruymkhxhvtenm9bk', function(jd) {
$('#stage').html('<p> Name: ' + jd.item.name + '</p>');
$('#stage').append('<p>Age : ' + jd.item.itemId+ '</p>');
$('#stage').append('<p> Sex: ' + jd.item.salePrice+ '</p>');
});
});
});
</script>
</head>
<body>
<p>Click on the button to load result.html file:</p>
<div id = "stage" style = "background-color:#cc0;">
STAGE
</div>
<input type = "button" id = "driver" value = "Load Data" />
</body>
</html>
some can know why I don't see nothing?

Your data is not contained in item object you need to access it directly.
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#driver").click(function(event){
$.getJSON('http://api.walmartlabs.com/v1/items/54732749?format=json&apiKey=fc5cku3vruymkhxhvtenm9bk', function(jd) {
$('#stage').html('<p> Name: ' + jd.name + '</p>');
$('#stage').append('<p>Age : ' + jd.itemId+ '</p>');
$('#stage').append('<p> Sex: ' + jd.salePrice+ '</p>');
});
});
});
</script>

The problem is with a cross domain Request.
You could make an ajax with dataType: "jsonp" to solve your issue.
Look here for better explanation.
note
as already pointed out, you should access to your response data without the .item, so jd.item.name become jd.name
$(document).ready(function() {
$("#driver").click(function(event) {
$.ajax({
url: 'http://api.walmartlabs.com/v1/items/54732749',
data: {
format: 'json',
apiKey: 'fc5cku3vruymkhxhvtenm9bk'
},
dataType: 'jsonp',
success: function(jd) {
console.log(jd);
$('#stage').html('<p> Name: ' + jd.name + '</p>');
$('#stage').append('<p>Age : ' + jd.itemId + '</p>');
$('#stage').append('<p> Sex: ' + jd.salePrice + '</p>');
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Click on the button to load result.html file:</p>
<div id="stage" style="background-color:#cc0;">
STAGE
</div>
<input type="button" id="driver" value="Load Data" />

Related

How display JSON output in html page using JQuery?

This is how I made API request using Python request :
mainurl = 'http://gw.api.alibaba.com/openapi/param2/2/portals.open/api.listPromotionProduct/'
api_key = '9420'
fields = '?fields=productId,productUrl,productTitle,salePrice,originalPrice,imageUrl'
payload = {
'keywords': "women",
'pageSize': "40",
'language': 'en',
'sort': 'volumeDown',
'isFreeShip': 'y',
'isFavorite': 'y',
'pageNo': "1"
}
urlx = mainurl + api_key + fields
r = requests.get(urlx, params=payload)
print(r.content)
when run it returns long JSON outputs :
{'result': {'commissionRate': '5.00%', 'originalPrice': 'US $1.21', ......}, 'currentPageNum': 0, 'errorCode': 20010000, 'totalPageNum': 0}
and this is how I try to make an API request using JQuery :
## index.html ##
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="orders">
</div>
<script src="js/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<script src="js/main.js" type="text/javascript" charset="utf-8" async defer></script>
</body>
</html>
## main.js ##
$(function (){
var $orders = $('#orders');
$.ajax({
type: 'GET',
url: 'http://gw.api.alibaba.com/openapi/param2/2/portals.open/api.listPromotionProduct/9420?fields=productUrl,originalPrice,productTitle&keywords=women',
success: function(orders){
$.each(orders, function(i, order){
$orders.append('<li> products :' + order.totalResults + '</li>');
});
}
});
});
I got this result in my browser :
products :5291514
This is the JSON output :
{"result":{"totalResults":5275965,"products":[{"productTitle":"S-XL Plus Size Tunic Autumn ...}
How can display productTitle in my html page ?
If I understood the question well, this is what you wanted to show?
$.each(orders, function(i, order){
$orders.append('<li> products :' + order.products[0].productTitle + '</li>');
});

JQuery Form Submission with enter key AJAX API

I've tried various solutions, but none are suitable for my particular case!
How can I make it so that when the user presses 'Enter' the form submits & searches.
I also want to try and remove the JavaScript from the HTML document, and move it to the ajax.js document & select it.
I'm unsure of the correct syntax to do so.
I am using rotten tomatoes API with AJAX by the way.
search.php
<form name="myform" action="" method="GET"><h3>Search for a movie here:</h3><br>
<input type="text" id="inputbox" value="">
<input type="button" id="button" value="Go!" onClick="filmlist(this.form)">
</form>
ajax.js
function filmlist (form) {
$('#films table').empty(); //removes previous search results before adding the new ones.
var apikey = "frceg2d5djxezaedgm3qq94h";
var baseUrl = "http://api.rottentomatoes.com/api/public/v1.0";
var moviesSearchUrl = baseUrl + '/movies.json?apikey=' + apikey;
var query = form.inputbox.value; //uses the value from the input box as the query search
// sends the query
$.ajax({
url: moviesSearchUrl + '&q=' + encodeURI(query),
dataType: "jsonp",
success: searchCallback
});
// receives the results
function searchCallback(data) {
$('#films table').append('Found ' + data.total + ' results for ' + query);
var movies = data.movies;
$.each(movies, function(index, movie) {
$('#films table').append('<tr><td width="70" rowspan="2"><a href="' + movie.links.alternate +
'" title="Click here to view film information for ' + movie.title + '."><img class="ajaximage" src="'
+ movie.posters.thumbnail + '" /></a></td><td class="ajaxfilmlisttitle"><h3><a href="' + movie.links.alternate +
'" title="Click here to view film information for ' + movie.title + '.">' + movie.title + '</a></h3>Release year: '
+ movie.year + '</td></tr><tr><td class="ajaxfilmlistinfo">Audience Score: ' + movie.ratings.audience_score +
'%<br>' + 'Cinema Release Date: ' + movie.release_dates.theater +
'<br>Runtime: ' + movie.runtime + ' minutes</td></tr>');
});
}
}
$("form").submit(function(){
$.ajax({
url: moviesSearchUrl + '&q=' + encodeURI(query),
dataType: "jsonp",
success: searchCallback
});
return false;
});
or you can just return false at the end of your filmlist function.
You can detect an enter keypress in the #inputbox element with the following jQuery code:
$('#inputbox').keyup(function(e)
{
if(e.keyCode == 13)
{
//do your stuff
}
});
You can also use $('#inputbox').change() to directly load movies when the user is typing.
Do not forget that some old or mobile browser do not have JavaScript support. Always build an server side solution as fallback.

OpenWeather API - Pulling JSON data out

I'm writing a little JavaScript to pull information from JSON that contains name, longitude, latitude and openweather API call. What I need is to get the API information out of the API call into the HTML page so you can get the weather forecast for each information. I have the two elements working separately but can't work out how to get them working together.
Help please? :-)
Sample API Weather from d.weather
api.openweathermap.org/data/2.5/forecase?lat=50.8609&lon=-0.08014&&units=metric
HTML page for pulling the openweather JSON data
<html>
<head>
<title>Weather</title>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-1.7.min.js" ></script>
<script src="http://code.jquery.com/ui/1.7.0/jquery-ui.js" ></script>
<script>
function getWeather(callback) {
var weather = 'http://api.openweathermap.org/data/2.5/forecast?lat=51.5072&lon=0.1275&units=metric';
$.ajax({
dataType: "jsonp",
url: weather,
success: callback
});
}
// get data:
getWeather(function (data) {
console.log('weather data received');
console.log(data.list[0].weather[0].description);
console.log(data.list[0].weather[0].main);
});
getWeather(function (data) {
document.write('weather data received');
document.write('<br>');
document.write(data.list[0].weather[0].description);
document.write('<br>');
document.write(data.list[0].weather[0].main);
document.write('<br>');
document.write(data.list[0].main.temp);
document.write('<br>');
document.write(data.list[0].main[0].dt_txt);
document.write('<br>');
});
</script>
</body>
</html>
Html page for pulling the JSON data
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<!-- Javascript -->
<script type="text/javascript">
function loadUrl(newLocation){
window.location = newLocation;
return false;
}
</script>
<script type="text/javascript">
$(document).ready(function (){
$("#btn382").click(function(){
/* set no cache */
$.ajaxSetup({ cache: false });
$.getJSON("weather.json", function(data){
var html = [];
/* loop through array */
$.each(data, function(index, d){
html.push("Team : ", d.Teams, ", ",
"Long : ", d.Long, ", ",
"Lat : ", d.Lat, ", ",
"Weather : ", d.Weather, "<br>");
});
$("#div381").html(html.join('')).css("background-color", "orange");
}).error(function(jqXHR, textStatus, errorThrown){ /* assign handler */
/* alert(jqXHR.responseText) */
alert("error occurred!");
});
});
});
</script>
<!-- HTML -->
<a name="#ajax-getjson-example"></a>
<div id="example-section38">
<div>Football weather</div>
<div id="div381"></div>
<button id="btn382" type="button">Team location</button>
</div>
weather.json
{
"Teams":"Wycombe Wanderers",
"Long":-0.800299,
"Lat":51.6306,
"Weather":" api.openweathermap.org/data/2.5/weather?lat=51.6306&lon=-0.800299&mode=html"
},
{
"Teams":"Livingston",
"Long":-3.52207,
"Lat":55.8864,
"Weather":" api.openweathermap.org/data/2.5/weather?lat=55.8864&lon=-3.52207&mode=html"
},
{
"Teams":"Brighton and Hove Albion",
"Long":-0.08014,
"Lat":50.8609,
"Weather":" api.openweathermap.org/data/2.5/weather?lat=50.8609&lon=-0.08014&mode=html"
},
I have the basics that should help you on your way. It's a mashup of your two pages.
First I amended your getWeather function to call for the weather rather than the forecast. It accepts a city parameter and appends that parameter to the data before the callback is called.
function getWeather(city, callback) {
var url = 'http://api.openweathermap.org/data/2.5/weather';
$.ajax({
dataType: "jsonp",
url: url,
jsonCallback: 'jsonp',
data: { q: city },
cache: false,
success: function (data) {
data.city = city;
callback(data);
}
});
}
Here, in lieu of your teams JSON I made one up in the form of a JS object, with Arsenal and Liverpool and their corresponding cities as the data. The function loops over the object, extracts the city name and passes it to getWeather. The data is returned and appended to the div.
$(document).ready(function () {
$("#btn382").click(function () {
var teams = {
arsenal: { city: 'london' },
liverpool: { city: 'liverpool' }
};
for (var team in teams) {
var city = teams[team].city;
getWeather(city, function(data) {
var html = [];
html.push('<div>')
html.push('City: ', data.city, ', ');
html.push('Lat: ', data.coord.lat, ', ');
html.push('Lon: ', data.coord.lon, ', ');
html.push('Weather: ', data.weather[0].description);
html.push('</div>')
$("#div381").append(html.join('')).css("background-color", "orange");
});
}
});
});
Hopefully this will give you a few ideas about how to tackle this project.
See it working here.
I have made a complete example. For me this worked:
HTML file:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<meta charset="utf-8">
<title>jQuery Ajax</title>
<link rel="stylesheet" href="css/ajx-json-styles.css">
<script>
function displayParsedData(data){
/* Working with the 'data' object (not string) here, now we can access the different properties available.*/
text = '<b>Name: </b>' + data.list[0].name + '<br/>';
text += '<b>message: </b>' + data.message + '<br/>';
text += '<b>Current Temperature: </b>' + data.list[0].main.temp + ' F<br/>';
text += '<b>Weather Conditions: </b>' + data.list[0].weather[0].description + '<br/>';
$('#parsed_json').append(text);
}
</script>
<script>
function test1() {
getWeather(function (data) {
$("#raw_json").html('<h2>callback</h2><pre>' + JSON.stringify(data, null, 2) + '</pre>');
displayParsedData(data);
});
}
function getWeather(callback) {
var weather = 'http://openweathermap.org/data/2.1/find/city?lat=8.2924495&lon=-62.7373258';
$.ajax({
dataType: "jsonp",
url: weather,
success: callback
});
}
</script>
<script>
function test2() {
$.ajax({
url: 'http://openweathermap.org/data/2.1/find/city?lat=8.2924495&lon=-62.7373258',
type: 'GET',
dataType:"jsonp",
success: function(data) {
$("#raw_json").html('<h2>$.ajax</h2><pre>' + JSON.stringify(data, null, 2) + '</pre>');
displayParsedData(data);
},
error: function(jqXHR, textStatus, error) {
alert( "error: " + jqXHR.responseText);
}
});
}
</script>
<script>
function test3() {
$.getJSON('http://openweathermap.org/data/2.1/find/city?lat=8.2924495&lon=-62.7373258&callback=?', function(data) {
$("#raw_json").html('<h2>getJSON</h2><pre>' + JSON.stringify(data, null, 2) + '</pre>');
displayParsedData(data);
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
});
}
/*$.getJSON('http://openweathermap.org/data/2.1/find/city?lat=13.3428&lon=-6.2661&cnt=10&callback=?', function(data) { console.log(data); });*/
</script>
<script>
$(document).ready(function (){
$("#btn382").click(function(){
/* set no cache */
$.ajaxSetup({ cache: false });
$.getJSON("weather.json", function(data){
for (var team in data) {
var html = [];
html = '<div class="item"><b>Team: </b>' + data[team].Teams + '<br/>';
html += '<b>Lat: </b>' +data[team].Lat + '<br/>';
html += '<b>Lon: </b>' + data[team].Lon + '<br/>';
html += '<b>Weather: </b>' + data[team].Weather + '<br/></div>';
$("#div381").append(html);
}
})
.error(function(jqXHR, textStatus, errorThrown){ /* assign handler */
/* alert(jqXHR.responseText) */
alert("error occurred!");
});
});
});
</script>
</head>
<body>
<div id="example-section38">
<div>Otra fuente</div>
<div id="div381"></div>
<button id="btn382" type="button">Team location</button>
</div>
<div id="raw_json"></div>
<div id="parsed_json"></div>
<button onclick="test1();">callback</button>
<button onclick="test2();">$.ajax</button>
<button onclick="test3();">getJSON</button>
</body>
</html>
weather.json
[
{
"Teams":"Wycombe Wanderers",
"Lon":-0.800299,
"Lat":51.6306,
"Weather":" api.openweathermap.org/data/2.5/weather?lat=51.6306&lon=-0.800299&mode=html"
},
{
"Teams":"Livingston",
"Lon":-3.52207,
"Lat":55.8864,
"Weather":" api.openweathermap.org/data/2.5/weather?lat=55.8864&lon=-3.52207&mode=html"
},
{
"Teams":"Brighton and Hove Albion",
"Lon":-0.08014,
"Lat":50.8609,
"Weather":" api.openweathermap.org/data/2.5/weather?lat=50.8609&lon=-0.08014&mode=html"
}
]
ajx-json-styles.css
#raw_json {
border:1px solid #333;
background-color:#ccc;
padding: 2em;
word-wrap: break-word;
margin-bottom: 2em;
width: 40%;
float: left;
}
#parsed_json {
padding:2em;
border: 1px solid blue;
width: 40%;
float: right;
}
h2 {
margin:0;
padding:0;
}
.item{
padding-bottom: 0.25em;
padding-top: 0.25em;
background-color: #E9BB18;
border: 1px solid white;
}
why don't you use xml instead of json it's easy to parse, i use it in my website weathercase , try api provider yr.no

Dynamic form on website

Hi I'm trying to show a form when the edit button is pressed and then once the save button for the form is pressed I'd like to edit my database and show the new information. I need to do this without refreshing the page as well. I'm new to jquery but below is what I've written so far, however, the event.preventDefault(); function isn't working for some reason and the forms action is run. Any help as to why my code is failing would be greatly appreciated thanks!
<!doctype html>
<html lang="en">
<head>
<!-- Irrelevant scripts from the site go here -->
</head>
<body>
<!-- Lots of other code from the site is here -->
<div id="jqueryFunction"></div>
<script text="text/javascript">
function checkEdit(ID){
//Check the fields make sure they're not empty
return true;
}
</script>
<script text="text/javascript">
function editV(ID, titleOld, descOld){
document.getElementById("divForm" + ID).innerHTML =
"<form name=\"editDiv" + ID + "\" id=\"editDiv" + ID + "\" onsubmit=\"return checkEdit(" + ID + ");\" action=\"editvid.php\" method=\"POST\">" +
"<input type=\"hidden\" name=\"divID\" id=\"divID\" value=\"" + ID + "\"/>" +
"<input type=\"text\" name=\"titleNew" + ID + "\" id=\"titleNew" + ID + "\" value=\"" + titleOld + "\"/><br>" +
"<textarea name=\"descNew" + ID + "\" id=\"descNew" + ID + "\">" + descOld + "</textarea><br>" +
"<input type=\"submit\" value=\"Save\" class=\"alt_btn\">" +
"</form>";
document.getElementById("jqueryFunction").innerHTML =
"<script src=\"js/jquery-1.5.2.min.js\" type=\"text/javascript\"><\/script>" +
"<script>" +
"$(function(){" +
"$('form[name=\"editDiv" + ID + "\"]').on('submit', function(event){" +
"event.preventDefault();" +
"var form = this;" +
"$.ajax({" +
"url: $(form).attr('action')," +
"type: \"POST\"," +
"data: {divID:$(form.divID).val(), titleN:$(form.titleNew).val(), descN:$(form.descNew).val()}," +
"success: function (response) {" +
"alert('response');" +
"}" +
"});" +
"});" +
"});" +
"<\/script>";
}
</script>
</body>
There are many cleaner solutions.
I just would hide the form and then display it by clicking edit.
Here is an example with fetching your parents id.
<!DOCTYPE HTML>
<html>
<head>
<title>Test</title>
<style>
.editForm {
display:none;
}
</style>
<script>
</script>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('.edit').click(function() {
$('.editForm').fadeIn();
});
$('a.submit').click(function() {
// get parents id
var parentId = $(this).parent().parent().parent().attr('id');
$.ajax({
type: "POST",
url: "some.php",
data: { divId: parentId, aName: $('.aName').val() }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
</script>
<body>
<div id="anId">
<a class="edit">edit</a>
<form class="editForm">
<div>
<input type="text" class="aName" />
Submit
</div>
</form>
</div>
</body>
</html>

Long polling will keep the page loading (javascript issue)

I've build a chat script with long-polling but I don't understand why it keeps loading. The long-polling should start after submitting a text but it looks like it starts automatically.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Helpdesk Longpolling Test</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<link rel="stylesheet" href="css/style.css" type="text/css" />
<script type="text/javascript" charset="utf-8">
var timestamp = null;
var name = "Guest: ";
function sendReply(message, myAsync) {
$.ajax({
type: "GET",
url: "putData.php?text=" + message,
async: myAsync,
cache: false,
success: function(data) {
var json=eval('('+data +')');
//alert(json["code"]);
if (json["code"] == "500") {
$('div#chatbox').append('Error<br />');
} else if (json["code"] == "200") {
$("#textToChat").val("");
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('div#chatbox').append('<p>Error: ' + textStatus + ' (' + errorThrown + ')</p>');
//alert("error: " + textStatus + " ("+errorThrown + ")");
}
});
}
function waitForMsg() {
$.ajax({
type: "GET",
url: "getData.php?timestamp=" + timestamp,
async: true,
cache: false,
success: function(data) {
var json=eval('('+data +')');
if (json["msg"] != "") {
//alert(json["msg"]);
$('div#chatbox').append(' ' + json["msg"] + '<br />');
}
timestamp = json["timestamp"];
setTimeout('waitForMsg()', 1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('div#chatbox').append('<p>Error: ' + textStatus + ' (' + errorThrown + ')</p>');
alert("error: " + textStatus + " ("+errorThrown + ")");
//setTimeout('waitForMsg()', 1000);
}
});
}
$(window).load(function() {
$('#sendMessage').submit(function() {
sendReply(name+" is connected.", true);
setTimeout(function() {
waitForMsg();
openConnection = true;
}, 500);
var text = $("#textToChat").val();
sendReply(name+": "+text, true);
return false;
});
});
$(window).bind('beforeunload', function(){
sendReply(name+" has left the conversation.", false);
});
</script>
</head>
<body>
<div id="chatbox">
<h3>Live Support!</h3>
</div>
<form method="get" id="sendMessage">
<input id="textToChat" name="text" type="text" value="Type your question..." size="63" />
<input name="submitmsg" type="submit" id="submitmsg" value="Verzenden" />
</form>
<input type="button" id="actie" name="actie" value="Actie_in_CMS" />
</body>
</html>
Someone who has an idea? I guess I've made a stupid mistake but can't figure it out myself after 2 days trying to debug the script. After the page is loaded , the script is working fine.

Categories

Resources