Getting YouTube views with Backbone.js - ajax

I have been using Backbone.js to act as a middleman between Wordpress (using the super rad JSON API plugin) and my front end.
Each of my Wordpress posts has a YouTube video ID attached to it, which is getting pulled back when I fetch the collection.
I am trying to work out the best point within the application to go out and parse the video ID to get the total video views.
This is code that is fetching the collection model:
parse: function(response) {
return response.posts;
}
And the following code is then rendering the appropriate view.
this.getCollection().each(function(model) {
var view = new App.Thumbnail.View({model: model});
var item = $(view.render().el);
this.container.append(item);
});
At some point in this process, I need the thumbnails to assign themselves the video count. This is the code I have for grabbing the YouTube view count:
function getYoutubeViewCount(videoID) {
$.ajax({
url: "http://gdata.youtube.com/feeds/api/videos/" + videoID + "?v=2&alt=json",
dataType: "jsonp",
success: function (data) { console.log(data.entry.yt$statistics.viewCount); }
});
}
So my question is, where do you think the best place to fetch the view count is? Should I create a sub-model that fetches the count? Or do it outside of backbone.js?
Any help would be beyond appreciated!
Thanks in advance,
Charlie.

The viewCount should be an attribute on your Video model subclass. You can load both the wordpress data for the video and the youtube count in parallel before instantiating your model, or you can instantiate your model with the data from wordpress while the youtube data is being fetched and latered applied. Once you get the view count from youtube, set it on the corresponding model instance. Have your view bind to the change:viewCount event on the model and re-render itself (or at least shove the view count into the appropriate element in the DOM) once this data is loaded.
As to WHEN you do this, probably you should start fetching the view count(s) in the background as soon as you have your basic Video model instance created and populated with its basic attributes from your wordpress data source. Or you can choose to load view counts later lazily when the video is played or scrolled into the viewport or moused over or whatever.

Related

Submitting data after image upload

My site has a feature that allows users to create posts (like Facebook). I have a form with a "Message" input field and a button that allows users to upload images.
Right now, how I have the code set up is that when the user submits the form, my code will submit the data first, and then upload the images.
The problem with this is that if the user cancels the image upload half way through, the database record will exist (because the data was submitted before the image upload), but there will be no images uploaded.
So my solution to this is to upload the images first and submit the data after. The problem with this is that I'm not sure how I can tie the images to the data in a database record.
Should I upload all of the images to /tmp and then move the files to a permanent directory, like /var/www/html/website/public/img/uploads/<upload_id> where upload_id is the id of the database record?
What should I do if the user uploads an image, but closes the tab half way. Then there will be an image in /tmp that will stay there forever unless the directory is cleaned up. How would I clean it up?
Is this the best way to do this or are there better ways?
I'm using Laravel 5.3 and Dropzone.js.
Thanks.
Since you are using Dropzone.js which allows files to be uploaded via ajax, you can do this the following way :
1) Send file to the backend server using Dropzone.js (ajax).
2) Since you are using laravel, each file you receive will be an instance of UploadedFile, you can use this class to access the Original Name of the file uploaded, size, MimeType etc.
3) In the Image Model in your database (create this if not done already), create a new record for this image and store the fields mentioned above if needed, along with the path where you will be storing the image. You can use this path stored in the table row to access the image later.
4) Get the 'id' of the newly inserted row in the Image Table and pass it back to the frontend where you can receive it using the 'success' event Handler for the Dropzone plugin.
5) Append this newly inserted 'id' as a hidden input element in your form.
6) When you submit the form, you will receive the image ids related to your post and you may save it using the Database relationship of your choice.
7) Yes, you need an additional check for images that have been uploaded and entered in your Image table, but those whose posts have not been created. You may create an Artisan CLI command for the same and assign it as a Cron Job.
I think you should submit your form with AJAX. This solution was useful for me.
Make a, span or other element with event "onclick" instead of button, because button pressing will confirm the form automatically, even if the button's type isn't a "submit".
Write an ajax function like this:
function newsFormSubmit(item_id){
var formData = new FormData($('.news-form')[0]);
formData.append("item_id", item_id);
$.ajax({
type: 'POST',
url: config.routes[0].savenews,
data: formData,
processData: false,
contentType: false,
success: function (data) {
if (data.error)
{
alert(data.error);
return false;
} else if (data)
{
$('#news-card-' + item_id).html(data);
}
}
});
}
Place this function on onclick event.

