I have a guardian json data feed that I want to pull into my page online.
http://content.guardianapis.com/world/cuba?format=json&show-fields=trail-text%2Cheadline&order-by=newest&api-key=c3rr449rqqebmuxua9k5mdcz
I have used this javascript but nothing seems to be working to grab the right content from the json;
$(document).ready(function() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "http://content.guardianapis.com/world/cuba?format=json&show-fields=trail-text%2Cheadline&order-by=newest&api-key=c3rr449rqqebmuxua9k5mdcz",
success: function(data) {
for (var i = 0; i < 12; i++) {
$("#cuban-news").append("<div class='guardian'><a target='_blank' href='" + webTitle + "'>Link</a></div>");
}
console.log(data);
}
});
});
This is not throwing anything in terms of errors.
Am I better using a js service like backbone or underscore?
Any help would be amazing on this.
Use
data.response.results[i].webTitle
instead of
webTitle
error was
Uncaught ReferenceError: webTitle is not defined
$(document).ready(function() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "http://content.guardianapis.com/world/cuba?format=json&show-fields=trail-text%2Cheadline&order-by=newest&api-key=c3rr449rqqebmuxua9k5mdcz",
success: function(data) {
for (var i = 0; i < data.response.results.length; i++) {
$("#cuban-news").append("<div class='guardian'><a target='_blank' href='"
+ data.response.results[i].webTitle + "'>Link</a></div>");
}
console.log(data);
}
});
});
JSFiddle
Related
I am writing a web page which reads data from an html table to be used on a MySQL query using PHP. This is a continuation of this question. I got AJAX send the data I need to use on to the PHP file with the code to update the information it sent. However, two errors have occured.
I get a message saying Error:Error: jQuery21405680291895882033_1487801210725 was not called
The data I send has a ":1" at the end of it, giving me an error.
How can I fix these two mistakes? Thank you so much!
JS code:
function getTableData(){
var array = [];
var headers = [];
$('#tablaListado th').each(function(index, item) {
headers[index] = $(item).html();
});
$('#tablaListado tr').has('td').each(function() {
var arrayItem = {};
$('td', $(this)).each(function(index, item) {
if($(this).find("textarea").length){
var costo = $(this).find('textarea').val();
arrayItem[headers[index]] = costo;
}else{
arrayItem[headers[index]] = $(item).html();
}
});
array.push(arrayItem);
});
actualizarCostos(array);
}
function actualizarCostos(array){
if(array.constructor === Array){
for(var i = 0; i < array.length ; i++){
console.log(array[i]);
console.log(JSON.stringify(array[i]));
$.ajax({
url: "http://www.page.com/Update.php",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
jsonp: false,
jsonpCallback: jsonCallback,
cache: true,
data:{ "table_data": JSON.stringify(array[i])},
success: function (data) {
console.log(data);
},
error: function(xhr,status,err){
alert("DEBUG: status"+status+" \nError:"+err);
},
traditional: true
});
}
}else{
alert("Input must be array");
}
}
function jsonCallback(data, status){
console.log(data + " " + status);
}
PHP portion:
//Added on top of the page
header('Access-Control-Allow-Origin: *');
...
function updateCosts($json){
conectar();
$array = json_decode($json, true);
echo "<script>console.log('$array');</script>";
$costo = $array["Costo"];
$sku = $array["SKU"];
$instruccion = "UPDATE articulos SET art_cost='$costo' WHERE art_SKU = '$sku'";
return ejecutarInstruccion($instruccion);
}
if(isset($_GET['table_data'])){
foreach($_GET['table_data'] as $index => $item)
{
// do something here
echo "<script>console.log('$item');</script>";
updateCosts($item);
}
// Response back - if needed
echo json_encode(array('status'=>true, 'msg'=>'Some Message'));
}
Edit:
I forgot to mention that I have tried changing 'jsonp' as 'json' on this code but I get an error saying the PHP file doesn't allow foreign data, even though I tried using header('Access-Control-Allow-Origin: *') on said file.
Your page is returning JSON, not JSONP. They aren't interchangeable. Remove the jsonp and jsonpCallback properties from the $.ajax() call, and change dataType to json:
$.ajax({
url: "http://www.page.com/Update.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: true,
data: {
table_data: JSON.stringify(array[i])
},
success: function (data) {
console.log(data);
},
error: function(xhr,status,err){
alert("DEBUG: status" + status + " \nError:" + err);
},
traditional: true
});
I'd suggest you have the following AJAX:
function actualizarCostos(array){
if(array.constructor === Array){
for(var i = 0; i < array.length ; i++){
console.log(array[i]);
console.log(JSON.stringify(array[i]));
}
$.ajax({
url: "http://www.page.com/Update.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
data:{ "table_data": JSON.stringify(array)},
success: function (data) {
console.log(data);
},
error: function(xhr,status,err){
alert("DEBUG: status"+status+" \nError:"+err);
}
});
}else{
alert("Input must be array");
}
}
Then do the For-Loop on the PHP side of the server. Maybe each variable in array has a hidden parameter to know its own index, or JSON is doing something strange like displaying the number of elements in the array (in this case 1 because you're iterating over each one)
I'm having trouble with my functions running before Ajax requests (the first to a local JSON, the second to an online resource) have finished.
In this example I want countTheMovies to run at the end after my application has got all the information it needs and populated the divs. Instead it's running straight away.
I tried to delay it using an if condition, but with no joy. I've also tried with callbacks, but think I must be getting those wrong (I'm assuming callbacks are the answer). I'm aware of timed delays, but because in the actual project I'm sourcing 250+ movies (and because a timed delay seems like cheating) I thought I'd ask here instead.
Can anyone recommend JavaScript or jQuery code to fix this problem?
$(function(){
getMovieList();
});
function getMovieList() {
$.ajax({
url: "movielist.json",
type: "GET",
dataType: "JSON",
success: function(data) {
for (var i = 0; i < data.length; i++) {
var title = data[i].title.toLowerCase().split(" ").join("+");
var year = data[i].year;
i === data.length - 1
? getMovieInfo(title, year, true)
: getMovieInfo(title, year, false);
}
}
});
}
function getMovieInfo(title, year, isLast) {
$.ajax({
url: "https://www.omdbapi.com/?t=" + title + "&y=" + year + "&plot=short&r=json",
type: "GET",
crossDomain: true,
dataType: "JSON",
success: function(val) {
if (!val.Error) {
movie = title.replace(/[^a-z0-9\s]/gi, '');
$("#app").append(
// appending info to divs
);
}
}
});
if (isLast) countTheMovies();
};
function countTheMovies() {
$("#app").append("There are " + $(".movie").length + " movies.");
}
A plunker of my failings: https://plnkr.co/edit/0mhAUtEsaOUWhkZMJqma?p=preview
You've almost got it!
The same way that you call getMovieInfo in the success callback of getMovieList, you should be calling countTheMovies in the success callback of getMovieInfo.
As Jacob said above, move the countTheMovies call inside the AJAX request.
$(function(){
getMovieList();
});
function getMovieList() {
$.ajax({
url: "movielist.json",
type: "GET",
dataType: "JSON",
success: function(data) {
for (var i = 0; i < data.length; i++) {
var title = data[i].title.toLowerCase().split(" ").join("+");
var year = data[i].year;
i === data.length - 1
? getMovieInfo(title, year, true)
: getMovieInfo(title, year, false);
}
}
});
}
function getMovieInfo(title, year, isLast) {
$.ajax({
url: "https://www.omdbapi.com/?t=" + title + "&y=" + year + "&plot=short&r=json",
type: "GET",
crossDomain: true,
dataType: "JSON",
success: function(val) {
if (!val.Error) {
movie = title.replace(/[^a-z0-9\s]/gi, '');
$("#app").append(
// appending info to divs
);
if (isLast) countTheMovies();
}
}
});
};
function countTheMovies() {
$("#app").append("There are " + $(".movie").length + " movies.");
}
Just put your countTheMovies() logic inside of the success callback of the AJAX request in getMovieInfo if you want it to run on success.
You can call your countTheMovies() function from inside the success field of your Ajax call. This way it will make the function call when you intend it to.
Try out this
$(function(){
getMovieList();
});
function getMovieList() {
$.when( $.ajax({
url: "movielist.json",
type: "GET",
dataType: "JSON",
success: function(data) {
for (var i = 0; i < data.length; i++) {
var title = data[i].title.toLowerCase().split(" ").join("+");
var year = data[i].year;
i === data.length - 1
? getMovieInfo(title, year, true)
: getMovieInfo(title, year, false);
}
}
}) ).then(function( data, textStatus, jqXHR ) {
countTheMovies();
});
}
function getMovieInfo(title, year, isLast) {
$.ajax({
url: "https://www.omdbapi.com/?t=" + title + "&y=" + year + "&plot=short&r=json",
type: "GET",
crossDomain: true,
dataType: "JSON",
success: function(val) {
if (!val.Error) {
movie = title.replace(/[^a-z0-9\s]/gi, '');
$("#app").append(
// appending info to divs
);
}
}
});
};
function countTheMovies() {
$("#app").append("There are " + $(".movie").length + " movies.");
}
I want to display data function name and function description from database and display it in div which will be created dynamically using jquery. How can I display data with dynamic div using jquery...
code for dynamically created div is:
$(document).ready(function () {
$.ajax({
type: "POST",
url: 'FunctionListing.aspx/CountFunction',
data: "{}",
contentType: 'application/json; charset=utf-8',
datatype: 'json',
success: function (result) {
//alert(result.d);
for (var i = 1; i <= result.d; i++) {
$('body').append("<div id='div" + i + "' />");
}
},
error: function (result) {
alert(result);
}
});
});
dataType :"json"
Not datatype :"json"
Hope, it'll helps you.
The function occurs before anything is clicked...
such as
When i click the name ^ fdsa, for exampmle, i need the id to pop up, but it automatically happens when the page is loaded for some reason
HTML
<ul data-role="listview" id="ccontent" data-inset="true">
</ul>
JS
function getClubs() {
$.ajax({
url: 'some url',
crossDomain: true,
type: 'post',
data: '',
success: function (data) {
$('#ccontent').empty();
var json = jQuery.parseJSON(data);
for (var i = 0; i < json.length; i++)
$('#ccontent').append('<li>' + json[i].name + '</li>');
$('#ccontent').listview('refresh');
},
});
}
function getData(id) {
$('#clubcontent').append ('<li>'+id+'</li>');
$('#clubcontent').listview('refresh');
};
I think this is what you're looking for:
$(document).on('click', '#ccontent li a', function () {
getData($(this).data('club-id'));
});
function getClubs() {
$.ajax({
url: 'some url',
crossDomain: true,
type: 'post',
data: '',
success: function (data) {
$('#ccontent').empty();
var json = jQuery.parseJSON(data);
for (var i = 0; i < json.length; i++)
$('#ccontent').append('<li>' + json[i].name + '</li>');
$('#ccontent').listview('refresh');
}
});
}
.on() is used instead of an inline onclick event. club-id is used to store the id which is used in the getData() function.
I'm doing cross-domain requests and once the first request is made I need to retrieve the ID (and do some other stuff) and then use the ID for the next request.
So far the hang-up is that the next request doesn't like the concatenation. Here's my code, and yes I know document.write should be changed to console.log() however console.log doesn't work and I was probably going to ask that question after get help with my current problem. the problem starts at the second .ajax() request.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script >
$(document).ready(function($) {
// First link out of three
var url = 'https://www.sciencebase.gov/catalo
/items?parentId=504108e5e4b07a90c5ec62d4&max=60&offset=0&format=jsonp';
$.ajax({
type: 'GET',
url: url,
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
for (var i = 36; i < 37; i++) {
document.write(json.items[i].id);
var urlId = json.items[i].id;
}
var deferUrl = 'https://www.sciencebase.gov/catalog/itemLink/" + urlId
+"?format=json&max=10';
$.ajax({
type: 'GET',
url: deferUrl,
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
// Get the next id to use for the next url
document.write(deferUrl);
$.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog
/item/4f4e4b19e4b07f02db6a7f04?format=jsonp',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
document.write(json.title);
},
error: function(e) {
console.log(e.message);
}
});
},
error: function(e) {
console.log(e.message);
}
});
},
error: function(e) {
console.log(e.message);
}
});
});
</script>
</head>
<body>
</body>
</html>
Thanks for the help
'https://www.sciencebase.gov/catalog/itemLink/" + urlId
+"?format=json&max=10';
should be
'https://www.sciencebase.gov/catalog/itemLink/' + urlId
+'?format=json&max=10';
You mix simples and doubles quotes. use 'srting' + var + 'string' or "string" + var + "string" but don't mix them
To address your concatenation issue only.. you have a mix of single and double quotes there. They should all be consistent.
ex:
var deferUrl = 'https://www.sciencebase.gov/catalog/itemLink/' + urlId + '?format=json&max=10';
I made a slight change from
for (var i = 36; i < 37; i++) {
var urlId = json.items[i].id;
}
var deferUrl = 'https://www.sciencebase.gov/catalog/itemLink/' +
urlId + '?format=jsonp&max=10';
$.ajax({
type: 'GET',
url: deferUrl,
jsonpCallback: 'getSBJSON',
contentType: 'application/json',
dataType: 'jsonp',
to
for (var i = 36; i < 37; i++) {
var urlId = json.items[i].id;
}
var deferUrl = urlId;
$.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/itemLink/' +
deferUrl + '?format=jsonp&max=10',
jsonpCallback: 'getSBJSON',
contentType: 'application/json',
dataType: 'jsonp',
and that seemed to do the trick. It didn't like having the concatenation done completely before assigning it to the url.