How get first image from all posts with ajax - javascript

I have this code which spits out all the content for the first post only. I would like it to spit out the first image from all posts.
$.ajax({url: "http://api.tumblr.com/v2/blog/sjtest1.tumblr.com/posts?api_key=mykey",
dataType: 'jsonp',
success: function(results){
console.log(results);
var postBody = results.response.posts[0].body;
$(".x").html(postBody);
}});
And this is a ajax response:
{
"meta": {
"status": 200,
"msg": "OK"
},
"response": {
"blog": { ... },
"posts": [
{
"blog_name": "citriccomics",
"id": 3507845453,
"post_url": "http:\/\/citriccomics.tumblr.com\/post\/3507845453",
"type": "text",
"date": "2011-02-25 20:27:00 GMT",
"timestamp": 1298665620,
"state": "published",
"format": "html",
"reblog_key": "b0baQtsl",
"tags": [
"tumblrize",
"milky dog",
"mini comic"
],
"note_count": 14,
"title": "Milky Dog",
"body": "<p><img src=\"http:\/\/media.tumblr.com\
/tumblr_lh6x8d7LBB1qa6gy3.jpg\"\/><a href=\"http:\/\
/citriccomics.com\/blog\/?p=487\" target=\"_blank\">TO READ
THE REST CLICK HERE<\/a><br\/>\n\nMilky Dog was inspired by
something <a href=\"http:\/\/gunadie.com\/naomi\"
target=\"_blank\">Naomi Gee<\/a> wrote on twitter, I really
liked the hash tag <a href=\"http:\/\/twitter.com\/
search?q=%23MILKYDOG\" target=\"_blank\">#milkydog<\/a>
and quickly came up with a little comic about it. You can
(and should) follow Naomi on twitter <a href=\"http:\/\
/twitter.com\/ngun\" target=\"_blank\">#ngun<\/a> I'm on
twitter as well <a href=\"http:\/\/twitter.com\
/weflewairplanes\"target=\"_blank\">#weflewairplanes<\/a>
<\/p>\n\nAlso, if you’re a Reddit user (or even if
you're not) I submitted this there, if you could up vote
it I'd be super grateful just <a href=\"http:\/\
/tinyurl.com\/5wj3tqz\" target=\"_blank\">CLICK HERE<\/a>"
},
...
],
"total_posts": 3
}
}
As you can see, images in the body are wrapped with tags.
How i get the images?

Using jQuery, see the sample code:
$(results.response.posts[0].body).find('img').first();
It is probably not the best alternative, but it should do.
If you wanna do it for multiple posts use array of images:
var img = new Array();
$.each(results.response.posts, function (ix,el){
img.push($(el.body).find('img').first());
})

try this:
$.ajax({url: "http://api.tumblr.com/v2/blog/sjtest1.tumblr.com/posts?api_key=mykey",
dataType: 'jsonp',
success: function(results){
console.log(results);
var postBody = results.response.posts[0].body;
var html = $(postBody);
var firstImage = $(postBody).find("img:first");
}});

var $ct = $('.x');
$.ajax({
url: "http://api.tumblr.com/v2/blog/sjtest1.tumblr.com/posts?api_key=mykey",
dataType: 'jsonp',
success: function (results) {
console.log(results);
$.each(results.response.posts, function (_, post) {
$(post.body).find('img:first').appendTo($ct)
})
}
});

Related

my JSON is not practical and I want to change it, how can I do so?

Problem: my JSON isn't practical and I want to change it. As you can see my JSON looks strange, but somehow it's valid JSON (checked with JSONLint). I have input fields which are in containers with their own unique id (they increment). I was wondering if it's possible to send the data inserted into the input fields together so when I fetch it, it will stay together.
how my JSON looks like right now:
{
"main_object": {
"id": "new",
"formData": {
"language": "nl_NL",
"getExerciseTitle": "ExampleForStackOverflow",
"question_takeAudio_exerciseWord[0": "ExampleForStackOverflow",
"Syllablescounter[0": "Example",
"Syllablescounter[1": "Example1",
"question_takeAudio_exerciseWord[1": "SecondExampleForStackOverflow",
"Syllablescounter[2": "Second",
"Syllablescounter[3": "Example"
}
}
}
what I am looking and hoping to achieve:
{ "main_object":
{
"id": "new",
"formData": [
{
"language": "nl_NL",
"getExerciseTitle": "ExampleForStackOverflow",
"Word": "ExampleForStackOverflow",
"Syllables":["Example", "Example1"]
},
{
"Word": "SecondExampleForStackOverflow",
"Syllables": ["Second", "Example"]
}
]
}
};
https://jsfiddle.net/StackOverflowAccount/sa2eowhh/ I have a fiddle so you can see what I mean. When you click on the green + button it adds a whole field. This is a container that has an ID, I am trying to keep everything with the same ID with each other in the JSON file, so when I fetch it to my front-end it "knows" which syllables are part of the exercise word.
I have an ajax call which I think causes my JSON file to look like what I have right now.
my ajax call:
function saveExerciseAjaxCall() {
$("#my_form").on("submit", function(event) {
event.preventDefault();
$.ajax({
url: 'saveJson.php',
type: 'POST',
data: {
id: getUrlParameter('id'),
formData: JSON.parse('{"' + decodeURI($('#my_form').serialize()).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}')
},
dataType: 'json',
}).done(function(response) {
});
});
}
Thanks!

JavaScript failing parsing JSON

I need to filter some information. The information is coming from a JSON parse. I can't make it work. What I want is that the JSON is filtered into the HTML classes. I think I'm stupid
$.ajax({
// Agenda
type: 'POST',
url: 'agendas',
data: {results: 'events'},
dataType: 'json',
cache: false,
success: function (response) {
$('.date, .country, .events').html('');
$.each(response.results, function (index, result) {
if (result.status)
$('.date').append(result.server);
$('.country').append(result.server);
$('.events').append(result.server);
});
}
});
It would be lovely if someone could help me
JSON:
{
"results": [
{
"events": {
"id": 1,
"date": "2022-05-06T00:00:00+00:00",
"description": "test",
"time": "2017-02-03T06:40:00+00:00",
"location": "NL",
"year": "2008",
"event": "Idk"
}
},
{
"events": {
"id": 2,
"date": "2019-04-05T00:00:00+00:00",
"description": "aasdasdasda",
"time": "2017-02-03T15:04:00+00:00",
"location": "asdasdasd",
"year": "0000",
"event": "asdasd"
}
}
]
}
HTML:
<div class="day">
<h2 class="date">Januari 23</h2>
<div class="country-events">
<span class="country">UK</span>
<div class="events">
<span class="event">Conference Amsterdam<br />11:00 CET</span>
<span class="event">Webinar Copenhagen<br />15:00 CET</span>
</div>
</div>
I really can't get my head around this. I know it is not the correct code, I am new to JSON and JavaScript. 4th day currently so please forgive me.
Thank you in advance
UPDATE
This is what it shows currently, the data from the json file needs to go in the specific elements
$.each(response.results, function(index, result) {
console.log(result)
$('.date').append(result.events.date);
$('.date').append('</br>');
$('.country').append(result.events.location);
$('.country').append('</br>');
$('.events').append(result.events.event);
$('.events').append('</br>');
});
is this what you want?
https://plnkr.co/edit/wCYJPXgAPII1mcW4cKw7?p=preview
check this fiddle

Cant retrieve the JSON using Ajax

My JSON:
{
"operatorname": "LUKUP",
"Schedule": {
"channel": [
{
"bouquet": "Music",
"channelgenre": "English Music",
"prepaid_price": 15
},
{
"bouquet": "News",
"channelgenre": "English News",
"prepaid_price": 7
}
]
}
}
Ajax call:
$.ajax({
type: "POST",
url: my_url,
async: false,
success: function(result){
alert(JSON.stringify(result));
message= JSON.parse(result);
alert(message.Schedule.channel.length);
}
});
My json is coming. First alert message is giving my JSON. When i parse that json, error is coming like
Uncaught SyntaxError: Unexpected token o
Location: jquery.min.js.2
I tried solving this issue. Couldnt able to figure out where it is going wrong.
Can anyone help me
Remove the comas after "prepaid_price": 15 and "prepaid_price": 7. You are also missing a closing } at the end of your JSON.
You can validate your JSON here: http://www.jsoneditoronline.org/
{
"operatorname": "LUKUP",
"Schedule": {
"channel": [
{
"bouquet": "Music",
"channelgenre": "English Music",
"prepaid_price": 15
},
{
"bouquet": "News",
"channelgenre": "English News",
"prepaid_price": 7
}
]
}
}
You can use dataType: 'json', in your AJAX-call, then your JSON will be parsed automatically and you don't need to call message = JSON.parse(result); because your result will be already an Object.
Then you can call alert(result.Schedule.channel.length); direct.
Your code would look like:
$.ajax({
type: "POST",
url: my_url,
async: false,
dataType: 'json',
success: function(result){
alert(result.Schedule.channel.length);
}
});