using ajax or not when displaying new records in asp.net mvc

I am a beginner in MVC. In my application, I list categories (as a button) on the left hand-side (inside a div). Just right to this div, there is another div which displays the items associated with the clicked category.
When a category button is clicked, I am planning to call the action of the controller that will retrieve the Items from the database and add these Items to the ViewModel (e.g., model.Items = db.Items...), and then call the View with the updated Model and display the Items.
However, I am curios if it is better to make an Ajax call here and use a partial view for displaying the Items of the clicked category.
If feel like between these two approaches in my scenario only difference will be the page-refresh, they should work the same in terms of speed since both of them require the same database call.
Can anyone share good practices in MVC for such scenarios?
Yes AJAX is faster and good way to update detail in same page without refresh.
For that you have to create JsonResult method in controller. It will give you result in Json.
Try JQuery Template plugin for repeated code.
<script id="trTemplate" type="text/x-jquery-tmpl">
<tr>
{{each $data}}
<td>${Col}</td>
{{/each}}
</tr>
</script>
<table id="containerTable">
</table>
AJAX Call
$.ajax({
url: 'Your JsonResult Method URL',
type: "GET",
data: data,
beforeSend: function () {
},
success: function (data) {
// It will pass data to template and template will bind parsing json
$('#trTemplate').tmpl(data).appendTo('#containerTable');
//Business logic
},
complete: function () {
// Your Code
}
});
Your JsonResult Method
[HttpPost]
public JsonResult GetData(ViewModel model)
{
// Your Code here
}
using ajax or not when displaying new records in asp.net mvc
Using jquery would be the best approach for this scenario. As you don't have to load the layout page which will have to render the scripts and stuff all over again. Stick on to Ajax calls in MVC as much as possible, The technologies are being improved and a lot of single page applications are out there, And if we still use a page load for every new request then there is no point.
Coming to comparison between passing back Partial View And Json Data. Which is better to use in the application design?
Both partial Views and Json data hold the same weight depending on the scenario.
When to use partial view: Lets say you have a Model and you have to build the view HTML by lot of if checks and loops and possibly some c# code ( in rare scenarios), etc, in such scenario using Partial view would be the better choice, Because if we try to build the same thing in Jquery using json data the complexity of the code required would be high compared to what can be done in Partial views, But still achieving it is possible but wont be that easy and we might make errors during development.
When to use Json Data: If the requirement is like updating a grid, generating dynamic drop down or dealing with some Jquery plugins in the page I think Json data would be better, as many plugins play with json data as the core requirement.
A Small Example Of Deciding Between Partial View And Json Data - interested folks and read through
Lets take a scenario where we have to display a grid of data. This is our initial requirement. So we can happily build our viewModel with data and pass it to our partial view and render the table using for loops. All set, Now the requirement changes and we are asked to build sorting, filtering and paging stuff in our table. So at present we look for a plugin that can be easily integrated with current code and yes the easy one to use at this scenario is Datatables. Ok, we wrote a small Jquery to apply the plugin to the table and all set we have the fancy stuff ready.
Now here is the tricky part, we are asked to add functionalities like add, edit, delete record from the table. Yes its possible but is little tricky to get it done in the best possible way with the current code which we have. What we tend to do is, when ever there is a change in the table we plan to recall the partial view. Which works fine but still asking to ourselves just to delete one record from the table is it good to reload the partial view again?? Definitely NOT,
What can we do? When ever there is any add, edit, delete operation we hit the controller to update the database and we can make the controller return a JSON data and just pass this Json data to the plugin API and refresh the table, This will be more neat and faster. So here you see JSON data would be the better choice. Also some might even want to make it more cleaner by just playing with that one record of data and writing up some jquery code to manipulate the table, which is absolutely fine, But it requires us to pass the Json data itself back from controller.
So having this done, we can go back and refactor our code to make partial view to use json data for the grid initially too or leave it as it is saying the initial load will be a partial view, but following operations would be a json result, which is fine but I feel let all the data related stuff come from one point.
So that explains how a simple module can change from being a partial view to then use Json data. There are scenarios where the story is the other way around, You have to pick the right one for the right work.

