How to update video playing current time using ajax in laravel - mysql

<script>
var vid = document.getElementById("player");
$(function() {
var timeout;
$("#player").on("playing pause", function(e) {
// Save reference
var v = this
// Clear previous timeout, if any
clearTimeout(timeout)
// Call immediately if paused or when started
performaction(v.currentTime, v.duration)
// Set up interval to fire every 5 seconds
if (e.type === "playing") {
timeout = setInterval(function() {
performaction(v.currentTime, v.duration)
}, 5000)
}
})
function performaction(currentTime, duration) {
console.log(currentTime);
console.log(' ajax action goes here');
var data = { pause_time : currentTime };
$.ajax({
type: "POST",
url: '/instructor/promo_video/84',
data: data,
success: function() {
console.log("Value added");
}
})
}
})
</script>
In my database I have a video table in which I have a column name as pause_time.
Now if I use this js code for video current playing time then I am getting the time after 5 seconds interval in the console.
I want to send this time to the database using ajax in laravel. And also how to take the currentTime value in the controller.
Thanks in Advance!!

If you created a video table, then you should make a video model:
php artisan make:model Video
When you're using POST methods in frontend, you need to pass a CSRF token too.
const data = {
_token: YOUR_TOKEN,
pause_time : currentTime,
};
To get data from database, you should use ORM, so:
$video = Video::where(SOME_CONDITIONS, value)->first();
$currentTime = $video->pause_time;
To get data from frontend, you should use $request:
public function yourController(Request $request)
{
$currentTime = $request->pause_time;
}

Related

Using Spotify webAPI to play random album of artist (ID)

here is my "little" project, as I am not a developer myself please don't blame me for my stupid questions.
I want to create a "audio book machine".
I want to use a Website, that shows several Artists of audiobooks. If I click on one artist, a random audiobook of the clicked artist should be played.
I had a look at this code example: http://jsfiddle.net/qlmhuge/t7a1sh4u/
// find template and compile it
var templateSource = document.getElementById('results-template').innerHTML,
template = Handlebars.compile(templateSource),
resultsPlaceholder = document.getElementById('results'),
playingCssClass = 'playing',
audioObject = null;
var fetchTracks = function (albumId, callback) {
$.ajax({
url: 'https://api.spotify.com/v1/artists/61qDotnjM0jnY5lkfOP7ve/albums/',
success: function (response) {
callback(response);
}
});
};
var searchAlbums = function (query) {
$.ajax({
url: 'https://api.spotify.com/v1/search',
data: {
q: 'artist:' + query,
type: 'album',
market: "DE"
},
success: function (response) {
resultsPlaceholder.innerHTML = template(response);
}
});
};
results.addEventListener('click', function(e) {
var target = e.target;
if (target !== null && target.classList.contains('cover')) {
if (target.classList.contains(playingCssClass)) {
audioObject.pause();
} else {
if (audioObject) {
audioObject.pause();
}
fetchTracks(target.getAttribute('data-album-id'), function(data) {
audioObject = new Audio(data.tracks.items[0].preview_url);
audioObject.play();
target.classList.add(playingCssClass);
audioObject.addEventListener('ended', function() {
target.classList.remove(playingCssClass);
});
audioObject.addEventListener('pause', function() {
target.classList.remove(playingCssClass);
});
});
}
}
});
searchAlbums('TKKG');
but I cannot figure out how to change it to play a random album by one artist.
The artist will be defindes by the spotify ID so that the artist ist the correct one.
Can someone help me out with my problem? What else info is needed to complete my goal?
I would be very thankful if one can give me a hint, or whatever, to get to the right direction.
Best regards,
goeste
You have to modify your fetchTracks function here:
var fetchTracks = function (albumId, callback) {
$.ajax({
url: 'https://api.spotify.com/v1/albums/' + albumId,
success: function (response) {
callback(response);
}
});
};
jsFiddle link
I got a little closer to the finish line... well, I guess:
I found the following on GitHub:
var SpotifyWebApi = require('spotify-web-api-node');
var spotifyApi = new SpotifyWebApi();
// credentials are optional
// var spotifyApi = new SpotifyWebApi({
// clientId : '',
// clientSecret : '',
// redirectUri : ''
// });
// Get albums by a certain artist
spotifyApi.getArtistAlbums('3meJIgRw7YleJrmbpbJK6S')
.then(function(data) {
console.log('Artist albums', data.body);
}, function(err) {
console.error(err);
});
However, I only get 20 albums out of 35. I need to increase the limit. The max limit is 50, as I read on the developer site of Spotify. As I only need to get one out of the 35 albums (randomly), how can I implement the randomize function and also play function in order to work?
I am still figuring out how to create a link from the results to show on a website with node.js.
Best regards, and thank you in advance for any assistance/help!
-goeste

