EDITED:
SQL
$valuefromjs = $_REQUEST['var'];
$result6 = "SELECT DISTINCT $valuefromjs FROM persons ORDER BY $valuefromjs ASC";
$result7 = mysql_query($result6);
$num = mysql_num_rows($result7);
$dataRanges[0] = array('dataRanges');
for ($i=1; $i<($num+1); $i++)
{
$dataRanges[$i] = array( (int) mysql_result($result7, $i-1) );
}
echo json_encode($dataRanges);
HTML
<select id="combo2" class="combo" data-index="2"></select>
jQuery
$('#1combo').on('change', function () {
var jsonVar = $.ajax({
url : "visits/comboquery.php?var="+$(this).val(),
dataType: "json",
async: false,
success: function(response) {
}
}).responseText;
for (var i=1; i<objVar.length;i++)
{
$('#combo2').html("<option value="+objVar[i]+">"+objVar[i]+"</option>");
}
});
QUESTION:
I have an array with query results. Now i need that results be the combo2 options, what is wrong?
To my understanding the choice from combo1 will define which query to run for building combo2.
The issue: your PHP for building the combo2 is parsed at the server side i.e. the PHP code is always finished executing by the time the page reaches the user's browser and your javascript begins to execute.
If you have a finite set of possible queries that can generate the seconds combo (which should be the case since combo1 has a finite number of options), you can create all of them, each with a different id, and maintain them hidden (css "display: none").
<select id="firstCombo2" class="combo2">
...
</select>
<select id="secondCombo2" class="combo2">
...
</select>
etc.
Now, when the user makes a selection from combo1, you can decide which one of the hidden combo2's you are going to display (css "display: block").
$('select#combo1).on("change", function(){
$('select.combo2').css('display','none'); //hide all combo2's
if($(this).val()=='Opt1'){
$('select#firstCombo2').css('display','block');
}else if($(this).val()=='Opt2'){
$('select#secondCombo2').css('display','block');
}
}
You should use AJAX in order to solve your problem.
on combo1 onChange call an AJAX call to your server and send selected value of combo1.
Then in your php code run query with value received from AJAX request and construct a new combo box with options in string and echo back that string. You can use that AJAX response to populate new combo2.
Related
Using Autocomplete text box to retrieve the data from the MySQL database table. my Ajax coding is working to retrieve the small amount of data. In my database table, I have more 300,000 records. The coding is not working when I used large data.
Please give suggestion about to retrieve a large data.
Which method is best to retrieve the data.
See my coding. It works fine to retrieve a small amount of data
<input type="text" name="protein_name" id="protein_name">
$("#protein_name").keypress(function (e){
var protein_name = $("#protein_name").val();
if(protein_name != "") {
$.ajax({
url: '<?php echo base_url(); ?>/index.php/Protein_Main/protien_search',
data: {protein_name: protein_name},
dataType: "json",
type: "POST",
success: function (res) {
$("#protein_name").autocomplete({
source: res
});
}
});
} });
PHP Coding
$query = $this->db->query("SELECT `Name_of_the_Protein` FROM `protein` WHERE Name_of_the_Protein Like '".$protein_name."%'");
$protein = $query->result();
echo json_encode($protein);
Autocomplete requires a few things.
An input element
<input type="text" id="nmRecipientSearch">
A couple of local javascript arrays:
(One containing a list of potential selections, and another with numeric unique ids corresponding to each selection)
var aryRecipientsFull=["Aaron","Adon","Andrew"];
var aryLrId=["1","2","3"];
A javascript .autocomplete handler bound to the input element:
$( "#nm_recipient_search" ).autocomplete({ source: aryRecipientsFull,
select: function( event, ui )
{
var numPosition,numLrId = 0;
//Find the index position within the array for the selected item (e.g. Adon)
numPosition=aryRecipientsFull.indexOf(ui.item.label);
//Set a variable to the numeric value corresponding to the selected item (e.g. 2)
numLrId=aryLrId[numPosition];
//Populate a hidden input field (nm_lr_id) to the numeric value
$('#nm_lr_id').val(numLrId);
//Set the focus to the next field once a selection has been made
$('#nm_text').focus();
}
});
A CSS style to ensure the autocomplete results appear above everything else:
ul.ui-autocomplete
{
z-index: 1100;
}
A couple of things to consider:
I'd recommend starting off using static arrays just to ensure that the UI looks okay
If you need to (re)populate the arrays dynamically then you may need to bind a .keyup event to the search field, perform an AJAX call to a PHP page which then does a query as you've suggested, but make sure that you limit the number of resulting records (perhaps 10 or 20 records).
Simply add "LIMIT 20" to the end of your SELECT query to achieve this.
I hope that helps.
I am developing a web application and i am stuck with a problem.
i have two drop-down list, one is dynamically populated from my db, while the the other is static html.
When a user selects an item form the dynamic drop-down and select an item from the static html drop-down, and clicks submit on the form, I would like the dynamic selected list item to print out the entire selected row in the db.
here is my code sample
if ($contactc =="Yes"){
$result = mysql_query("SELECT * FROM company_details where comid = '$selectsector'");
while ($row = mysql_fetch_array($result)){
echo $row["fname"]." ".$row["comname"]."<br/>";
}
}
maybe this is what you wanted, though you will have to use JQuery
HTML
<form id="when_user_clicks_submit_button">
<input class="data_to_send" type="text" value="MySQL Selection data"></input>
<input type="submit" value="Submit"></input>
</form>
JavaScript|JQuery for Ajax Request:
document.getElementById('when_user_clicks_submit_button').onsubmit = function() {
$.ajax({
type: "POST",
url: "php_code_script.php",//php script location
data: { "data_from_form": data_to_send }, //data to send in JSON format
success: function(data) { //callback if the script execution is successful
$('<p>' + data + '</p>').appendTo('body');//this returns the selected information from the MySQL database and inserts it somewhere, make sure to echo or print the selected data inside the php script.
}
)}
};
PHP
if($_POST['data_from_form']) {
if ($contactc =="Yes"){
$selectsector = $_POST['data_from_form']; //gets the sended data from the form page to use for selection in the MySQL database
$result = mysqli_query("SELECT * FROM company_details where comid = '$selectsector'");
while ($row = mysqli_fetch_array($result)){
echo $row["fname"]." ".$row["comname"]."<br/>";
}
}
}
Maybe this is sort of what you wanted, you basically send the information you want to use to select from the database, the php script then handles it and echoes the selected information from the database, that data then returns to the form page where it becomes the value pf an DOM Element(HTML tag). This is just to give an example of what you maybe want, I didn't think about security or anything(I don't know much about it yet). Note I also changed the mysql to mysqli to make it more compatible with newer versions of PHP because mysql is no longer supported in newer versions or for the future.
This is what I'm trying to achieve, but my Googling hasn't helped:
I have a button that adds a new row to a table dynamically. I also add a select component to a cell with the same action all in javascript. I'd like for that select component to populate with values from a sql select statement. Of course I don't want to define the connection to the DB in the JavaScript. So I was wondering if there was a way I could call a PHP function to retrieve the values then store it in variable within JavaScript.
PS I understand that PHP is server side as opposed to JS. But surely this is possible.
here's a simple implementation of such a thing using jQuery's ajax and php.
html
<select data-source-url="/category/list"></select>
javascript using jQuery
$("select[data-source-url]").each(function(){
var url = $(this).attr("data-source-url");
var el = $(this);
$.get(url, function(data){
for (i=0;i<data.length;i++){
el.append("<option>" + data[i] + "</option>");
}
},"json");
});
category/list endpoint (a php script)
$list = array();
$list[0] = "category 1";
$list[1] = "category 2";
$list[2] = "category 3";
$list[3] = "category 4";
$list[4] = "category 5";
echo json_encode($list);
a little explanation: what happens is a request being made via the JavaScript client to a php script, which returns an array of values in JSON (which is basically a javascript data-structure), those values are added to the select box dynamically.
Please note that on initial load of the page, the select box will be empty.
yes ofcourse you can. for storing s php variable in a js ariable you can do like this.
before storing it into js variable store the required value in your php variable
var value = '<?php echo $value;?>';
Javascript cannot connect directly to a database.
You want AJAX. A basic flow for this functionality looks like this.
Create a PHP script that connects to the database and gets the options for your select element (let's call it options.php). This script should fetch the options from the database and output them as a JSON array.
In your javascript, you would create an ajax request to options.php. With the JSON data returned from that script, you would loop over each element and create and append a corresponding option element to the dom inside of your select element.
Also consider using jQuery. It greatly simplifies ajax and provides a cross-browser solution.
Option 1
Pass a php array with all possible values to the client side using something like this on the client side:
var opt_values = [<?php echo $php_values; ?>]; //javascript array
or
var opt_values = <?php echo json_encode($php_values); ?>; //json object
Option 2
Another way is making an ajax request. Write a php function that return a JSON object and then you can manipulate the result using jQuery ajax method:
PHP function:
$json = array();
$result = mysqli_query ($connection, $query);
while($row = mysqli_fetch_array ($result))
{
$bus = array(
'id' => $row['id'],
'text' => $row['name']
);
array_push($json, $bus);
}
return = json_encode($json)
Jquery
$('#button-id').click(function(){
//adds a new row to a table dynamically
$.ajax({
type: "get",
dataType: "json",
url: "/get_values.php",
success: function (response) {
var $el = $("#myselect"); //get the select
$el.empty(); // remove old options
//Append the new values
$.each(response, function(key, value) {
$el.append($("<option></option>")
.attr("value", value.id).text(value.text));
});
}
});
});
Just thought i'd put it out there since w3schools is my friend and i kinda follow what they're saying in this post.
W3Schools PHP & AJAX communication
Coming from Adobe Flex I am used to having data available in an ArrayCollection and when I want to display the selected item's data I can use something like sourcedata.getItemAt(x) which gives me all the returned data from that index.
Now working in php and javascript I am looking for when a user clicks a row of data (in a table with onClick on the row, to get able to look in my data variable $results, and then populate a text input with the values from that row. My problem is I have no idea how to use javascript to look into the variable that contains all my data and just pull out one row based on either an index or a matching variable (primary key for instance).
Anyone know how to do this. Prefer not firing off a 'read' query to have to bang against the mySQL server again when I can deliver the data in the original pull.
Thanks!
I'd make a large AJAX/JSON request and modify the given data by JavaScript.
The code below is an example of an actual request. The JS is using jQuery, for easier management of JSON results. The container object may be extended with some methods for entering the result object into the table and so forth.
PHP:
$result = array();
$r = mysql_query("SELECT * FROM table WHERE quantifier = 'this_section'");
while($row = mysql_fetch_assoc($r))
$result[$row['id']] = $row;
echo json_encode($result);
JavaScript + jQuery:
container.result = {};
container.doStuff = function () {
// do something with the this.result
console.debug(this.result[0]);
}
// asynchronus request
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(result){
container.result = result;
}
});
This is a good question! AJAXy stuff is so simple in concept but when you're working with vanilla code there are so many holes that seem impossible to fill.
The first thing you need to do is identify each row in the table in your HTML. Here's a simple way to do it:
<tr class="tablerow" id="row-<?= $row->id ">
<td><input type="text" class="rowinput" /></td>
</tr>
I also gave the row a non-unique class of tablerow. Now to give them some actions! I'm using jQuery here, which will do all of the heavy lifting for us.
<script type="text/javascript">
$(function(){
$('.tablerow').click(function(){
var row_id = $(this).attr('id').replace('row-','');
$.getJSON('script.php', {id: row_id}, function(rs){
if (rs.id && rs.data) {
$('#row-' + rs.id).find('.rowinput').val(rs.data);
}
});
});
});
</script>
Then in script.php you'll want to do something like this:
$id = (int) $_GET['id'];
$rs = mysql_query("SELECT data FROM table WHERE id = '$id' LIMIT 1");
if ($rs && mysql_num_rows($rs)) {
print json_encode(mysql_fetch_array($rs, MYSQL_ASSOC));
}
Maybe you can give each row a radio button. You can use JavaScript to trigger an action on selections in the radio button group. Later, when everything is working, you can hide the actual radio button using CSS and make the entire row a label which means that a click on the row will effectively click the radio button. This way, it will also be accessible, since there is an action input element, you are just hiding it.
I'd simply store the DB field name in the td element (well... a slightly different field name as there's no reason to expose production DB field names to anyone to cares to view the page source) and then extract it with using the dataset properties.
Alternatively, you could just set a class attribute instead.
Your PHP would look something like:
<tr>
<td data-name="<?=echo "FavoriteColor"?>"></td>
</tr>
or
<tr>
<td class="<?=echo "FavoriteColor"?>"></td>
</tr>
The javascript would look a little like:
var Test;
if (!Test) {
Test = {
};
}
(function () {
Test.trClick = function (e) {
var tdCollection,
i,
field = 'FavoriteColor',
div = document.createElement('div');
tdCollection = this.getElementsByTagName('td');
div.innerText = function () {
var data;
for (i = 0; i < tdCollection.length; i += 1) {
if (tdCollection[i].dataset['name'] === field) { // or tdCollection[i].className.indexOf(field) > -1
data = tdCollection[i].innerText;
return data;
}
}
}();
document.body.appendChild(div);
};
Test.addClicker = function () {
var table = document.getElementById('myQueryRenderedAsTable'),
i;
for (i = 0; i < table.tBodies[0].children.length; i += 1) {
table.tBodies[0].children[i].onclick = Test.trClick;
}
};
Test.addClicker();
}());
Working fiddle with dataset: http://jsfiddle.net/R5eVa/1/
Working fiddle with class: http://jsfiddle.net/R5eVa/2/
I attempt to fill a drop down from a database. I query and add my result to an array. I then use json_encode to send my data to a php file.
$query="SELECT project FROM main";
$results = $db->query($query);
while ($row_id = $results->fetchArray()) {
$proj_option[] = "<option value=\"".$row_id['project']."\">".$row_id['project']."</option>\n";
$pselected=$row_id['project'];
}
$output = array( "proj" => $proj_option);
echo json_encode($output);
In my php file, I use jquery ajax to fill the drop down.
$("#turninId").change(function() {
var user_id = $("#turninId").val();
$.ajax ( {
url:"send_input.php",
type: "POST",
dataType: "json",
data:{id_selection: user_id},
success:function(response) {
for (var i=0; i<response.proj.length; i++) {
$("#exp").html(response.proj[i]);
$("#project").html(response.proj[i]); } });
});
This is great, BUT the only item in my drop down is the last item in the db. For example, my database has the following under Project:
Project: up, down, low, right
But my drop down only fills with the last entry, "right." Why is this? How can I fix it?
PHP json_encode() in while loop was similar, and I made the changes, but there is something missing here.
may be try this
success:function(response) {
$.each(response.proj,function(key,value){
$("#exp").append(value);
$("#project").append(value);
});
}
each time thru your loop in javascript you are overwriting your html. The .html() method sets the innerHTML property of the tag, so each time you call it you are resetting the html and only the last one will show. try not using a loop, instead join you response together and then call .html()
$("#exp").html(response.proj.join(''));
$("#project").html(response.proj.join(''));