For-in Loop through Tumblr posts with ajax - ajax

The expectation is that $(".post-title").append(postTitle); will return the title of that post, as will postBody. Yet when I console.log these variables > undefined is returned.
$.ajax({
url: "http://api.tumblr.com/v2/blog/ohc-gallery.tumblr.com/posts?api_key=***",
dataType: 'jsonp',
success: function(res){
var postings = res.response.posts;
var postTitle = "";
var postBody = "";
$(".post-title").append(postTitle);
$(".post-body").append(postBody);
for (var i in postings){
postTitle = postings[i].title;
postBody = postings[i].body;
}
console.log("postBody: " + postBody);
}
});
Am I missing something basic regarding Javascript closures... I really don't know right now. I simply want to loop through created post data for later display.
Github JS code- https://github.com/mrcn/ohc/blob/master/js/tumblr.js
Github HTML code- https://github.com/mrcn/ohc/blob/master/index-posting.html#L82-L89
I got it. The problem was with how I intended to display this information on the website, and I had to alter the code accordingly. The idea was to display paired blog post titles and entries. The problem was all titles were appearing together, and all bodies were appearing together- not paired off respectively.
The updated code is more along the lines of --
Javascript --
//use $.each() or Array.forEach
$.each(postings, function (i, post) {
$(".post ").append("<h3>" + post.title + "</h3>" + post.body + "<br><br>");
});
}
});
HTML --
<div class="post-wrap"><!--post-wrap-->
<div class="post">
</div>
</div><!--post-wrap-->

The for..in is used to iterate over an object... posts is an array for you can use the normal for (var i=0;i<x;i++) loop or any other iteration methods like $.each() or Array.forEach()
$.ajax({
url: 'http://api.tumblr.com/v2/blog/ohc-gallery.tumblr.com/posts?api_key=***',
dataType: 'jsonp',
success: function (res) {
var postings = res.response.posts;
var postTitle = '';
var postBody = '';
//use $.each() or Array.forEach
$.each(postings, function (i, post) {
$(".post-title ").append(post.title);
$(".post-body ").append(post.body);
})
}
});

Not every post type supports title or body. You currently have three posts, two text and one photo. The photo post type only support photos and caption, which is causing the undefined.
Check the API for more details: https://www.tumblr.com/docs/en/api/v2

Related

Shopify: How can I render the recommended products?

I am trying to use Shopify Ajax API to get recommended products inside the cart. I am able to get the recommended product's json but not the section rendering.
The script (note section_id):
jQuery.getJSON('/cart.js', function(cart) {
// first recommendation
jQuery.getJSON("/recommendations/products.json?product_id=" + cart.items[0].product_id + "&limit=6&section_id=recommended_first", function(
response
) {
var recommendedProducts = response.products;
}
});
})
The HTML:
<div id="recommended_first" class="upsell_product">
</div>
I get some messages in the console:
Error: ShopifyAnalytics.meta.page.pageType is empty: undefined
Fallback logic initiated
What am I missing? I didn't find any examples in the Shopify doc.
Thanks a lot!
Your code will not work because you have an extra } on line 7. Assuming the cart request returns valid data, the following code should work (also a good idea to check if the cart request returns any items before using the cart.items variable):
jQuery.getJSON('/cart.js', function(cart) {
jQuery.getJSON("/recommendations/products.json?product_id=" + cart?.items?[0]?.product_id + "&limit=6&section_id=recommended_first", function(response) {
var recommendedProducts = response.products;
var recommendedProductsHTML = "";
for (i = 0; i < recommendedProducts.length; i++) {
recommendedProductsHTML += `<div>${recommendedProducts[i].title}</div>`;
}
$("#recommended_first").html(recommendedProductsHTML);
});
});

Like System with AJAX and Laravel

