BackboneJS + Codeigniter RESTful API - How do I pass $startdate and $enddate - php

I have a Backbone App with Codeingiter as Backend. I use the RESTful API setup to pass data back and forth between these to Frameworks.
Now I want to have a View which shows me the "newest followers", for that I created an API like this:
public function new_artist_followers_get($start_date, $end_date)
{
$this->load->database();
$sql = "SELECT users.img_name FROM artist_followers INNER JOIN artists ON artists.artist_id = artist_followers.artist_id INNER JOIN users ON users.user_id = artist_followers.user_id
WHERE artist_followers.artist_id = artists.artist_id AND date_time BETWEEN '$start_date' AND '$end_date' LIMIT 20";
$query = $this->db->query($sql);
$data = $query->result();
if($data) {
$this->response($data, 200);
} else {
$this->response(array('error' => 'Couldn\'t find any artist followers!'), 404);
}
}
My issue is that I'm not really sure how to pass the dates to my Backbone frontend? Do I have to do it somehow like this?:
NewFollowers.NewFollowersCollection = Backbone.Collection.extend({
url: function() {
return '/projects/testproject/index.php/api/testfile/new_artist_followers/'+ this.artist_id + this.startdate + this.enddate;
}
});
Normally, I fetch an API exactly like in the example above, just without the this.startdate and this.enddate and then in my MainView i gather everything, where I for each API/Collection do this (in this case an artist biography):
beforeRender: function() {
var artistbioCollection = new Artistbio.ArtistbioCollection();
artistbioCollection.artist_id = this.artist_id;
this.insertView('.artistBio', new Artistbio.View({collection: artistbioCollection}));
artistbioCollection.fetch();
....etc. etc. ...
}
So can anyone help me out?

Backbone.Collection fetch method accepts extra parameters, they should be passed like this:
artistbioCollection.fetch({
data: {
start_date: this.startdate,
end_date: this.enddate
}
});
It is in Backbone documentation
So here, data is the same property as jQuery.ajax data property, you can then grab these values server-side as usual.
As fetch perfoms a GET request, all parameters passed to data will be appended to query string

You should use URI templates to define the URI on the server side, like so:
http://example.com/api{/artist,id}/followers{?stardate,enddate}
After that you can use for example this library to fill this template on the client side with params. You can add a custom setter for those params, for example (not tested):
NewFollowers.NewFollowersCollection = Backbone.Collection.extend({
url: function() {
return URI.expand("http://example.com/api{/artist,artistId}/followers{?startDate,endDate}", this.params).href();
},
setParams: function (artist, start, end){
this.params = {
artistId: artist.get("id"),
startDate: start,
endDate: end
};
}
});
Be aware, that this is not a complete REST solution. By REST you get hypermedia responses, which contain links. One of those links can contain the actual URI template and a parameter description. So your client is completely decoupled from the URI structure, it does not know how to build an URI, but it knows how to evaluate an URI template, which is a standard solution. You decouple the client from the implementation of the service using standard solutions, this is called the uniform interface constraint of REST.

Related

How to run a helper function multiple times for checking live results from the DB