Data not being fetched from json file

I am trying to fetch data from the static json file but the data is not getting displayed at all. What could be the possible reason for it.
Below is my code:
var Collection = Backbone.Collection.extend({
url: "names_of_people.json",
initialize: function() {
this.fetch();
}
});
collections = new Collection();
console.log("the length "+collections.length);
for (i=1;i<collections.length;i++)
{
console.log("done "+ collections.at(i).get("name"));
}
The problem is that this code:
console.log("the length "+collections.length);
for (i=1;i<collections.length;i++)
{
console.log("done "+ collections.at(i).get("name"));
}
ends up being executed before this.fetch() has completed. You'll need to either put your code in this.fetch's success callback, like this:
var Collection = Backbone.Collection.extend({
url: '/data.json',
initialize: function() {
this.fetch({
success: function() {
console.log(collections, 'the length ' + collections.length);
for (var i = 0; i < collections.length; i++) {
console.log('done ' + collections.at(i).get('name'));
}
}
});
}
});
var collections = new Collection();
or by listening to the collection's sync event, which occurs when this.fetch has completed successfully. This pattern is more commonly used in Backbone applications.
var Collection = Backbone.Collection.extend({
url: '/data.json',
initialize: function() {
this.listenTo(this, 'sync', this.syncExample);
this.fetch();
},
syncExample: function() {
console.log(collections, 'the length ' + collections.length);
for (var i = 0; i < collections.length; i++) {
console.log('done ' + collections.at(i).get('name'));
}
}
});
var collections = new Collection();
You can read more about Backbone's event system and the listenTo function here.
check backbone parse function. after fetch it will also call vlidate and parse if they exist.
EDIT: more detail
The key thing here I think is, the fetch() is asynchronous, so by the time you start loop, the data is not here yet. So you need to execute the code when you are sure the collection is ready. I usually listen to a "reset" event, and let the fetch to fire a reset event by collection.fetch({reset:true}).
Backbone Collection, whenever fetch, and get an array of data from server in a format
[obj1,obj2],
it will pass each of these into a parse function, described here
For debug purpose you can simply do:
var MyCollection=Backbone.Collection.extend({
parse:function(response){
console.log(response);
return response;
}
})
This can check if the fetch indeed get the json.
On a side note, it is always a good practise to fetch it after you initialized the collection, means you don't put the this.fetch() inside initialize(), you do this outside.
for example, if you want to print out all the element name, you can do
var c=MyCollection();
c.fetch({reset:true}); // this will fire 'reset' event after fetch
c.on('reset',printstuff());
function printstuff(){
_.forEach(c,function(e){
console.log(e.get('name'));
});
}
Note this 'reset' event fires after all the collection is set, means it is after the parse() function. Apart from this parse(), there is also a validate function that is called by model. You collection must have a model parameter, you can make your own model, and give it a validate(), it also print out stuff.

Parallel form submit and ajax call

I have a web page that invokes long request on the server. The request generates an excel file and stream it back to the client when it is ready.
The request is invoked by creating form element using jQuery and invoking the submit method.
I would like during the request is being processed to display the user with progress of the task.
I thought to do it using jQuery ajax call to service I have on the server that returns status messages.
My problem is that when I am calling this service (using $.ajax) The callback is being called only when the request intiated by the form submit ended.
Any suggestions ?
The code:
<script>
function dummyFunction(){
var notificationContextId = "someid";
var url = $fdbUI.config.baseUrl() + "/Promis/GenerateExcel.aspx";
var $form = $('<form action="' + url + '" method="POST" target="_blank"></form>');
var $hidden = $("<input type='hidden' name='viewModel'/>");
$hidden.val(self.toJSON());
$hidden.appendTo($form);
var $contextId = new $("<input type='hidden' name='notifyContextId'/>").val(notificationContextId);
$contextId.appendTo($form);
$('body').append($form);
self.progressMessages([]);
$fdbUI.notificationHelper.getNotifications(notificationContextId, function (message) {
var messageText = '';
if (message.IsEnded) {
messageText = "Excel is ready to download";
} else if (message.IsError) {
messageText = "An error occured while preparing excel file. Please try again...";
} else {
messageText = message.NotifyData;
}
self.progressMessages.push(messageText);
});
$form.submit();
}
<script>
The code is using utility library that invokes the $.ajax. Its code is:
(function () {
if (!window.flowdbUI) {
throw ("missing reference to flowdb.ui.core.");
}
function NotificationHelper() {
var self = this;
this.intervalId = null;
this.getNotifications = function (contextId, fnCallback) {
if ($.isFunction(fnCallback) == false)
return;
self.intervalId = setInterval(function() {
self._startNotificationPolling(contextId, fnCallback);
}, 500);
};
this._startNotificationPolling = function (contextId, fnCallback) {
if (self._processing)
return;
self._processing = true;
self._notificationPolling(contextId, function (result) {
if (result.success) {
var message = result.retVal;
if (message == null)
return;
if (message.IsEnded || message.IsError) {
clearInterval(self.intervalId);
}
fnCallback(message);
} else {
clearInterval(self.intervalId);
fnCallback({NotifyData:null, IsEnded:false, IsError:true});
}
self._processing = false;
});
};
this._notificationPolling = function (contextId, fnCallback) {
$fdbUI.core.executeAjax("NotificationProvider", { id: contextId }, function(result) {
fnCallback(result);
});
};
return this;
}
window.flowdbUI.notificationHelper = new NotificationHelper();
})();
By default, ASP.NET will only allow a single concurrent request per session, to avoid race conditions. So the server is not responding to your status requests until after the long-polling request is complete.
One possible approach would be to make your form post return immediately, and when the status request shows completion, start up a new request to get the data that it knows is waiting for it on the server.
Or you could try changing the EnableSessionState settings to allow multiple concurrent requests, as described here.