I'm trying to get it so people can like a post on a button click which will upload a row to the likes table and then if they press the button again it will delete the record and unlike the post. The problem i am having is that i have rehashed a tutorial which included a boolean for a like and dislike, i do not have the boolean and have tried to reconfigure the code to accommodate that. The problem i'm having is that after i've sorted out the unauthorized errors the button now appears to be dead and doesn't do anything. I presume this mean that their is an issue with the laravel code for this. Can anyone see why the button isnt responding and point me in the direction of how i like(post) to database, check for a like and delete if the button is pressed and the row exists?
Here is what i have so far:
Table:
likes: id, post_id, user_id, timestamps()
HTML:
<a class="btn btn-not-liked like">Liked?</a>
AJAX JS:
var postId = 0;
var token = '{{ Session::token() }}';
var urlLiKes = '{{ route('likes') }}';
$('.like').on('click', function(event){
event.preventDefault();
postId = event.target.parentNode.parentNode.dataset['postid'];
var isVisit = event.target.previousElementSibling == null;
$.ajax({
method: 'POST',
url: urlLikes,
data: {isLikes: isLikes, postId: postId, _token: token}
})
.done(function() {
});
});
PHP:
$post_id = $request['postId'];
$is_visit = $request['isLike'] === 'true';
$post = Post::find($post_id);
if (!$post) {
return null;
}
$liked = Auth::user()->likes()->where('post_id', $post_id)->first();
if($liked == $is_like){
$liked->delete();
return null;
}
else{
$liked = new Like();
}
$liked->user_id = Auth::user();
$liked->post_id = $post->id;
$liked->save();
return null;
}
Please help to find the issue in this code or point me in the direction of a like system without the boolean and just a simple like(post)/unlike(delete) with Laravel and AJAX.
I think the problem is that you are performing a Boolean / Object compassion.
I suggest rewriting your if condition in:
if( !is_null($liked)){...}

How can i append partial view result in to div?

I have a div id="comments"
in this i am displaying 10 comments at a time.
when user want to view next comments, i have provided one button that will collect next 10 comments. for this next comment i have created partial view to display remaining 10 comments into another div morecomments.
My problem is when i am displaying next 10 comments its showing me all 20 comments but whole comments div is getting refreshed, how to prevent loading whole comment div.
My code is here:
<div id="comments">
// Display Comments
<div id="moreButton">
<input type="submit" id="more" class="morerecords" value="More Post" />
</div>
</div>
<div id="morecomments">
</div>
Jquery::
$('.morerecords').livequery("click", function (e) {
// alert("Showing more records...");
var next = 10;
var url = '#Url.Action("ViewMore", "Home")'
var data = { nextrecord: next};
$.ajax({
type: "POST",
url: url,
data: data,
success: function (result) {
$("#morecomments").html(result);
}
});
});
In above code i am getting 10 comments first time and when user click on More Post button it will show me above 10 comments plus next 10 comments. but whole div is getting refreshed.
What changes i have to do so that i can get user comments without affecting previous showing comments?
Suppose user having 50-60 post in his section then all comments should be display 10+ on More Post button click and so on...
How can i do that?
You need to filter your records and put it in comment div... Your code should like this:
$('.morerecords').livequery("click", function (e) {
var next = 10;
var url = '#Url.Action("ViewMore", "Home")'
var data = { nextrecord: next};
var older_records = $("#morecomments").text();
$.("comments").append(older_records); //When you will get next record data, older data will be filled in comment div.
$.ajax({
type: "POST",
url: url,
data: data,
success: function (result) {
$("#morecomments").html(result);
}
});
});
The error is in:
$("#morecomments").html(result);
.html("somevalue") deletes the content, then fills it with whatever parameter you supplied.
Try doing this:
$("#morecomments").html($("#morecomments").html() + result);
or even easier:
$("#morecomments").append(result);
I know this works if you're passing strings, and a partial view is basically a html string. I don't know if there will be any conflict issues with the tags brought along by partial views.
Either way, this is the easiest way to add to an element rather than write over it.
If you are using Entity Framework (which you do), you need to use something like below:
public JsonResult Get(
//this is basically giving how many times you get the comments before
//for example, if you get only one portion of the comments, this should be 1
//if this is the first time, this should be 0
int pageIndex,
//how many entiries you are getting
int pageSize) {
IEnumerable<Foo> list = _context.Foos;
list.Skip(PageIndex * PageSize).Take(pageSize);
if(list.Count() < 1) {
//do something here, there is no source
}
return Json(list);
}
This is returning Json though but you will get the idea. you can modify this based on your needs.
You can use this way for pagination as well. Here is a helper for that:
https://bitbucket.org/tugberk/tugberkug.mvc/src/69ef9e1f1670/TugberkUg.MVC/Helpers/PaginatedList.cs

