how to reach database with javascript - javascript

I want to show some informations on site from database. But I know there is no way to connect to database with native javascript. And I read something about this is not a good method.
So I really curious about how developers show informations on sites from database? For example member name? It's in somewhere in the database. Site is coded with javascript. How can javascript reach member name info?

They use AJAX to send request to the back-end.
For example, javascript may ask special php script to return mebmer's name by id.
$.get( "sitename.com/script.php", {id: 125},
function( data ) {
alert( "The name is "+data );
});

You're looking for a scripting language. There is PHP, C#, ColdFusion, and many more options. You will probably want to use PHP because it's free, and it is included on most hosting services, but check with your host to see what they support.

You are correct connecting to a database from client-side JavaScript (I say client-side JavaScript because we now have node.js that is server-sider JavaScript) is a bad idea because you would need to send (expose) your connection information to the client; e.g. the username, password, database name, and DBMS engine would all be exposed to anyone that visited your site.
Most people that fetch information from a database in JavaScript code do so by sending AJAX (asynchronous GET, POST, etc. HTTP requests) to some server-side code that handles CRUD with the database. You can expose server-side code as a web-service, API, or have POST/GET methods in your server-side project that return information (usually in JSON or XML).

You can use an ajax call to a file written on php for example that exist on you server, for example look at the following code
<script src="jquery-1.11.1.min.js"></script>
<script>
//send query to bbdd (information is in the input with id="information")
//and sended when pressed the button with id="btn-send"
$(function(){
$("#btn-send").click(function() {
var url = "file_that_search.php";
$.ajax({
type: "POST",
url: url,
data: $("#information").serialize(),
success: function(data){
$("#html").html(data);//paste the data to the browser
}
})
return false;
})
})
</script>
then the file "file_that_search.php" has the retrieved data from the BBDD making something like
$search= "ID=" . $_POST['consult'];
$query = "SELECT * FROM database WHERE ".$search;

Related

Connecting DB and Ajax (no php)

I have to do a project as exam and I'm getting really troubled with this topic. My project is about a photoblog like Instagram. As in Instagram I want to get values from my DB and posting after the page has been loaded. So I've understood I need help from AJAX but every example I've found is about using PHP and I can't for my projects. Tools I can use are: HTML, CSS, XML, JQuery, AJAX, Servlet/JSP, DOM and JSON. I've found examples in PHP and I've tried to "translate" into Servlet/JSP but it (obviously) didn't work. This is my idea:
$.ajax({ type: "GET",
url: "Jspfile",
success : function()
{
// Here I would like to use the return value from db that I got by a servlet/jsp file
}
});
I'm using MySQL aS DB
You'll have to connect your Java applet to the database, then serialize the data from whatever object type your DB driver uses to JSON.
You then have to render the JSON in your "Jspfile" URL. Then, you just have to parse the JSON in your success / complete function in the jQuery request.

MediaWiki: How do I use an AJAX POST in JS to send data to a custom API extension (PHP)?

I've been stumped on this for a while. I've successfully created a MediaWiki API extension from which I'm able to extract data using an API url, but now I want to go the other way. I want to use JS to send a simple bit of data to the server for storage in a session variable (in PHP). I've experimented with something like the following:
$.ajax({
// start POST request
type: "POST",
// url to which the request is sent
url: "/",
// data to the server
data: { myvariable: 0 },
// Type of data
dataType: 'json',
// Funciton to be called if the request succeeds
success: function( data ){
console.log("POST successful with " + data);
}
})
What I don't fundamentally get is how to "pick up" the POSTed data in PHP. In my research, I came upon something saying I should look for $_POST['myvariable'] in PHP. Yet I'm not sure how or where I'd create something that would listen for such a POST from JS. It seems to me the easiest solution to this would be if I could write a method onto my API extension that simply assigns the value of the myvariable that's POSTed to the session variable whenever that thing is POSTed. I've written this method already, in fact, but it's unclear to me how I'd instruct AJAX to invoke it in PHP. I've also read that this type of thing may not be advisable for security reasons.
I've seen advice elsewhere suggesting I should do something in JS like:
var api = new mw.Api();
...and then use the Api object's methods to execute Ajax GET and POST requests. Well, I tried creating an instance of this object, and it throws errors on the console that say it's not a recognized function or something of that nature.
I'm rather new at all this, but I'm at my wit's end trying to figure out something that in theory ought to be very simple. Any suggestions?

How to hide the data in source code from the user

