jQuery-File-Upload(Blueimp) with custom ajax under October CMS - components

Trying to create a component under October CMS which should allow frontend multiple fileuploads. I try to integrate in already exiting form the Blueimp jQuery-File-Upload Plugin and because October CMS uses an integrated ajax Framework which allows data Submission to Component method I would use this ajax method instead what from default by Blueimp
so a normal fileupload looks like
$('#gallery').fileupload({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: 'path/to/controller'
});
but instead I would like to use something like
$('#gallery').fileupload({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
add: function (e, data) {
data.submit();
$.request('onUploads', {
success: function(data){
console.log(data);
}
})
}
});

You need to use the Request class from Laravel which OctoberCMS sits on top of. Basically you go to the code section of your layout file and add
function onUploads()
{
// Get the file
$file = Request::file('somefile');
// Code to do something with it
// enter code here
}
Based on what you are trying to achieve you can write appropriate code to upload it. For example, in my Social Login plugin i use methods of this class to fetch photos from the chosen Social network and create a relation between the plugin's Social model and the uploaded file so that a frontend user may output the photo as a display photo in their web app.
Another good way to do it would be to directly upload it into the themes directory by doing something like Request::file('somefile')->move(app_path() . '/themes/yourtheme/assets/uploads/'); but then you will need to add code to limit the upload size and also to fix the file names. Feel free to make a comment if you need help on achieving something particularly. gl hf

Related

How to structure external API calls for Node.js, express, ejs routing?

//API Call one
function receiveLocation(){
axios({
"method":"GET",
"url":"https://ip-geo-location.p.rapidapi.com/ip/check",
...
})
.then((response)=>{
return response.data.country.name;
})
.catch((error)=>{
console.log(error)
})
}
//API Call two
//API Call three
console.log(receiveLocation());
app.get("/", function(req,res){
var location = receiveLocation();//
//Then render all the data from my API calls such as location, currency,
//etc. in my landing page. Also use that data on the backend.
res.render("landing",{location:location});
});
I am currently trying to make a website that uses multiple API calls to get information such as location, currency, and other things of a user who loads the website.
I am attempting to receive all the information from the different API calls as I go through the get request route that allows a user to see the landing page. Firstly, I am not even sure if this is allowed. If it is allowed/standard practice, what am I doing wrong in this example. I am attempting to call a function that in the get route to the root page that returns the country of a visiting user. But after doing some console.log() debugging I see that that information is never being received in the get route. Last note: I want to use the info from the API calls both to change what the user sees, and for some calculations that would need to be run on the backend.
If this is not allowed/not standard practice, may someone explain what I should do instead/point in the right direction as to what I should learn to get a better understanding of what I am trying to do
What you are trying at the moment to do is not standard practice, you should lookup MVC for Express,there you will learn how to structure your backend code so that the GET Routes will be used as Views ( these will be your server getting some public files like html,css,javascript that will be passed some information from the Controllers,this is done by using some server-side renders like EJS).
I recommend taking this Udemy course https://www.udemy.com/course/nodejs-the-complete-guide/ for a full understanding,but if you don't have the time,lookup node.js mvc with express, there is plently information about this.

Can i use AJAX request to update the whole page like reqular http requests?

If i can update the whole page with AJAX when and why should i use regular http methods?
Can AJAX requests replace normal http methods?
i am using nodeJS expressJS
Yes, you can update the whole page using AJAX. Send request from user end and get back an JSON array from server containing all the information you want.
If you want to load data from .txt file or .html, then
$.ajax({ url: 'http://website/some'
, type: 'GET'
, dataType: 'html'
})
.done(function(data) {
$('#container').html(data);
})
.fail(function() {
console.log("Something went wrong!");
});
Just wondering why you are looking at AJAX when you need a complete reload.
Yes, definitely you can. But You will not ask this question once you know the use of AJAX.
For example, you will never ever update the whole page if you are using AJAX. For example, at least Navigation will remain the same and the body part will change. This is the use of AJAX and many web applications load like this. They keep navigation the same and then update rest of the web page.
You will have this kind of application where you will update the body of the page. You can use REST API to fetch the data in the form of JSON and then load this data using styling and Javascript framework like Angular, React, Backbone, etc.

React Node API Request Design Pattern