Passing the signed_request along with the AJAX call to an ActionMethod decorated with CanvasAuthorize

This is a follow-up to AJAX Call Does Not Trigger Action Method When Decorated With CanvasAuthorize
So I found the following links and it seems that this is a common problem:
http://facebooksdk.codeplex.com/discussions/251878
http://facebooksdk.codeplex.com/discussions/250820
I tried to follow the advice by prabir but I couldn't get it to work...
Here's my setup:
I have the following snippet in the page where the button that triggers the whole post to facebook is located:
#if (!string.IsNullOrEmpty(Request.Params["signed_request"]))
{
<input type="hidden" id="signedReq" value="#Request.Params["signed_request"]" />
}
And then I have this snippet (inside a script tag inside the same page):
var signedRequest = $('#signedReq').val();
$('.facebookIcon').click(function () {
var thisItem = $(this).parent().parent();
var msg = thisItem.find('.compItemDescription').text();
var title = thisItem.find('.compareItemTitle').text();
var itemLink = thisItem.find('.compareItemTitle').attr('href');
var img = thisItem.find('img').first().attr('src');
postOnFacebook(msg, itemLink, img, title, signedRequest);
});
And finally, inside an external js file I have the following function:
/*Facebook post item to wall*/
function postOnFacebook(msg, itemLink, pic, itemTitle, signedReq) {
console.log(signedReq);
var siteUrl = 'http://www.localhost:2732';
$.ajax({
url: '/Facebook/PostItem',
data: {
'message': msg,
'link': siteUrl + itemLink,
'picture': siteUrl + pic,
'name' : itemTitle,
'signed_request': signedReq
},
type: 'get',
success: function(data) {
if(data.result == "success") {
alert("item was posted on facebook");
}
}
});
}
But signedReq is always undefined. And I'm not really sure I should be passing the 'signed_request' field inside the data object. Any thoughts?
Make sure you hidden input field is being populated.
Also, when you try to pull the ID of the input field via JQuery, you might not be referencing the proper element since .NET butcher's ID's of anything that's run on the server.
When I use the hidden input field trick, I set the jquery value like so:
var signedRequest = $('#<%=signedReq.ClientID %>').val();
This way, I'm getting the identifier that .NET is giving to the HTML element.
Hope that helps.
Just a guess - in your hidden field: id="signed_request" instead of id="signedReq"

MVC.net noob question about Ajax and Json

I have a beginner level Json question with MVC.net (I've never really used jquery or json) so please excuse me if I ask something stupid.
I have a javascript file with the below
<script>
function refreshMovies() {
//$.getJSON("/Home/Refresh", showMovies);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Home/Refresh",
success: showMovies
});
}
function showMovies(movie) {
var frag = "<ul>";
frag += "<li>" + movie[0] + " - " + movie[1] + "</li>";
frag += "</ul>";
alert(frag);
$("#divMovies").html(frag);
}
</script>
My Home controller looks like:
public ActionResult Refresh()
{
return Json(GetMovies()); // Method Returns IList<Movies>
}
The question I have is the frag on the alert and when the UL is displayed on the page is always empty.
However, firebug does show that the post request is returning the json, so maybe something is going wrong with showMovies()?
You say that firebug reports that you are getting your JSon correctly, otherwise I'd ask you whether you decorated the action with [HttpPost], as you are using the POST method.
Does the alert() currently display the correct HTML? If so, does the div have the id="divMovies" attribute (note, no # character here!).
Otherwise, try to move the alert() on top of the showMovies: does it show anything?

Resources