As a side project to learn Web Development, I'm writing a web app in Javascript that allows my fellow classmates type in our Class ID # to a search field. If they enter the correct Class ID, they will automatically be redirected to our Google Groups page. The only problem I'm seeing is that since I'm running multiple Google Groups for different classes that I'm taking, I don't know how to hide the javascript code.
Example in Pseudocode:
If (input === 12345){
redirect to (LinkToClass1GoogleGroupsPage.com)}
Else If (input === 12344){
redirect to (LinkToClass2GoogleGroupsPage.com)}
The problem here is if they right-click and view source code, they will clearly see what inputs I'm looking for. I'm new to Web Development and I would like to know what's the best way to implement something like this.
You cannot hide JavaScript code. If you have a secret, keep it on the server.
Anything on client-side environment is readable unless it is encrypted - what doesn't works with JavaScript. You can use a server-side environment to deal with that without leaving JavaScript with node.js, look this post.
Use an ajax request(jQuery or pure) to a node.js service or any other server-side language of your choice and keep those actions out of user's sight. This is safer, right and maybe only way to do that.
You cannot literally hide the data in JavaScript, unless you use a server-side language to redirect.
What you can do however is obfuscate your code, there are tools to help you do this.
http://javascriptobfuscator.com/
"LinkToClass2GoogleGroupsPage.com"
Results in
var _0x2ec6= ["\x4C\x69\x6E\x6B\x54\x6F\x43\x6C\x61\x73\x73\x32\x47\x6F\x6F\x67\x6C\x65\x47\x72\x6F\x75\x70\x73\x50\x61\x67\x65\x2E\x63\x6F\x6D"];_0x2ec6[0];
Probably the most secure way for this to be done would be to have a Server Side function that can be called via Ajax to return the link.
What type of Server Side code you use depends on your preferences.
For example ASP.NET Web Service, PHP, ASPX Web Methods.
Below is example Ajax Request Code using jQuery :
var o = new Object();
o.ID = input;
var x = JSON.stringify(o);
$.ajax({
url: 'SOME URL', //Path to the Server Side function (i.e. Php / ASPX Web Method / Web Service)
type: 'GET',
dataType: 'JSON',
contentType: 'application/json;charset=utf-8;',
data: x,
success: function (data) {
//Method returned without issue
redirect to (data.d)
//data is a JSON object that contains a "d" property, if your function returns a string then d will be the value of the string.
},
error: function (ajaxrequest) {
//Ajax call received an error.
}
})
This cannpt be done yet. HTML5 might have DRM implementations in the future but this will also depend on browsers opting in for this feature (Mozilla are against it for example).
Disable right click and ctrl button thats all you can do! :D

how to use mysql query inside the javascript, php

I have a JavaScript function onLoad a PHP page. Inside this JavaScript function, How can I use mysql query? Please Help me..
You can't really do that. JavaScript code runs in the browser, which (presumably) doesn't have access to your database server, and it doesn't have facilities for talking to remote databases anyway.
What you'd typically do is perform the SQL query from your PHP code, running on the server, and put the results into the page that it sends to the browser. If you want to use the results in JavaScript, you can make your PHP code generate a JSON string in a <script> tag so that the JavaScript code can just access a global variable that contains the data.
Or, you can use AJAX to load the data separately. This involves another HTTP request to a PHP page on the server, which runs the SQL query and sends back the results.
$(window).load(function() {
$.ajax({
method:'POST',
url:"ajax_page.php?branchcode="+branchcode,
success:function(data){
},
error: function (error) {
alert("Failed to load.. Kindly try again!!");
}
});
});
I have solved by using this AJAX, jQuery code.

Update twitter status without prompting user using pure JavaScript

I have web application where people can login from twitter and based on their preference and DOM events I need update their status on twitter. I have a good idea how to do this on server side, but for this project I am not using any server side code, So how can I do this by just javascript, #anywhere twitter api and twitter intents are taking me to no where because they prompt user for submitting the tweet which I dont want.
A pure Javascript solution to consume twitter API is not possible without compromising your consumer secret key. Twitter API authenticates every request using a HMAC-SHA1 token, the SHA1 token is generated using the public/private key assigned by twitter to your api account. If you plan to generate this token using a pure javascript SHA1 implementation then it means you will be exposing your private key in the javascript code which anyone can look at.
Even though technically its possible (provided you can find a javascript library which implements SHA1), its not advisable.
FYI, jQuery.Ajax method does let you modify the headers of the ajax request by tapping in to the beforeSend(jqXHR, settings) method.
You should be able to do this with an AJAX POST request to the REST API. Documentation: https://dev.twitter.com/docs/api/1/post/statuses/update
You target the URL http://api.twitter.com/1/statuses/update.format, where format can be either xml or json, and reflects the format of the response. Required data is the status text, and there are several optional parameters which I won't list here. This only works for the currently authenticated user.
An (untested) example using jQuery:
var message = "This is a tweet, there are many like it but this one is mine";
$.ajax({
type: "POST",
url: "http://api.twitter.com/1/statuses/update.json",
data: "status="+message,
datatype: "json"
});

Categories