JSON data logging to buffer and PUT to server

I have a javascript function which generates JSON data at every certain second and then PUT it to a cloud server. Now I don't want to POST in realtime, rather I want to log this data in a buffer and say after n number of data log I will PUT to cloud. For example I want to log 50 data point in 10 second and then with timestamp I will PUT to a server
Now JSON data is passed through var fromDatan. JSON data format is
{"values": [ { "at": "2014-08-17T12:00:00Z", "value": "15" }]}
This is a single instance which is passing through say var fromDatan and being PUT in cloud.
Now I want to log say n number of JSON data. ie.
{ "values": [ { "at": "2014-08-17T12:00:00Z", "value": "15" }, { "at": "2014-08-18T12:00:00Z", "value": "20" }, { "at": "2014-08-19T12:00:00Z", "value": "25" } ] }
And then I will PUT to cloud. This is my PUT code for real time which is working:
$.ajax({
url: "https://abcd.com",
headers: {
"X-API-KEY": "23dq3dq3ddbb16a7956e6f7a",
"Content-Type": "application/json"
},
type: "PUT",
data: fromDatan,
dataType: "JSON",
success: function(fromData, status, jqXHR) {
alert(JSON.stringify(fromData));
},
error: function(jqXHR, status) {
alert(JSON.stringify(jqXHR));
}
});
So please let me know how to do this. Help me out
the code that runs every second should do:
fromDatan.values.push({
at: timestamp,
value: value
});
if (fromDatan.values.length >= 50) {
$.ajax( {
...
});
fromDatan.values = [];
};

