I Have a html select element generated in PHP from an array as follows
$countries = array(
array('iso' => 'AF', 'name' => 'Afghanistan', 'key' => 'Red'),
array('iso' => 'AX', 'name' => 'Ă…land Islands','key' => 'Yellow'),
array('iso' => 'AL', 'name' => 'Albania', 'key' => 'Blue')
);
$select = '<select id="country_select" onchange="countryfind()">';
foreach($countries as $country) {
$select .= '<option value="'.$country['key'].'">'.$country['name'].'</option>';
}
$select = '</select>';
return $select;
The select box uses a small javascript function to displays the country key of the selected country:
function countryfind(){
jQuery('#countrykey').text(
jQuery('#country_select option:selected').val()
)};
I want to now use that key to interface with another PHP array which contain information about the country and display that country in the #countrykey div instead of the selected value:
$si_federations = array(
'Red' => array('name'=>'A Red Country', 'url'=>'http://www.redcountry.com'),
'Blue' => array('name'=>'A Blue Country', 'url'=>'http://www.soroptimisteurope.org'),
);
Is this something that can be easily achieved, or is my approach entirely wrong?
You're on the right track here. So, here's how to get this to do what you want
Within your <script> block we want to output that array in JSON
var federations = <?php echo json_encode($si_federations); ?>;
Now, when you run countryfind we want to pull the value out of that object and display it as well. So let's modify your function
function countryfind(){
var fed;
var selected = jQuery('#country_select option:selected').val();
if(federations[selected] !== undefined) fed = federations[selected];
else fed = {"name":"Default Name", "url":""}; //placeholders if it's not defined
jQuery('#countrykey').text(
selected + ' - ' + fed.name + ' ' + fed.url;
)};
I don't know how you want it displayed (I just dumped it as text for simplicity), but this gets you the data you need so you can take it from there
You have to convert your php associative array into js object for further reference. As php runs on server and you are doing every action on client side so right after page loads, your php is useless. You need js var so that you can reference it further.
Like this:
<script>
var countries = [];
var country = {};
<?php foreach($si_federations as $k => $country): ?>
<?php foreach($country as $key=>$val): ?>
country['<?php echo $key; ?>'] = '<?php echo $val; ?>';
<?php endforeach; ?>
countries['<?php echo $k; ?>'] = country;
<?php endforeach; ?>
function countryfind(){
var keyVal = jQuery('#country_select option:selected').val();
jQuery('#countrykey').text('name: '+countries[keyVal]['name']+' url: '+countries[keyVal]['url']);
}
</script>
I hope it helps
Related
What is wrong here:
function getoptions(){
echo "<option value = 3>ABX</option>";
}
...
$id = $db->lastInsertId(); // for example `10`
$options = getoptions();
echo ($id . '***' . $options);
js
console.log(data);
Result:
<option value = 3>ABX</option>10***
I'm expecting 10***<option value = 3>ABX</option>
Any help?
If you need to use the same function to either echo or return the output you can pass a flag to the function. You can set a default value so the function performs as expected by other parts of your app.
// set default value of echo the output so it's non-breaking for other functions that require the output to be echoed
function getoptions($out = 'echo'){
if ($out == 'return') return "<option value = 3>ABX</option>";
echo "<option value = 3>ABX</option>";
}
...
$id = $db->lastInsertId(); // for example `10`
$options = getoptions('return');
echo ($id . '***' . $options);
In function getoptions you are echoing, you need to return the value. Look at the corrected function below.
function getoptions(){
return "<option value = 3>ABX</option>";
}
...
$id = $db->lastInsertId(); // for example `10`
$options = getoptions();
echo ($id . '***' . $options);
I am getting some value through a form . But unable to automatically insert that value in a separate js file.
Details :
i am getting value from form as $id and $marks.
i have a js file named as raw_data.js
JS File Content : window.raw_data = " (6,9) ";
Now i want that any value that i get from form should cancanate in that JS file in ($id,$marks) format.
LocalStorage is your solution:
window.localStorage.setItem('some title', $id);
window.localStorage.setItem('some title2', $marks);
And get it on raw_data.js:
var $id = window.localStorage.getItem('some title');
var $marks = window.localStorage.getItem('some title2');
window.raw_data = "($id, $marks)";
Edit: in your code, should be like this:
<?php
if($_POST["marks"] && $_POST["id"]) {
$marks = $_POST["marks"];
$id = "ID_" . $_POST["id"];
?>
<script>
window.localStorage.setItem('some title', $id);
window.localStorage.setItem('some title2', $marks);
</script>
<?php
}
?>
i am doing my school project. I manage to add/delete in database from my data-table checkbox if the value is check then it will add then if uncheck then it will be deleted, Now what i want is , when i go load the data table with checkbox, i want to check already the values that is already in my database. For example, if i have user_id = 102 already in my database, if i load the data-table, i want the name with user_id value of 102 will be automatically check when fetching the data-table checkbox. How can i do it? i am using a codeigniter framework.
Here is my controller in populating my data-table:
public function getalldocs() {
$listdocs = $this->Admin_model->getdoctors();
$data = array();
foreach ($listdocs as $docs) {
$row = array();
$row[] = $docs->user_fname;
$row[] = $docs->user_mname;
$row[] = $docs->user_lname;
$row[] = '<input name="user_id[]" value="'.$docs->user_id.'" type="checkbox">';
$data[] = $row;
}
$output = array(
"data" => $data,
);
echo json_encode($output);
}
Here is my ajax/javascript:
function show_docs() {
$("#dataTables-docs").dataTable().fnDestroy();
table = $('#dataTables-docs').DataTable({
"ajax": {
"url": "<?php echo site_url('admin_controls/getalldocs')?>",
"type": "POST",
},
responsive: true,
className: 'select-checkbox',
'bInfo': false,
'paging': false
});
}
and then i put the function into document-ready:
$(document).ready(function() {
$('#dataTables-docs').dataTable();
show_docs();
});
what i want is when i will go load my data-table, i want to check all the data-table checkbox if it is already in the database.
You're just comparing arrays. I'm not PHP coder, so what follows might be a poor method, but it demonstrates the principle of comparing one array with another. Actually, it compares an array with an interating value, but that iterating value could just as easily be borrowed from another array...
<?php
$my_array = array(
0 => 1,
1 => 2,
2 => 3,
3 => 5,
4 => 7
);
for($i=0;$i<10;$i++){
echo $i;
if(in_array($i,$my_array)){echo " yes <br>\n";} else {echo " no <br>\n";}
}
?>
I'm creating one Graph chart using Google APIs I used Java Script source from Google. In PHP I'm using while loop where I fetch some array row using query, this mysql query works fine, and values of fetched array are also correct (When I echoed that in PHP) but problem is that how do I pass this values to JavaScripts function?
My PHP code is as follows :
while ($graph_result = mysqli_fetch_row($graph))
{
$graphCount = $graph_result[0];
$graphMonth = $graph_result[1];
echo $graphCount; // This works
echo $graphMonth;
}
This gives me in result of two rows, each contains two values listed below:
Now I want to pass this above values to Java script function so that it draws Graph chart for me, my javascript code is as follows:
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Months', 'users'],
[graphMonth, graphCount] // Here I have to place PHP values !
]);
}
So how to pass this values to JS ???
Try the below code,
In PHP
$i = 0;
while ($graph_result = mysqli_fetch_row($graph))
{
$graph_values[$i]["count"] = $graph_result[0];
$graph_values[$i]["month"] = $graph_result[1];
$i++;
}
In script,
<script>
<?php foreach($graph_values as $key){ ?>
drawChart('<?php echo $key["count"]; ?>', '<?php echo $key["month"]; ?>');
<?php } ?>
function drawChart(graphCount, graphMonth) {
var data = google.visualization.arrayToDataTable([
['Months', 'users'],
[graphMonth, graphCount]
]);
}
</script>
<?php while ($graph_result = mysqli_fetch_row($graph))
{
?>
<script>
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Months', 'users'],
[<?php echo $graph_result[0]; ?>, <?php echo $graph_result[1]; ?>]
]);
}
</script>
<?php
}
?>
I don't know if it is best practice or not..
You can use json to do that.
In your while loop, build an associative array and encode it in json:
$jsonArray = array();
while ($graph_result = mysqli_fetch_row($graph))
{
$graphCount = $graph_result[0];
$graphMonth = $graph_result[1];
$jsonArray[] = array($graphCount, $graphMonth);
}
echo '<div id="json">' . json_encode($jsonArray) . '</div>';
And then recover it in your javascript:
var json_data = JSON.parse(document.getElementById('json').innerHTML);
function drawChart(json_data) {
var data = google.visualization.DataTable();
data.addColumn('number','Months');
data.addColumn('number','users');
data.addRows(json_data);
}
I have a select option from which I can select a hotel name which I get from a php script.
And then I have another select option which shows room types based on the hotel selected from 1st select option.
And when I select a hotel with the help of ajax I only get one room type in my 2nd select option, while in my table I have multiple room types for a single hotel.
My php code for getting room types.
<?php
include('mysql.php');
$h_id = $_POST['hotel_id'];
$result = mysql_query("SELECT * FROM room_type WHERE hotel_id = '$h_id'");
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$type_name = $row['type_name'];
$type_id = $row['roomtype_id'];
echo $type_name.",".$type_id;
}
exit();
?>
javascript:
jQuery(document).ready(function($){
$('#hotel_list').change(function(){
$.ajax({
type:'post',
url:'roomtype_fetch.php',
data: 'hotel_id='+ $(this).val(),
success: function(value){
var data = value.split(",");
var type_name =data[0];
var type_id =data[1];
$("#roomtype_list").html("<option value="+type_id+">"+type_name+"</option>");
}
});
});
});
html for 1st select option with its php to get hotel name.
<select class="form-control" name="hotel_list" id="hotel_list" onchange="cal()">
<option>--Select--</option>
<?php
$query2 = mysql_query("SELECT * FROM hotel") or die("the query cannot be completed at this moment");
if(mysql_num_rows($query2) <1) {
?>
<option>No Hotel Found!</option>
<?php
}
while($row = mysql_fetch_array($query2, MYSQL_ASSOC)){
$hotel_name = $row['hotel_name'];
$hotel_id_1 = $row['hotel_id'];
?>
<option value="<?php echo $hotel_id_1; ?>"><?php echo $hotel_name; ?></option>
<?php
}
?>
</select>
2nd select html code:
<select class="form-control" name="roomtype_list" id="roomtype_list">
<option>--Select--</option>
</select>
Any type of help would be appreciated.
You cant directly do value.split(",") because your php output looks like:
name1,id1name2,id2name3,id3
echo does not add a new line at the end, if you change the line to:
echo $type_name.",".$type_id,"\n";
That would give you an output like:
name1,id1
name2,id2
name3,id3
Which then you can split by "\n" to get an array of lines then by "," to separate name and id:
var data = value.split(",");
data.forEach(function(line){
var type_values = line.split(",");
var type_name = type_values[0];
var type_id = type_values[1];
$("#roomtype_list").html("<option value="+type_id+">"+type_name+"</option>");
}
But anyway, I think your best option is to change your php to return JSON:
$result = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$result[] = $row;
}
echo json_encode($result);
Then just do something like:
var data = JSON.parse(value);
$("#roomtype_list").empty();
data.forEach(function(type){
$("#roomtype_list").append("<option value="+type.roomtype_id+">"+type.type_name+"</option>");
});
The first thing is, your php loop that generates the types gives a wrong output:
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$type_name = $row['type_name'];
$type_id = $row['roomtype_id'];
echo $type_name.",".$type_id;
}
That gives you something like that:
name1,type1name2,type2name3,type3...
You should add a ; or an other separator like that between, so change the echo line to:
echo $type_name.",".$type_id.",";
That will give you an output like that:
name1,type1;name2,type2;name3,type3...
The second thing is, that you have to loop with jquery through your received types. You split the received string in an array:
var data = value.split(",");
..and so you should do the following in your javascript success function:
...
success: function(value){
var data = value.split(";");
//split all types first with ";"
$.each(data, function() {
var type = $(this).split(",");
//then split the type in name and id
var type_name = type[0];
var type_id = type[1];
//add every type to roomtype_list
$("#roomtype_list").html("<option value="+type_id+">"+type_name+"</option>");
});
}
...
Explanation: Split first all types with the separator ";" and split then the type in name and id with ",". I hope this helps.