Recently I have been trying to make an auto-complete search.
I looked up some infos and figured out that there is a way to
use PHP variables at the source... but however when I try to get a
list of the places name, I get the results into an array
$db = new OBJ_mysql($config_budapest);
$places = array();
//- getting the list of the cities
$autocomplete= $db->query("SELECT DISTINCT Helyseg FROM M_munka WHERE Publikus = '1' AND Aktiv = 1 AND Jovahagyott = 1");
$autocomp_q= $autocomplete->fetchAllArray();
$writeauto = json_encode($autocomp_q); /* ECHO ALL THE RESULTS */
//array push
array_push($places,$autocomp_q);
<script type="text/javascript">
$(function() {
var availableClients = [<?php echo json_encode($places);?> ];
$("#tags").autocomplete({
source: availableClients,
});
});
</script>
Result:
Updated Result:
As far as I can see in your code, $places is an array of your query result. It seems you are creating an array of arrays (array with other arrays inside it)
Did you try to assign the query result to $places, something like this:
$db = new OBJ_mysql($config_budapest);
//- getting the list of the cities
$autocomplete= $db->query("SELECT DISTINCT Helyseg FROM M_munka WHERE Publikus = '1' AND Aktiv = 1 AND Jovahagyott = 1");
$autocomp_q= $autocomplete->fetchAllArray();
$writeauto = json_encode($autocomp_q); /* ECHO ALL THE RESULTS */
$places = $autocomp_q;
Hope it helps!
Related
So I am trying to send the "id" of a selected row in datatable in javascript to a php page so I could delete it from database.
var ids = $.map(table.rows('.selected').data(), function (item) {
return item[0] });
the variable "ids" is sent by post method
$.post( "deleterow.php", { v1: ids });
but it didn't worked so i try to see the response from post method and it says
"notice array to string conversion in C on line ... "
the line is of php page where i am writing the delete query
$id = $_POST["v1"];
$query = "DELETE FROM `package` WHERE `id` = '$id'";
The whole php page works fine when trying with other values.
Because you send an array here:
$.post( "deleterow.php", { v1: ids });
so v1 contains an array of elements. But in your php code you treat it as a single element:
$id = $_POST["v1"];
Hence the notice array to string conversion.
If you send an array of elements, you have to get it as an array and treat is as an array. To create a correct SQL string you should append each ID, like this:
$ids = json_decode($_POST["v1"]);
$query = "DELETE FROM `package` WHERE";
$first = true;
foreach ($ids as $id) {
if ($first) {
$first = false;
} else {
$query += " OR";
}
$query += " `id` = '$id'"
}
This way you loop the array and append a id = ID for each array element.
Now, this is important, this code is prone to SQL injection, a really bad security problem. Read this to get more info about this: How can I prevent SQL injection in PHP?
So I'm working on quite a big school project and our goal is to show the presence or absence of all students at our school, we have to show this data using chartJS, now we made a query which selects all classes and a foreach-loop runs through the classes and the the query to select the presence and convert it to JSON, I've been working on this function for quite a few days but I just can't seem to make it work...
Here is my QueryManager which activates the query:
public function getAanwezigheid($klassen){
$result = $this->dbconn->query("SELECT klas.code klas, ROUND(
(
SELECT Count(aanwezigheid)
FROM aanwezigheid
JOIN college ON aanwezigheid.Ccode = college.code
JOIN klas ON college.Kcode = klas.code
WHERE klas.code = '".$klassen."' AND vak.code = 'WFHBOICT.M032.16' AND college.college = '8'
AND aanwezigheid = '1'
)
/
(
SELECT Count(aanwezigheid)
FROM aanwezigheid
JOIN college ON aanwezigheid.Ccode = college.code
JOIN klas ON college.Kcode = klas.code
WHERE klas.code = '".$klassen."' AND vak.code = 'WFHBOICT.M032.16' AND college.college = '8'
)
* 100)
as percentage
FROM aanwezigheid
JOIN college ON aanwezigheid.Ccode = college.code
JOIN klas ON college.Kcode = klas.code
JOIN vak ON college.Vcode = vak.code
WHERE klas.code = '".$klassen."' AND vak.code = 'WFHBOICT.M032.16' AND college.college = '8'
GROUP BY klas.code");
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
print json_encode($data);
}
Here is the code which gets the query(the unserialize gets all classes which are available which are class A-F):
if($_GET['action']=='getAanwezigheid'){
header('Content-Type: application/json');
$klas = unserialize($_SESSION['klas']);
/*This loop runs the query for every class which has been found (A-F)*/
foreach($klas as $klas){
$klassen = $klas->getCode();
$result = $q->getAanwezigheid($klassen);
}
}
Here is the result I get:
[][][{"klas":"WFHBOICT.V1C","percentage":"38"}][][][{"klas":"WFHBOICT.V1F","percentage":"67"}]
And I want the result to be this:
[{"klas":"WFHBOICT.V1C","percentage":"38"},{"klas":"WFHBOICT.V1F","percentage":"67"}]
Now I get why I get all the brackets, it's because I loop through data[] every class too, but that's what I'm stuck at. I just need to print 1 JSON result
Any help would be really appreciated.
i have code above which gets data from a database and then place in in json form to make it readable in java script.
the results of the echo is
"FIAT":["Anglia","Bronco","Capri","Cobra","Consul","Corsair","Cortina"],
"Land Rover":["Defender","Discovery","Discovery 3","Discovery 4"]
I would like the data to be converted in such a way the i can reference it in this form Var Brand=array ();
Brand["FIAT"]=["Anglia","Bronco","Capri","Cobra","Consul","Corsair","Cortina"];
Brand["Land Rover"]=["Defender","Discovery","Discovery 3","Discovery 4"];
in java script. Does Any one know how i can do this.
$query = mysqli_query($conn,"SELECT * FROM car_models");
// Loop the DB result
while(($result = mysqli_fetch_array($query))) {
// Check if this ID is already in the data array
if(!array_key_exists($result['Brand'], $data)){
// Create array for current user
$data[$result['Brand']] = array();
}
// Add the current race time to the array (do not need to use the float)
$data[$result['Brand']][] = $result['Model'];
}
//json data
json_encode($data);
I found the solution. Simply added the json object in a variable and now am able to get the echo it to the console
`
//json data
var brandAvailable =
console.log(brandAvailable);
"`
I have 3 dropdowns with list of places that I wanted to sort in ascending order. The first dropdown of places is sorted using codeigniter active record order_by function and the places were successfully sorted in ascending order.However,using onchange javascript function,when I choose a place in the first dropdown then populate the second dropdown of places excluding the place I have chosen in the first dropdown, the places returned were not sorted in ascending order even though there is order_by function I have in my query. I suspect that this is because of the json formatted data returned in onchange. Here are my codes. Thanks for the help.
This code sorts the data properly in ascending order
function get_dropdown_barangay(){
$query = $this->db->select('ID,brgy_name')
->from('tbl_barangay')
->order_by('brgy_name','asc')
->get()
->result_array();
$dropdown = array('0'=>'Select Barangay');
foreach($query as $value){
$dropdown[$value['ID']] = $value['brgy_name'];
}
return $dropdown;
}
Output Image:
Onchange code, the returned places are not sorted in ascending order
$('#brgy_id_1').change(function(){
var brgy_id = $("#brgy_id_1").val();
alert(brgy_id);
var data_val = {'brgy_id':brgy_id};
$.ajax({
type: "POST",
url:"<?php echo base_url();?>admin/get_barangay_list",
data:data_val,
dataType:'json',
success: function(data)
{
$('#brgy_id_2').empty();
$.each(data,function(id,val)
{
var opt = $('<option />'); // here we're creating a new select option for each group
opt.val(id);
opt.text(val);
$('#brgy_id_2').append(opt);
});
}
});
}); //end change
admin.php
function get_barangay_list(){
if(isset($_POST['brgy_id2'])){
$brgy_array_id = array('0'=>$_POST['brgy_id'],'1'=>$_POST['brgy_id2']);
} else{
$brgy_array_id = array('0'=>$_POST['brgy_id']);
}
$result=$this->core_model->get_barangay_list($brgy_array_id);
$this->output->set_header('Content-Type: application/json',true);
echo json_encode($result);
}
model.php
function get_barangay_list($brgy_array_id){
$query = $this->db->select('ID,brgy_name')
->from('tbl_barangay')
->where_not_in('ID',$brgy_array_id)
->order_by('brgy_name','asc')
->get()
->result_array();
$dropdown = array('0'=>'Select Barangay');
foreach($query as $value){
$dropdown[$value['ID']] = $value['brgy_name'];
}
return $dropdown;
}
Output Image showing data are not sorted in ascending order
One way to implement kinghfb's comment :
On the server side : build an array
$dropdown = array();
$dropdown[] = array('id' => 0, 'label' => 'Select city');
for ($query as $value) {
$dropdown[] = array('id' => $value['ID'], 'label' => $value['brgy_name']);
}
On the client side (javascript) : change your loop code :
$.each(data,function(id,val) {
var opt = $('<option />'); // here we're creating a new select option for each group
opt.val(val.id);
opt.text(val.label);
$('#brgy_id_2').append(opt);
});
You are losing your order here, because you are setting new keys (problem is described here Change array key without changing order).
So you have to keep the keys and due this you have to change the js part as well, because you can´t access the data using key-value anymore.
function get_dropdown_barangay(){
$query = $this->db->select('ID,brgy_name')
->from('tbl_barangay')
->order_by('brgy_name','asc')
->get()
->result_array();
$dropdown = array('0'=>'Select Barangay');
foreach($query as $value){
$dropdown[] = array("id" => $value["ID"], "name" => $value['brgy_name']); // setting new value and keep an numeric key which represents the order
}
return $dropdown;
}
and the js has to be like:
$('#brgy_id_1').change(function(){
var brgy_id = $("#brgy_id_1").val();
alert(brgy_id);
var data_val = {'brgy_id':brgy_id};
$.ajax({
type: "POST",
url:"<?php echo base_url();?>admin/get_barangay_list",
data:data_val,
dataType:'json',
success: function(data)
{
$('#brgy_id_2').empty();
$.each(data,function(object)
{
var opt = $('<option />'); // here we're creating a new select option for each group
opt.val(object.id);
opt.text(object.value);
$('#brgy_id_2').append(opt);
});
}
});
});
I had highlighted the changes, but I don´t know hot to use bold in code at SO....
You could sort your JSON using underscore
Just pass in your JSON and a sort function. Like so:
var cityJSON = [{city: 'San Vinente'}, {city: 'Pequnio'}, {city: 'Pili Drive'}, {city: 'Jc Aquino'}, {city: 'Banza'}];
console.log(cityJSON); // unsorted
cityJSON = _.sortBy(cityJSON, function(item){return item.city});
console.log(cityJSON); // sorted
I have fetched data from MySQL and echoed JSON encoded data as follows:
$result = mysql_query ("SELECT * FROM order_list");
$myjsons = array();
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$myjsons[$i] = json_encode(array($row));
$i++;
}
echo json_encode($myjsons);
And I have a Javascript function that reads the string and shows it in a text box:
if(ajaxRequest.readyState == 4){
$.post('userfind.php', function(data) {
$("#txtfld").val(data);
var arr =data.slice(1);
var user_arr = arr.slice(0,-1);
var json = user_arr,
obj = JSON.parse(json);
alert(obj.user_id);
$("#resultTXT").val(obj.user_id);
},'json'
);}
}
ajaxRequest.open("POST", "userfind.php", true);
ajaxRequest.send(null);
}
The problem is that txtfld shows the string as [{"user_id":"2790","fre.....tst":""}] and resultTXT shows nothing because of the two [ ]. I have tried to remove them using slice but it seems that the slice doesn't work on JSON strings. What else can I do to remove [ ] so that the resultTXT shows the user_id?
Thanks
you convert the array 2 times to json.
php doesn't need the a index for the next array element
i would also add the correct header "application/json"
$row is already a associative array
$result = mysql_query ("SELECT * FROM order_list");
$myjsons = array();
while ($row = mysql_fetch_assoc($result)) {
$myjsons[] = $row;
}
header('Content-type: application/json');
echo json_encode($myjsons);
this gives you a proper formatted json
to access your json in javascript u do:
var obj=JSON.parse(json);
i assume that your mysql returns a list of orders or users [{"user_id":1},{"user_id":2}] so if you want to access the first user's id:
obj[0].user_id
but if i misunderstand u could post more info about your json.