Get all products by category with AJAX call - Magento

Im a newbie in magento and i have a project where the client requires to have a custom page to list all products and filter them via Categories(dropdown list of categories). When a category is chosen from the dropdown, the product list should be updated without reloading the page. In the programming side, once the category is chosen, i will call a url/function of magento via ajax and pass category id ass post/get parameter. The response of the call should be a json.
Ive been researching a while but seems like most of the examples need page reloading.
Can you give me idea or code snippets on what function/url to call as my starting point?
I have not tried anything so far but i know how the logic works. It;s just that i dont know where to get started.
Hopefully someone can lead me to the right direction.
Any little help will be greatly appreciated
Magento uses Prototype JS library. It has the AJAX object included. You can add event onchange for the dropdown and init AJAX in this event.
var request = new Ajax.Request(url,{
method: 'get',
parameters:{'is_ajax':1},
onSuccess: function(response){
data = response.responseText;
if(!data.isJSON()){
setLocation(url);
}
data = data.evalJSON();
if (!data.page || !data.blocks){
setLocation(url);
}
amasty_layered_navigation_ajax_update(data);
},
onFailure: function(){
setLocation(url);
}
}
);

JQuery Mobile and JSONP

I have my jquery mobile app pulling data from our mysql db using JSONP. The data is pulling fine, but the problem comes when I go back to the previous "page" in my app then click on a different option, it doubles the data on the next screen, and it will just keep stacking the data as many times as I do that. What am I missing?
The app doesn't look right in any browsers, but it looks fine in the ios simulator or appmobi simulator. I can post some code if needed, just know it won't look right in your browser.
Thank you for any help you can provide
$('#two').bind('pagecreate',function(event){
var img = getUrlVars()["st"];
var photo = $('#img');
$.ajax({
type: 'GET',
url: 'http://serverhidden/json/img.php?st='+img,
dataType: 'jsonp',
success: function(data) {
$.each(data, function(i,item){
var image = '<img class="stmap" src="images/states/lrg/'+item.img+' "/>';
photo.html(image);
});
},
error: function(e) {
//called if there is an error
//console.log(e.message);
}
});
});
Make sure you are not subscribing your event multiple times. It seems silly but is easy to do.
I would recommend you add logs to your JQM site so that you can see how many times your site is being updated.
You should also be aware that updating a JQMobile page often requires a call to a method to update content after a page is rendered. See here: jQuery Mobile rendering problems with content being added after the page is initialized
Hope those help.
So without any code from your project this is a shot in the dark but it seems like you populate a pseudo-page with information on pageshow with an .append() call. Instead of using .append(), use .html() as it will replace the information already present rather than add to it.
If each state has an individual page then you can bind to the pagecreate (or similar) event so the data will only be appended once rather than on each pageshow event.

Ajax state history in coldfusion page

