JavaScript retrieve data from DB - javascript

In my database I have table Person (id, name, last_name, phone_number). I do something like this:
$queryPerson = mysqli_query($con, 'SELECT * FROM Person');
while ($person = mysqli_fetch_array($queryPerson)) {
echo '<option value="'.$person["id"].'">'.$person["name"].' '.$person["last_name"].'</option>';
}
I want to use javascipt function to copy selected value from the select to textboxes:
function copyPerson(data) {
document.getElementById["name"].value = data.value;
}
...but instead of their id I want their names and last names and phone numbers to be displayed in textboxes. Now I came up with this idea to read the value from an option, send query to DB SELECT * FROM Person WHERE id = ID_FROM_SELECT and then recieve the data I want to recieve. I'm not sure if it's a good idea though.
In before: yes, I need to have $person["id"] as a value of an option.
My question is: sending the query to DB is a good idea - if yes, how can I send a value from javascript to MySQL, if no - what is a better solution?
EDIT: Apart from #Thanos Tourikas answer, I found this link to be helpful: http://www.w3schools.com/php/php_ajax_database.asp

Generally it is not a good idea to send the query.
The solution would be to send the id with ajax and have a php page that handles that request.
In that php page, you just need to get the id, which is sent as a parameter to the request, and construct there the db query. Then just echo the result as a json object and handle that response with JavaScript.
First, use jQuery to make a request to the server sending the person id:
$.ajax({
url: 'url_that_handles_request.php',
data: { id: person_id },
dataType: 'json',
success: function(response){
// here you handle the response from server.
// you can access the data returned doing something like:
var id = response.id;
var name = response.name;
}
});
And then, you need to provide a php page to handle the ajax call:
$person_id = $_POST["person_id"];
// here you make the query to the database using the person id
// and then just echo the db response as a json object
echo json_encode($db_response);
Here are some useful links
A quick tutorial for jQuery and how to install it:
http://www.w3schools.com/jquery/default.asp
A quick tutorial for jQuery ajax:
http://www.w3schools.com/jquery/jquery_ajax_intro.asp
Some references in the ajax methods that jQuery provides:
http://www.w3schools.com/jquery/jquery_ref_ajax.asp
A tutorial about json:
http://www.w3schools.com/json/
And finally a documentation about json_encode php function:
http://php.net/manual/en/function.json-encode.php

Related

How to pass data from Laravel View to Ajax or Javascript code without html div (id or class) - Laravel 5.3

So, currently I am passing values stored in Database MySQL to View (using Controller). I do simple querying ModelName::where()->first();.
I have my data right now in View. I want to use that data in Ajax or Javascript code that I am writing.
I can have 46 values and one way to do this is to have <div id="field1"></div> for 46 times set div style to display:none in css and in Javascript use document.getElementById('field1'); to access the values and finally, do whatever I want to do with it.
But I find this quite long and un-necessary to do as there is no point of printing all the values in html first and then accessing it. How can I directly get {{$data}} in Javascript?
myCode
public function index(Request $request){
$cattfs = Cattf::all();
$cattts = Cattt::all();
$cattos = Catto::all();
return view('/index',compact('cattfs'));
}
View
Nothing in the view. and I prefer it to be none.
Javascript and Ajax
$(document).ready(function()
{
init();
});
function init(){
my_Date = new Date();
var feedback = $.ajax({
url:url,
dataType: "JSON",
type: "GET",
}).success(function(data){
console.log(data);
//I have some data called data from url
//I want some data from controller like: cattf,cattt,catto
//I will combine url data and cattf and do simple arithmetic to it
//finally output to the view.
}).responseText;
}
One good way would be to actually make a small API to get your data. Let's say you wanted to retrieve users.
In the api.php file in your route folder:
Route::get('/posts', function () {
return Post::all();
});
and then you just need to use http://yourUrl.dev/api/posts as your URL sent in your .ajax() call to work with what you need.
I found best solution use this: https://github.com/laracasts/PHP-Vars-To-Js-Transformer
It takes values from controller directly to Javascript.

How to send an Array via URL and extract it in PHP?

