Reputation: 301
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?
Upvotes: 0
Views: 9137
Reputation: 71
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
Upvotes: 4