I'm confused as to how to accomplish this. I have a page which, has a popup filter, which has some input elements and an "Apply" button (not a submit). When the button is clicked, two jquery .get() calls are made, which load a graph, a DataTables grid, photos, and miscellaneous info into four separate tabs. Inside the graph, if one clicks on a particular element, the user is taken to another page where the data is drilled down to a finer level. All this works well.
The problem is if the user decides to go back to the original page, but with the ajax generated graph/grid/photos etc. Originally I thought that I would store a session variable with the filter variables used to form the original query, and on returning to the page, if the session var was found, the original ajax call would be made again, re-populating the tabs.
The problem that I find with this method is that Coldfusion doesn't recognize that the session variable has been set when returning to the page using the browser's back button. If I dump out the session var at both the original and the second page, I can see the newly set var at the second page, and I can see it if I go to the original page through the navigation menu, but NOT if I use the back button.
SO.... from reading posts on here about ajax browser history plugins, it seems that there are various jquery plugins which help with this, including BBQ. The problem that I see with this approach is that it requires the use of anchor elements to trigger it, and then modifies the query string using the anchors' href attributes. I suppose that I could modify the page to include a hidden anchor.
My question, at long last is: is an ajax history plugin like BBQ the best way to accomplish this, or is there a way to make Coldfusion see the newly created session var when returning to the page via the back button? Or, should I consider re-architecting the page so that the ajax calls are replaced by a form submission back to the page instead?
Thanks in advance, as always.
EDIT: some code to help clarify things:
Here's the button that makes the original ajax calls:
<button id="applyFilter">APPLY</button>
and part of the js called on #applyFilter, wrapped in $(document).ready():
$('#applyFilter').click(function(){
// fill in the Photos tab
$.get('tracking/listPhotos.cfm',
{
id: id,
randParam: Math.random()
},
function(response){
$('#tabs-photos').html(response);
}
);
});
Finally, when the user calls the drill-down on the ajax generated graph, it uses the MaintAction form which has been populated with the needed variables:
function DrillDown() {
//get the necessary variables and populate the form inputs
document.MaintAction.action = "index.cfm?file=somepage.cfm&Config=someConfig";
document.MaintAction.submit();
}
and that takes us to the new page, from which we'd like to return to the first page but with the ajax-loaded photos.
The best bet is to use the BBQ method. For this, you don't have to actually include the anchor tags in your page; in fact, doing so would cause problems. This page: http://ajaxpatterns.org/Unique_URLs explains how the underlying process works. I'm sure a jQuery plugin would make the actual implementation much easier.
Regarding your other question, about how this could be done with session variables - I've actually done something similar to that, prior to learning about the BBQ method. This was specifically to save the state of a jqGrid component, but it could be easily changed to support any particular Ajax state. Basically, what I did was keep a session variable around for each instance of each component that stored the last parameters passed to the server via AJAX requests. Then, on the client side, the first thing I did was run a synchronous XHR request back to the server to fetch the state from that session variable. Using the callback method for that synchronous request, I then set up the components on my page using those saved parameters. This worked for me, but if I had to do it again I would definitely go with the BBQ method because it is much simpler to deal with and also allows more than one level of history.
Some example code based on your update:
$('#applyFilter').click(function(){
var id = $("#filterid").val(); // assumes the below id value is stored in some input on the page with the id "filterid"
// fill in the Photos tab
$.get('tracking/listPhotos.cfm',
{
id: id // I'm assuming this is what you need to remember when the page is returned to via a back-button...
//randParam: Math.random() - I assume this is to prevent caching? See below
},
function(response){
$('#tabs-photos').html(response);
}
);
});
/* fixes stupid caching behavior, primarily in IE */
$.ajaxSetup({ cache: false });
$.ajax({
async: false,
url: 'tracking/listPhotosSessionKeeper.cfm',
success: function (data, textStatus, XMLHttpRequest)
{
if (data.length)
{
$("#filterid").val(data);
$('#applyFilter').trigger('click');
}
}
});
This is what you need on the client-side to fetch the state of the photo list. On the server side, you'll need to add this modification to tracking/listPhotos.cfm:
<cfset session.lastUsedPhotoFilterID = URL.id>
And add this new one-line file, tracking/listPhotosSessionKeeper.cfm:
<cfif IsDefined("session.lastUsedPhotoFilterID")><cfoutput>#session.lastUsedPhotoFilterID#</cfoutput></cfif>
Together these changes will keep track of the last ID used by the user, and will load it up each time the page is rendered (whether via a back button, or simply by the user revisiting the page).

Resources