Here is a script.
It provides some select inputs which allow picking from various types of options. When the submit button is pressed it records the data in mats and pushes the mats array into an array called materialsUsed. Everytime the submit button is clicked a new array is added in materialsUsed.
I want to know how to send the materialsUsed array through a URL to php to extract the data there and insert it into an array created in PHP.
var mats = [name= "", thick= "", size= "", quantity= 0, price= 0];
mats.name = document.getElementById("mat").options[document.getElementById("mat").selectedIndex].value;
mats.thick = document.getElementById("thick").options[document.getElementById("thick").selectedIndex].value;
mats.size = document.getElementById("size").options[document.getElementById("size").selectedIndex].value;
mats.price = parseFloat($('#priceto').val()).toFixed(2);
mats.quantity = parseInt($('#quant').val());
materialsUsed.push(mats);
If you would like to simply load them as GET values into the URL just set them directly in the URL using location.href. Then simply use $__GET (IE: $__GET['mat']) in PHP to grab values.
var baseURL = "http://yourdomain.com";
window.location.href = baseURL + "?mat=" + mats.name + "&thick=" + mats.thick etc...
First you have to properly prepare your mats array and convert materialsUsed array into JSON format. Then you can call an ajax function like below, to send it to the php script.
var jsonString = JSON.stringify(materialsUsed);
$.ajax({
type: "GET",
url: "your_script.php",
data: {data : jsonString},
success: function(){
alert("Successfully sent the data!");
}
});
From the your_script.php file, you can perform this to extract the array.
$data = json_decode(stripslashes($_GET['data']));
Important
When using GET method, the amount of the data (length of url) is
limited. So, if your materialUsed array is too huge, you should use
POST method instead.
I think what you're looking for is making an ajax call to your php script providing your js array as its data.
You should listen for the form submission event in your javascript and launch an AJAX call to your PHP script providing your array. You may send your array via the URL (query string) using a GET or in the request body using a POST (that's an option you specify in your AJAX call). Then you would just retrieve your array in your php script an do whatever you want with it.
I suggest you read more on form submission events and AJAX calls in javaScript.
Quick hint : if you have the possibility to do so, try using jQuery as AJAX is way easier to use with jQuery.
You are trying to use associative array, but it's not possible in Javascript as far as I know.
I'd say the best way to do that is creating a object, parsing to json and sending to php. Does't look that hard.

Using JSON to store multiple form entries

I'm trying to create a note taking web app that will simply store notes client side using HTML5 local storage. I think JSON is the way to do it but unsure how to go about it.
I have a simple form set up with a Title and textarea. Is there a way I can submit the form and store the details entered with several "notes" then list them back?
I'm new to Javascript and JSON so any help would be appreciated.
there are many ways to use json.
1> u can create a funciton on HTML page and call ajax & post data.
here you have to use $("#txtboxid").val(). get value and post it.
2> use knock out js to bind two way.and call ajax.
here is simple code to call web app. using ajax call.
var params = { "clientID": $("#txtboxid") };
$.ajax({
type: "POST",
url: "http:localhost/Services/LogisticsAppSuite.svc/Json/GetAllLevelSubClients",
contentType: 'application/json',
data: JSON.stringify(params),
dataType: 'json',
async: false,
cache: false,
success: function (response) {
},
error: function (ErrorResponse) {
}
I have written a lib that works just like entity framework. I WILL put it here later, you can follow me there or contact me to get the source code now. Then you can write js code like:
var DemoDbContext = function(){ // define your db
nova.data.DbContext.call(this);
this.notes=new nova.data.Repository(...); // define your table
}
//todo: make DemoDbContext implement nova.data.DbContext
var Notes = function(){
this.id=0; this.name="";
}
//todo: make Note implement nova.data.Entity
How to query data?
var notes = new DemoDbContext().notes.toArray(function(data){});
How to add a note to db?
var db = new DemoDbContext();
db.notes.add(new Note(...));
db.saveChanges(callback);
Depending on the complexity of the information you want to store you may not need JSON.
You can use the setItem() method of localStorage in HTML5 to save a key/value pair on the client-side. You can only store string values with this method but if your notes don't have too complicated a structure, this would probably be the easiest way. Assuming this was some HTML you were using:
<input type="text" id="title"></input>
<textarea id="notes"></textarea>
You could use this simple Javascript code to store the information:
// on trigger (e.g. clicking a save button, or pressing a key)
localStorage.setItem('title', document.getElementById('title').value);
localStorage.setItem('textarea', document.getElementById('notes').value);
You would use localStorage.getItem() to retrieve the values.
Here is a simple JSFiddle I created to show you how the methods work (though not using the exact same code as above; this one relies on a keyup event).
The only reason you might want to use JSON, that I can see, is if you needed a structure with depth to your notes. For example you might want to attach notes with information like the date they were written and put them in a structure like this:
{
'title': {
'text':
'date':
}
'notes': {
'text':
'date':
}
}
That would be JSON. But bear in mind that the localStorage.setItem() method only accepts string values, you would need to turn the object into a string to do that and then convert it back when retrieving it with localStorage.getItem(). The methods JSON.stringify will do the object-to-string transformation and JSON.parse will do the reverse. But as I say this conversion means extra code and is only really worth it if your notes need to be that complicated.

How can I use jQuery to run MySQL queries?

Is it possible to run a MySQL query using jQuery? I'm trying to emulate the functionality of voting on SE sites.
The vote counter on SE automatically updates without the need to reload the page (which is what I currently have, a hidden form that re-submits to the current page but runs a small block on PHP that updates the score of a question in the database). I'm assuming that is being done using Javascript/jQuery seeing as it is dynamic.
How can I do this? Is there a library which makes it easy and simple (like PHP)?
You can use ajax to call a server page (PHP / ASP /ASP.NET/JSP ) and in that server page you can execute a query.
http://api.jquery.com/jQuery.ajax/
HTML
<input type='button' id='btnVote' value='Vote' />
Javascript
This code will be excuted when user clicks on the button with the id "btnVote". The below script is making use of the "ajax" function written in the jquery library.It will send a request to the page mentioned as the value of "url" property (ajaxserverpage.aspx). In this example, i am sending a querystring value 5 for the key called "answer".
$("#btnVote").click(function(){
$.ajax({
url: "ajaxserverpage.aspx?answer=5",
success: function(data){
alert(data)
}
});
});
and in your aspx page, you can read the querystring (in this example, answer=5) and
build a query and execute it againist a database. You can return data back by writing a Response.Write (in asp & asp.net )/ echo in PHP. Whatever you are returning will be coming back to the variable data. If your query execution was successful, you may return a message like "Vote captured" or whatever appropriate for your application. If there was an error caught in your try-catch block, Return a message for that.
Make sure you properly sanitize the input before building your query. I usually group my functionalities and put those into a single file. Ex : MY Ajax page which handles user related stuff will have methods for ValidateUser, RegisterUser etc...
EDIT : As per your comment,
jQuery support post also. Here is the format
$.post(url, function(data) {
alert("Do whatever you want if the call completed successfully")
);
which is equivalent to
$.ajax({
type: 'POST',
url: url,
success: function(data)
{
alert("Do whatever you want if the call completed successfully")
}
});
This should be a good reading : http://en.wikipedia.org/wiki/Same_origin_policy
It's just a few lines in your favorite language.
Javascript
$.post('script.php', { id: 12345 }, function(data) {
// Increment vote count, etc
});
PHP (simplified)
$id = intval($_POST['id']);
mysql_query("UPDATE votes SET num = num + 1 WHERE id = $id");
There are many different ways to accomplish this.

Manipulate form data before it's sent with jQuery

I want to encrypt some data in a form using jQuery before it's sent to the server, it can be a MD5 hash. It is a small project, so I don't really need to use SSL.
I have the following JavaScript code where I use $.md5 in the password confirmation info:
$(document).ready(function() {
var dataToSend = {};
dataToSend['action'] = 'signup';
dataToSend['name'] = name.val();
dataToSend['email'] = email.val();
dataToSend['confsenha'] = $.md5(pass2.val());
var options = {
target: '#error',
url: 'insert.php',
beforeSubmit: validate,
data: dataToSend,
success: function(resposta) {
$('#message').html(resposta);
}
};
$('#customForm').ajaxForm(options);
});
The problem is that the data is being duplicated. I tought that overwriting the data being sent by using the var dataToSend would make ajaxForm send only data in that map. But besides sending data from dataToSend, it also sends data from the form, so what I wanted to encrypt using MD5 appears both encrypted and clean. This is an example of what goes in the request:
usuario=user&email=user%40email.com&senha=12345&confsenha=12345&send=&action=signup&name=user&email=user%40email.com&confsenha=d41d8cd98f00b204e9800998ecf8427e
I know I have to define the a function beforeSerialize, but I don't know how to manipulate form data. Can anyone tell me how to do that?
As per the documentation on the plugin site:
data
An object containing extra data that should be submitted
along with the form.
The word along is the crux.
So when you pass data as a part of the options object that data is serialized and is sent along with any data/input elements values that are part of a form.
A better approach would be to hash the password value and assign it to the same field or another hidden field in the beforeSubmit handler(in your case the validate function) and remove the dataToSend object totally.
Something like:
Without any hidden element:
function validate(){
//Other Code
pass2.val($.md5(pass2.val()));
}
With a hidden element in the form:
function validate(){
//Other Code
$("#hdnPass").val($.md5(pass2.val()));
pass2.val("");
}

Categories