I have a forum project with Laravel 9, and I have made this helper function.
if(!function_exists('new_question')){
function new_question($c) {
$quelist = \DB::table('questions')->get();
$quecount = $quelist->count();
if($quecount > $c){
return 'A new question is added.. please refresh the page..';
}
}
}
So it gets the number of current questions like this:
{{ new_question($queCnt); }}
And then, it will check if the $quecount equals $queCnt or not. And if not, then print the statement A new question is added.. please refresh the page... Therefore the user will understand if any new question is added. But I need to run this helper function after some periods of time (for example, 10 seconds). However, I don't know how to call a function after a custom amount of time.
to run any function after a specific time, you have set the interval for example
// Call the new_question function every 10 seconds
setInterval(new_question, 10000);
// Use an AJAX request to call the new_question function on the
// server
function new_question(){
$.ajax({
url: '{{ url('/new_question') }}?c=10',
success: function(response) {
// Handle the response from the server
console.log(response);
}
});
}
</script>
// to receive get value update helper function
if(!function_exists('new_question')){
function new_question() {
// Get the value of the c parameter from the query string
$c = isset($_GET['c']) ? $_GET['c'] : 0;
// Your code here...
}
}
First, you have to figure out if the number of "content" has changed. Using Laravel, create a function that is accessible through a route, this function would return the number of posts, then, using javascript, you will call that function in an interval (example is 5 seconds) and if the number has changed since the last call, then there's new posts, so you should do some DOM manipulation to update your page to alert the user.
Your server side function would be simple, something like this:
function count_questions() {
$quelist = DB::table('questions')->get();
$quecount = $quelist->count();
$response = array('quecount' => $quecount);
echo json_encode($response);
}
Then, identify how to reach this function through your routing table, and use the below jquery functions:
var quecount = 0;
$(document).ready(function() {
setInterval(function() {
$.ajax({
// change this URL to your path to the laravel function
url: 'questions/count',
type: 'GET',
dataType: 'json',
success: function(response) {
// if queuecount is 0, then set its initial value to quecount
if(quecount == 0){
quecount = response.quecount;
}
if(response.quecount > quecount){
quecount = response.quecount;
new_question_found();
}
}
});
}, 5000);
});
function new_question_found(){
$("#new_questions").html("New questions found");
}
The solution that is coming to my mind is may be too advance or too complex.
This solution need
Laravel scheduler and queue (Jobs)
and web push notification (ex : one-signal)
To reduce the traffic in the back-end you can have job to run like every 10 seconds in the back-end (Laravel scheduler and Queue).
If the question count get increased. you can call a api in the push notification and you can say there is a new question added.
the above work-flow is not explained well but this is in very simple term.
For example:
on frontend side:
const check_new_questions = function() {
const message =
fetch('http://yourserver.com/new_questions_endpoint');
if (message) {
// show message
}
};
// call each 10 seconds.
setInterval(check_new_questions, 10000);
then on backend side:
create a route new_questions_endpoint which will call your function and return result as response.
But note, that receiving all the questions from the table each time could be expensive. Eloquent enables to make a count query without retrieving all the rows.
You can't have this behaviour happen without any form of javascript.
The main way you could do this is by setting an interval via front-end like others have said. If you have any familiarity with APIs and general HTTP protocol, I would recommend you make an API route that calls your helper function; I also recommend responding with an empty body, and using the http status code to determine whether a refresh is needed: 200 for success and no refresh, 205 for success and refresh needed.
So you simply set a fetch api call on timeout, don't even need to decode the body and just use the response status to determine whether you need to run location.reload().
To achieve your requirement as per the comment you need to create an ajax request to BE from FE to check the latest question and based on that response you need to do it.
setInterval(function()
{
$.ajax({
url: "{{url('/')}}/check/questions",
type: "POST",
dataType: "json",
data: {"action": "loadlatest", "id": id},
success: function(data){
console.log(data);
},
error: function(error){
console.log("Error:");
console.log(error);
}
});
}, 10000);//time in milliseconds
the above js code will create an ajax request to Backend, below code will get the latest question 'id'.
$latest_id = DB::table('Questions')->select('id')->order_by('created_at', 'desc')->first();
so either check it in BE and return a corresponding response to FE or return the latest id to FE and check it there.
then show the prompt to refresh or show a toast and refresh after 5 sec
Why do you use function_exists() ? I don't think it's useful in this case.
The easiest way to do what you want is to use ajax and setInterval
Front side:
const check_new_questions = function() {
const data =
fetch('http://yourserver.com/new_questions_endpoint?c=current');
if (data) {
alert(your_message);
}
};
// call each 10 seconds.
setInterval(check_new_questions, 10000);
Back side:
function new_question() {
// Get the value of the c parameter from the query string
$c = isset($_GET['c']) ? $_GET['c'] : 0;
$quelist = \DB::table('questions')->get();
$quecount = $quelist->count();
return ($quecount > $c);
}
I suggest to use c as the last id and to not count questions but just to get the last question id. If they are different, one question or more was inserted.
Attention if you use this solution ( Ajax pulling ) you'll get two requests per 10 seconds per connected users. One for the ajax call and one for for the database call. If you have 10 users a day, it's ok but not if you have 10 thousands. A better but more complex approach is to use Mercure protocol or similar ( https://mercure.rocks/ ).

How to access auth response in trigger file

When a user tries to connect my Zapier app, I'll ask for a login. I have used custom authentication, you can see the code below.
const testAuth = (z , bundle) =>
{
var email = bundle.authData.email;
var password = bundle.authData.password;
return z.request({
method: 'POST',
url: 'http://mysite/check_login',
}).then((response) => {
if (response['status'] === 201) {
throw new Error('Your credentials is not match with our database');
}
else
{
var obj = JSON.parse( response.content );
var user_id =obj.user_id;
return user_id;
}
});
This is run successfully, now I want to use this return data user_id in
trigger page(list.js) code listed below,
const list = (z, bundle) => {
//I WANTS TO USE THAT USER_ID OVER HERE
//USER_ID=;
const promise = z.request('http://mysite/list_data/'+USER_ID,
{
params: {}
});
return promise.then((response) => response.json);
};
Please help me out how to access auth response in trigger file.
Create a dynamic dropdown field for a trigger like below screnshot
to access user_id in a perform API call.
Here is an example app that utilizing dynamic dropdown feature:
https://github.com/zapier/zapier-platform-example-app-dynamic-dropdown
More helpful articles:
https://platform.zapier.com/cli_tutorials/dynamic-dropdowns
https://platform.zapier.com/cli_docs/docs#dynamic-dropdowns
David here, from the Zapier Platform team. Great question!
Normally, computed fields would be the answer here, but it's not currently possible to use those outside of OAuth.
In your case, there are two options:
If there's an easy and obvious way for the user to manually supply their id, then add it to the auth fields use it as needed
Otherwise, you'll need to call the login endpoint before you run each trigger to fetch the user id. You've got 30 seconds of execution time, so doing a second API request should be doable.
Yes Sure, Rather than sending user_id that is returned by the auth response, in sending bundle.authData.email at the end of the URL.
const list = (z, bundle) => {
var email=encodeURIComponent(bundle.authData.email);//Like this
const promise = z.request('http://mysite/list_data/'+email,
{
params: {}
});
return promise.then((response) => response.json);
};

right way to construct and accept GET request in Laravel with long parameter (array)

I am new to Laravel. I do not know the right way to construct and accept GET requests.
I need to send the following request (en and es are language codes):
translation/next-word/en/es
and in Controller I have
public function getNextWord($langfrom, $langto) {
However, now new requirement came and I also have to send a list of IDs (on my client side it is an array (for instance, [1,5,12,15]), but it could be long list (about 100 IDs). Thus I am not sure how to send this ID array to controller and also accept it in controller method.
My old client side request (without categories):
// var categories = [1,2,5,6,17,20];
var url = "translation/next-word/en/es";
$.ajax({
url: url,
method: "GET"
}).success(function(data){
...
});
For get, change your controller like this,
public function getNextWord() {
$langfrom = $_GET['langfrom'];
$langto = $_GET['langto'];
}
In ajax send the data like this,
$.ajax({
url: url,
method: "GET" ,
data: {langfrom:langfrom,langto:langto} <----- passing from GET
}).success(function(data){
...
});
If you wan to get in parameters like this,
public function getNextWord($langfrom, $langto) {
Then ajax should look like this,
$.ajax({
url: url +"/" + langfrom + "/" langto, <----- passing as parameter
method: "GET" ,
}).success(function(data){
...
});
In Laravel, you handle GET requests by making a route in your routes.php file and then a corresponding method in a controller class to actually handle the request. In your case, because you want to also pass in an unknown number of IDs, I would suggest making that into a query parameter. You can format that however you want, although I would suggest using something like commas to divide the data in your URL. So in the end, your URL would look something like this:
example.com/translation/next-word/en/es?categories=1,2,5,6,17,20
routes
Route::get('translation/{nextWord}/{from}/{to}', 'TranslationController#translate');
TranslationController
public method translate($nextWord, $from, $to, Request $request)
{
//get the categories passed in as a query parameter
$input = $request->all();
$categories = $input['categories'];
$categories = explode(',',$categories); //turn string into array
//actually translate the words here (or whatever you need to do)
$translated = magicTranslateFunction($nextWord, $from, $to);
//also you can now use the categories however you need to
//once you're done doing everything return data
return $translated;
}
Inside your javascript, you'll just want to turn your array of categories into a comma delimited string and pass that to make the URL I started the post with.
var categories = [1,2,5,6,17,20];
var categoriesString = categories.join();
var url = "translation/next-word/en/es?categories="+categoriesString;
$.ajax({
url: url,
method: "GET",
success: function(data) {
...
}
});
Edit - using $.ajax 'data' setting
Instead of appending the categories as a string to the URL, you can just pass in the array directly as part of the 'data' setting of your ajax call.
var categories = [1,2,5,6,17,20];
var url = "translation/next-word/en/es";
$.ajax({
url: url,
method: "GET",
data: {
"categories": categories
},
success: function(data) {
...
}
});
Laravel will actually convert this correctly to a PHP array, so you don't need to do any special parsing in your controller. Just take it in like normal and use it:
TranslationController
public method translate($nextWord, $from, $to, Request $request)
{
//get the categories passed in as a query parameter
$input = $request->all();
$categories = $input['categories']; //already a PHP array
//actually translate the words here (or whatever you need to do)
$translated = magicTranslateFunction($nextWord, $from, $to);
//also you can now use the categories however you need to
//once you're done doing everything return data
return $translated;
}

Backbone JS + Codeigniter Restful API and MYSQL Substring function not working

I have this BackboneJS Application where I use Codeigniter as Backend. I use the RESTful API to return data from my MySQL Database to the Frontend. As part of my application, I want to display Music artists Albums and the relevant tracks and the tracks duration. Right now, I get the track duration like 00:03:26 but I want it to display 03:26, so I made this MySQL-query where i use the SUBSTRING-method:
public function artist_tracks_get($artist_id)
{
$this->load->database();
$sql = "SELECT products.title AS album_title, products.genre AS album_genre, products.ccws_pro_id AS product_upc, track_title, SUBSTRING(track_duration, 4) AS track_duration FROM products
INNER JOIN track_albumn_information ON products.ccws_pro_upc = track_albumn_information.product_upc
AND track_albumn_information.artist_id = '".$artist_id."' LIMIT 0 , 30";
$query = $this->db->query($sql);
$data = $query->result();
if($data) {
$this->response($data, 200);
} else {
$this->response(array('error' => 'Couldn\'t find any artist albums!'), 404);
}
}
And inside my Backbone View I have:
serialize: function() {
var grouped = _.groupBy(this.collection.toJSON(), function(item) {
return item.album_title;
}), spanned = [];
_.each(grouped, function(item) {
var firstItem = item[0],
spannedItem = {
'album_genre': firstItem.album_genre,
'album_id': firstItem.album_id,
'album_title': firstItem.album_title,
'cover_image': firstItem.cover_image,
'digitalReleaseDate': firstItem.digitalReleaseDate,
'physicalReleaseDate': firstItem.physicalReleaseDate,
'pro_id': firstItem.pro_id,
'product_upc': firstItem.product_upc,
'tracks': []
};
_.each(item, function(albumItem) {
spannedItem.tracks.push({
'track_duration': albumItem.track_duration,
'track_title': albumItem.track_title
})
})
spanned.push(spannedItem);
});
return spanned;
}
When I run this query on my local phpmyadmin, I get the right result like 03:26 but when I test it online on my webserver, I get 00:03:26... What is the issue here? Is it the SQL version? Is BackboneJs unable to handle the SUBSTRING-method?
Please help! Thanks in advance...
Backbone has no idea what you are doing in MySQL so it's not Backbone having a problem with MySQL SUBSTRING().
If you wanted to avoid dealing with MYSQL, you could simply do
albumItem.track_duration.substr(3);
in the view to display it as "03:26".

JavaScript: Backbone.js populate collection of models

Here is what I have so far:
var Item = Backbone.Model.extend({
defaults: {
id: 0,
pid: 0,
t: null,
c: null
},
idAttribute: 'RootNode_', // what should this be ???
url: 'page.php'
});
var ItemList = Backbone.Collection.extend({
model: Item,
url: 'page.php',
parse: function(data) {
alert(JSON.stringify(data)); // returns a list of json objects, but does nothing with them ???
}
});
var ItemView = Backbone.View.extend({
initialize: function() {
this.list = new ItemList();
this.list.bind('all', this.render, this);
this.list.fetch();
},
render: function() {
// access this.list ???
}
});
var view = new ItemView();
Current (expected) json response:
{
"RootElem_0":{"Id":1,"Pid":1,"T":"Test","C":"Blue"},
"RootElem_1":{"Id":2,"Pid":1,"T":"Test","C":"Red"},
"RootElem_2":{"Id":3,"Pid":1,"T":"Test2","C":"Money"}
}
This successfully polls page.php and the backend acts on $_SERVER['REQUEST_METHOD'] and returns the required information, however I don't know why the collection is not filled.
In the parse function of ItemList it properly shows me all the output, but it does nothing with it.
I left some comments in the code for some more precise questions, but the main question is why doesn't the collection populate with the obviously received data?
Modify your parse method to:
parse: function(response){
var parsed = [];
for(var key in response){
parsed.push(response[key]);
}
return parsed;
}
To follow conventions, change list inside ItemView to model. Also in render():
render: function() {
var template = _.template("<div>some template</div>");
this.model.each(function(item){
this.$el.append(template(item.toJSON()));
}, this);
return this;
}
The parse method you're supposed to be returning the data after doing whatever necessary parsing is required for it.
The common use case for parse would be if you're sending back an object of a form like:
{ "id" : "NaN", "tasks": [ *all your models in a list here *] }
then you'd use parse like so:
parse: function (data) {
return data.tasks
}
Backbone then handles the rest.
Is there a particular reason why you're sending the data back in that dictionary format? It's not exactly clear how you intend to map that to each model of the collection. Is the key irrelevant? if so, you should be passing back a list of the objects in the values.(Although see note at bottom). If not, and you want to attach it to the models, it should be moved to the object you're using as a value and send back a list.
* Note: Don't actually send back a JSON list bare. There is an exploit for GET requests that relies on lists being valid javascript on their own, where a malicious site can use the Array object and override it to use a script tag to your API to use the users credentials to pull down whatever information is available in that call. Instead, when wanting to send back a list you should use something like this:
{ result: [*list here*] }
Then you just use the parse method above to extract the list.

Categories