Repeat jQuery JSON request until condition is met

I am trying to repeat a JSON request in jQuery to check the status of a video encoding job until it is completed. "Processing" would be displayed until the job is finished, at which point the video will be displayed.
Would a loop, checking every x seconds to see if "status" equals "finished," be the best solution for this? If so, how would I break free from this loop when the job is finished?
The JSON response while the job is in progress will be nothing more than "processing," when it is finished it will contain things such as the job ID, width, and height.
Any help would be appreciated, thanks!
UPDATE
Here's my final solution thanks to Felix:
var checkStatus = function() {
$.getJSON('json-data.php', function(data) {
if (data.status != 'finished') {
setTimeout(checkStatus, 2000);
} else {
//Sample code to run when finished
$("#statusText").text("Job Complete");
$("#dimensions").text(data.width + 'x' + data.height);
}
});
};
checkStatus();
A loop won't work as the Ajax request is asynchronous.
One way would be to make same kind of recursive call and trigger the Ajax function again from the success callback (maybe after some timeout), if the condition is not met.
Something like (pseudo code):
function check_condition() {
$.getJSON(<url>, function(result) {
if(!result.finished) {
setTimeout(check_condition, 2000);
}
// do something else
}
}
var checkStatusInterval = 30 * 10000; // 30 seconds
var checkStatusFunc = function(){
$.getJSON('getMovieStatus', function(data){
if (data.Incompleted){ // or however you check
checkStatusTimer = setTimeout(checkStatusFunc, checkStatusInterval);
}
});
};
var checkStatusTimer = setTimeout(checkStatusFunc,checkStatusInterval );
To stop:
<input type="button" id="stopchecking" value="Stop Checking..." />
$('#stopchecking').click(function(e){
clearTimeout(checkStatusTimer);
});

How would I send a POST Request via Ajax?

I have a php page, Post.php it recieves the POST's Action, and that has two functions. Insert, and Update.Now how would I go about posting INSERT with this Ajax code. The code posts update fine but is doesnt post insert at all.
$(document).ready(function(){
//global vars var inputUser =
$("#nick"); var inputMessage =
$("#message"); var loading =
$("#loading"); var messageList =
$(".content > ul"); //functions
function updateShoutbox(){ //just
for the fade effect
messageList.hide();
loading.fadeIn(); //send the post to shoutbox.php
$.ajax({ type:
"POST", url: "Shoutbox.php", data:
"action=update",complete:
function(data){
loading.fadeOut();
messageList.html(data.responseText);
messageList.fadeIn(2000); } }); }
function checkForm(){
if(inputUser.attr("value") &&
inputMessage.attr("value"))return
true; else return false; }
//Load for the first time the
shoutbox data updateShoutbox();
//on submit event
$("#form").submit(function(){
if(checkForm()){ var nick =
inputUser.attr("value"); var
message = inputMessage.attr("value");
//we deactivate submit button while
sending $("#send").attr({
disabled:true, value:"Sending..." });
$("#send").blur(); //send the
post to shoutbox.php $.ajax({
type: "POST", url: "Shoutbox.php", data: "action=insert&nick=" + nick +
"&message=" + message,
complete: function(data){
messageList.html(data.responseText);
updateShoutbox();
//reactivate the send button
$("#send").attr({ disabled:false, value:"Shout it!" });
}
}); } else alert("Please fill all fields!"); //we prevent the
refresh of the page after submitting
the form return false; }); });*emphasized text*
List item
Your second call to $.ajax uses type: "GET" whereas the first uses type: "POST". Try switching the second one to "POST".