Autocomplete in jQuery 1.4.2 jQuery UI 1.8.3

I must be thick because I cannot for the life of me get jQuery autocomplete to work. I have searched for many many examples, and it seems that most of them use an older version of jQuery. I found one fairly good example directly from the jQuery UI site: http://jqueryui.com/demos/autocomplete/#remote-jsonp So I modeled mine after that example. When I type in my input box, the little autocomplete box pops underneath the input box, but there is nothing in the autocomplete box. My data is not being loaded correctly by jQuery.
My datasource is a URL that returns JSON data. Example:
[{
"pk": 1,
"model": "concierge.location",
"fields": {
"online": false,
"link": "",
"email": "",
"address": "TBA"
}
}, {
"pk": 2,
"model": "concierge.location",
"fields": {
"online": false,
"link": "",
"email": "",
"address": "UB 2008"
}
}]
My Javascript code:
$(document).ready(function() {
$("input#id_location_address").autocomplete({
max: 10,
source: function(request, response) {
$.ajax({
url: "/concierge/autocomplete/locations/",
dataType: "json",
data: request,
success: function( data ) {
console.log( data )
response( data, function(item) {
return { label: item.address, value: item.address }
});
}
});
}
});
});
So when I console.log(data) in Firebug, it shows the object with all the data in tact. I think I am not accessing the 'address' properly in my Javascript code. See really, I just want the 'address' to pop up in the autocomplete box. How do I do this?
Thanks in advance,
Chris
I figured it out. Needed to loop through the array of json objects and then put the data into an array. I got the idea of returning an array from the defualt jQuery UI example http://jqueryui.com/demos/autocomplete/#default
$('input#id_location_address').keyup( function() {
$("input#id_location_address").autocomplete({
source: function(request, response) {
$.ajax({
url: "/concierge/autocomplete/locations/",
dataType: "json",
data: request,
success: function( data ) {
// loop through data and return as array
items = new Array();
for(item in data) items.push( data[item].fields.address );
response( items );
}
});
}
});
});
Try:
response($.map(data, function(item) {
return {
label: item.fields.address, // item.FIELDS ;)
value: item.fields.address
}
}));
Indeed, response expects an array as argument. $.map iterates over the data items and forms a new array of the return value from the passed mutator method. Once done, $.map returns the new array which will be the argument of response().
try
response($.map(data, function(item) {
return {
label: item.fields.address,
value: item.fields.address
}
}));
see the source of this demo

Categories

Resources