Angular 2 with CodeIgniter - javascript

I searched a lot but unable to find the solution for this.
In angular 1.x, I used to include js in php pages and load the pages from server side code like CodeIgniter controller.
In angular 2.x, I unable to figure out that how I use server side features like $_SESSION?
e.g. I want to insert the data to mysql table and I will send data using POST service of Angular 2. How can I achieve that which user is logged in and created that record??
$city = $this->input->post("city");
$specialty= $this->input->post("specialty");
$data = array("city"=>, "specialty"=>$specialty, "createdBy"=>$this->session->userdata("userid"));
$this->db->insert("citywise", $data);
How to get this $this->session->userdata("userid"); because application is loading at client and everything is handling like REST services.
Using localStorage I can get login data on client browser but what about server?

Use JWT(Json Web Token) for the same purpose
refer this link

Related

What's the best/most efficient way to send data from Rails to JavaScript in a Slim view template?

I have researched how to send data from Rails to JavaScript in a Slim view template, and the most accepted method is to declare a Ruby section on the Slim template to get the data from the controller, and then declare a JavaScript section to store that data into a window variable, and then load the JavaScript pack that's going to use that data.
The data is needed to build a JavaScript snippet that will go in the <head> of our app.
Here's an example of what I'm doing (this is the app/views/layouts/_my-template.html.slim file):
ruby:
myDataFromRails = #my_data.to_json.html_safe
javascript:
window.myData = #{myDataFromRails};
- include_javascript_pack 'my-pack'
The problem with this method is that all the data coming from the Rails backend is available for anyone that inspects the code or types window.myData in the developer tools console, which is not ideal...
Another option will be to query the backend from the JavaScript snippet itself, using an HTTP request, but this doesn't look like an efficient way of getting the data from the backend.

How to connect laravel api with pure html website