I need to make an API request to an external API using an API Key. I know how to make this API request in React by writing a onSubmit function. But since I have an API key that I want to keep a secret I am going to write a simple Node app to house env variables.
Besides messing around in node this is my first production experience with Node and I am wondering if my thought process is correct and if not, the better way to do this.
Most of this question will be pseudo code since I haven't started with the Node portion yet.
The idea is that from within the React component it would call the Node app who in turn would call the external API.
React -> Node -> External API
So the React component would be something like so:
handleSubmit: function() {
var data = this.refs.testData.getDomNode().value;
$.ajax({
url: '/my-node-endpoint',
dataType: 'json',
type: 'POST',
data: { test: data },
success: function(data) {
// Whatever success call I want to make
}.bind(this)
})
}
And then in my Node app it would like something like this:
app.post('/my-node-endpoint', function(req, res) {
// Store the values we are posting as JSON
// Start the post request
// On End tell the React component everything is ok
// Prosper
});
As always, thanks for any help that is offered.
Your thought process looks right to me.
If the API you are calling is from a different domain, you will have to build a wrapper on your node server like you did here. Unless the external API supports cross-origin requests with no domain restrictions (such as MapBox web services), you will have to do this.
Several improvements to your code:
As far as I know, you can use React.findDOMNode(this.refs.testData).value instead of this.refs.testData.getDomNode().value. getDomNode() is deprecated in v0.13.
For all the AJAX calls, you can use the Store concept in Flux. The store keeps the states of the data, including updating data through AJAX request. In your React UI code, you just need to call the methods of the store, which makes your UI code clean. I usually create a store class myself without using Flux.

Use dynamic express routes within another Express route

For a school project, I created a plugin system for an Express.js-Application in Node.js. The main page of the application should display a dashboard, where every root page of each plugin should be displayed in a div. Every root page is accessible over the pluginName/-route.
What I would like to do is the following: I wanna include the HTML-string of every home-route in the dashboard. But for this, I need to call the routes inside Node.js (like partials) and for some plugins I even have to provide some properties.
Does someone have an idea, how this could be implemented?
e.g. I have following route:
router.get('/pluginName', function(req, res) {
res.render(__dirname + '/views/home.handlebars', {
layout: __dirname + '/views/layouts/main.handlebars',
markup: markup // Pass rendered react markup
});
});
Now I want to pass the resulting HTML from this route into another route.
So far I had the following ideas:
Simply add the URLs of the plugins to a "data-ajax-url" attribute of the divs and load the stuff via AJAX.
Make an HTTP-Call to every route and append the result on server side (pretty nasty...).
Create a renderDashboard-function for every plugin, where I get the HTML using app.render(...) and then I append the result.
But I'm not really sure, which approach (if any) would be the nicest.

Add data to couchdb with jsonp response

Is there a way add data to a couchdb that runs on another domain and get back an response whether the operation was successfully or not? I know couchdb supports jsonp callback but can I add data with this approach?
No, you cannot currently do this. CouchDB's REST API requires a POST or PUT request in order to insert data, but JSONP only supports GET requests. So you can retrieve data from CouchDB across domains, but updates/inserts/deletes won't work.
You can use client-side javascript to make a form to do the POST, direct the output to an iframe, and use cross-window iframe messaging to get the result.
Of course, someone has already made a nice javascript library to do this. Get the code here:
https://github.com/benvinegar/couchdb-xd
Follow the instructions to push it as an additional database on your couchdb server. Then, on any site, include one not in the 'your-couch-server' domain, you can do the following (just try it in the javascript console):
jQuery.getScript(
"http://YOUR-COUCH-SERVER/couchdb-xd/_design/couchdb-xd/couchdb.js",
function() {
Couch.init(
function() {
var s = new Couch.Server('http://YOUR-COUCH-SERVER/');
var d = new Couch.Database(s,'YOURDB');
d.put(
"stackoverflow-test 1",
{ foo: 111, bar: 222 },
function(resp) {
console.log(resp);
}
);
}
)
}
);
The above presumes you have jquery is already loaded on the page. If not, you'll need to add it however you're currently interacting with the other page.
The library only works on modern browsers with window.postMessage() support, though a small patch may eventually allow older browsers to use it via src/hash communication.

Resources