Since I am new to laravel api, I don't know hot to connect laravel api to html endpoint. My laravel api is working well and html web pages also completely finish. I just want to connect them together... Please explain how to connect these two.
Thank you
I would suggest two ways to go about this but it all depends on what your API does. If you are looking to serve the HTML with Laravel and have some parts of the application loaded by Laravels view() method, you'd basically need to break your HTML into blade files in resources/view folder and call the blade files via view() in controller to load the desired page.
However if you are looking for a separation of view and API where API is called by the view only for some information, you'd need to utilize AJAX via JavaScript to make a call to the API endpoint and retrieve the data (JSON) for use in your HTML site.
I use axios a lot and here is a sample call:
axios.get(url).then(response => { // do whatever here with the response data });
I'm not sure I understand you. But it reads like you developed your Laravel Application (PHP) and HTML separately. Laravel uses Blade (see: https://laravel.com/docs/7.x/blade) as a template engine into which you can inject PHP objects. Basically, the call of a web page (more or less) works like this:
The user is calling the url
URL goes to the routes/web.php
in this file you can call e.g. a controller
the controller called via (e.g.)
return view('my.site.nice-site', [ key => value]);
blade starts and displays the page to the user with the given key as variable.
I hope this helps you a bit. Otherwise I recommend, just to get started, the documentation from Laravel or YouTube.

Is there a way to send data from HTML (using ejs template engine) to Node.js?

I am currently working on my self-project using Node.Js (Express) + MongoDB + Javascript/Jquery + HTML (using EJS as my template engine).
Currently I have some knowledge of sending data from Node.js router to Views and sending form data from Views back to router using "POST" and "GET" method.
I was wondering if there are other methods of sending a data from Views to Node.js router without going through
<form action="/" method="POST">
...
</form>
methods...
I have no knowledge on Angular2 and REACT..
For example, I am trying to send back the updated data from Views (probably using Jquery's editable() plugin to simply edit a text that was generated from MongoDB and send the updated contents back to server so I could update MongoDB
and save contents based on updated contents.
I feel like using a form should be only done once when I want to add new stuffs into DB...please help me out! Some of the stuffs I am asking are vague but these are the best I can explain. Or learning Angular2 is the best approach Lol ?
It sounds like you want to learn about $.ajax (if you're using Jquery) or XMLHttpRequest (if you aren't). That is significantly more versatile than forms (though you still should use a form to hold the entry fields; just don't give it an action if you're using a JavaScript-based AJAX call instead).
If updating an existing entry, you probably want the PUT method.

node js, json, sql, tables

hey everyone I am working with nodejs and express framework. I am trying to design a client side page which can be used to enter the form data into database i.e Mysql.So far I have succeeded to enter and retrieve the data from the database. Now I want to show this result in a tabular form where I can edit or delete the records dynamically. But I am unable to arrange the data into datatables. I am using json.stringify to pass the results to client side. The results are showing in this manner <"result:323 id=:321">
You can send the html page with the desired table as response instead of <"result:323 id=:321">. This is not advisable, though. Please refer to client side scripting tools like angularjs or reactjs

How to use JavaScript/Ajax and Python to edit local SQL database?

I've developed the front-end of a web site using JavaScript.
I have a button that when it's clicked retrieves an integer value from another object on the website.
I have a local SQL database. How do I make SQL calls when this button is clicked?
I've seen answers with JavaScript/Ajax and PHP, but I don't want to use PHP.
Using JavaScript only, can I open a local SQL db and make SQL calls? If yes, how?
If I can't do this using JavaScript only, can I use JavaScript/Ajax and Python? If yes, please post a reference or simple example.
Technically it is possible to connect to a database using client-side JavaScript. However, as others have already pointed out, doing so is considered to be really bad practice for a few reasons - the most important of them being security.
When the browser is asked to load a certain page it will go ahead and ask the server for the content that is found at that URL. This means HTML files, external JavaScript files, images, stylesheets and other resources that are needed in order for the page to get rendered. Since the user has access to the these files, especially your JavaScript code, it means he has access to your database credentials. You could try to minify/obfuscate the code, but that won't make it any safer.
If you do understand all the consequences and for some reason you still want to do it, take a look at this example.
The best way to go at it is to have a server handle the interaction with the database. Depending on your language of choice, you could build that part of the application using PHP (among with an HTTP server such as Apache), Java, Python and so on. You could even use JavaScript (see Node.js).
Since you asked for a Python snippet, here's one that connects to a MySQL database and creates an HTTP server that listens for connections on port 8080. For each GET request it will receive, the script will query the database and send back the result as text/html.
#!/usr/bin/python
import MySQLdb
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
PORT_NUMBER = 8080
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query using execute() method
cursor.execute("SELECT VERSION()")
# Fetch a single row using fetchone() method
data = cursor.fetchone()
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write(data)
return
try:
db = MySQLdb.connect(host="localhost", user="root", passwd="yourpwd", db="pw_exam")
server = HTTPServer(('', PORT_NUMBER), myHandler)
print 'Started httpserver on port ' , PORT_NUMBER
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close()
You can't do this from the javascript in the browser for a simple reason - if your database is available to your javascript code, it is also available for any web site user. And someone will just delete all your data or will replace it with something funny.
That is why we usually also have the server-side application and it can basically be in any language - php, python or javascript.
And there are frameworks and libraries to simplify your job also for any language.
For example, for python you can use flask and sqlalchemy.
If you want javascript everywhere, then use nodejs on the server and expressjs as server-side framework is one of most popular options for node. And you can find node.js packages to make SQL queries to your database too.
The general flow of your application can look like this:
Your client-side application is opened in the browser and it needs some data from the database
It sends the AJAX request to the sever
Server makes a database request and returns the data as json
Client-side application displays this data
It works similar when data need to be modified.
The difference here is that your database is "covered" by server side, so you can be sure that only allowed operations are performed.
Like nobody is able to drop the database, or only a registered user can edit the profile data (and only own profile data editing is possible), etc.
JQuery is a brilliant way to create live Database feeds in Website development. You can simple import the JavaScript files from CDN or Google or download and use it here: https://jquery.com
Front end:
$(document).ready(function(){
$("#idHere").click(function(){
var testdata = document.getElementByID("#idHere").value;
var anothertestdata = document.getElementByID("#idHere").value;
$.ajax({
url: "/inc/Database.php",
data: {
example: testdata,
anotherexample: anothertestdata
},
success: function( data ) {
$( "#idHere" ).html( "<strong>" + data + "</strong> " );
}
});
});
});
PHP file:
if(isset($_GET['testdata'])):
$db = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
$query = "SELECT * FROM TABLE";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_array($result)):
echo $row['CollumnName'];
endwhile;
$db->close();
endif;
Anything echo'd will show in the response.
Using JavaScript to open a Database is hard, long and has MANY security issues. I would not recommend in doing so.

Categories

Resources