I was able to succesfully get data from database in json format from controller, this is how it looks:
{
"dealer":[
["1","himanshu"],
["2","bhola the dealer"],
["3","bhola the dealer"]
]
}
the problem is that I am not able to pass json data into the dropdown list in view from the controller.
Model Code:
public function getName(){
$this->db->select('dealerid,dealername');
$query=$this->db->get('Dealer');
$result=$query->result_array();
//echo "<pre>";
return $result;
}
Controller Code:
public function dealer_list()
{
$list = $this->person->getName();
$ddata = array();
foreach ($list as $person) {
$row = array();
$row[] = $person['dealerid'];
$row[] = $person['dealername'];
$ddata[] = $row;
}
$output = array(
"dealer" => $ddata,
);
//output to json format
echo json_encode($output);
}
View Code:
//get a reference to the select element
$select = $('#select');
//request the JSON data and parse into the select element
$.ajax({
url: "<?php echo site_url('dealer_controller/dealer_list')?>"
, dataType: 'JSON'
, success: function (data) {
//clear the current content of the select
$select.html('');
//iterate over the data and append a select option
$.each(data.dealer, function (key, val) {
$select.append('<option id="' + val.id + '">' + val.name + '</option>');
})
}
, error: function () { <strong>
//if there is an error append a 'none available' option
$select.html('<option id="-1">none available</option>');
}
});
Your json output doesn't have the keys id or name for each dealer. Therefore val.id and val.name won't work.
In your Controller change:
$row[] = $person['dealerid'];
$row[] = $person['dealername'];
to:
$row["id"] = $person['dealerid'];
$row["name"] = $person['dealername'];
This adds the keys id and name to the php array, and when converted to json should output something like the following:
{"dealer":[{"id": "1", "name": "himanshu"}, {...}]}
These can then be retrieved in your $.each with val.id and val.name
Fiddle
$.each(data.dealer, function (index, item) {
$select.append(
$('<option>', {
value: item[0],
text: item[1]
}, '</option>'))
}
)
})
Related
I am calling a PHP function from a JQuery ajax method. Below is how the response looks from ajax call:
My question is: how to iterate over this array in jquery to get the values?
I am getting "Cannot use 'in' operator to search for 'length' in Array" if I iterate using $.each.
Below is the Code:
$("#member_country").change(function() {
var country = $(this).val();
//alert(country);
var ajax_url_mtypes = ins_membership_ajax.ajax_url;
//alert(ajax_url_mtypes);
jQuery.ajax({
url:ajax_url_mtypes,
data:{country:country,
action: "ins_get_membershiptypes_from_country"},
method:'GET',
contentType: "application/json;charset=utf-8",
success:function(response) {
//var resp = $.trim(response);
alert(response);
$.each(response, function( key, value ) {
alert( key );
alert( value );
});
}
});
PHP Code:
public static function getMembershipTypesNonAdmin($country){
$rtn = array();
global $wpdb;
$table = $wpdb->prefix.self::TABLE_NAME;
$query = "SELECT * FROM {$table} where admin_only = 'false' order by member_type";
$results = $wpdb->get_results($query);
if($results){
foreach($results as $row){
$membership_type = INS_Membership_Types::loadById($row->id);
$membership_type->setDues(INS_Membership_Types::getDuesByEconomy($country, $membership_type->getMemberType()));
$rtn[] = $membership_type;
}
}
return $rtn;
}
private $dues;
public function getDues()
{
return $this->dues;
}
public function setDues($dues)
{
return $this->dues = $dues;
}
You can iterate over objects through for in loop. like as below:
for(var prop in object){
console.log(object[prop]);
}
Hope this helps.
Try with json.
Use
json_encode()
in the php code and
dataType: "json"
in the ajax call
I am working with my project in school. How can i get the value of selected checkbox in data table. I am using a codeigniter framework and i am populating my data table in controller and passed it to the view. Now i want to something alert/output the user_id of the checked data table. What i really want is to save the values of the checked user_id in my database table.
Here is my controller for populating the 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);
}
in my view, here is the ajax for data table:
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
});
}
$(document).ready(function() {
$('#dataTables-docs').dataTable();
show_docs();
});
You can get data from row table using this code:
$('#dataTables-docs tbody').on('click', 'input[type="checkbox"]', function(e){
var row = $(this).closest('tr');
var data = table.row(row).data();
var rowData = data[1];
alert(rowData);
});
Return the data of row selected from checkbox, if you want get the value of checkbox (user_id), then you can use this code:
$('#dataTables-docs tbody').on('click', 'input[type="checkbox"]', function(e){
var user_id = $(this).val();
alert(user_id);
});
Result: https://jsfiddle.net/cmedina/7kfmyw6x/130/
This may be the duplicate question but I would like to mention that other answers have not solved my problem.
As the question says, I want to populate the dropdown using ajax/jquery. I am able to send and recieve data in the JSON format successfully but it does not append with the dropdown. Following is my code:
View
<select name="guard_id" id="guard_id" style="width:100%;">
<option>select guard</option>
<optgroup label="Previously assigned guard" id="trained_guards">
</optgroup>
</select>
Jquery/Ajax call
function checkTrainedGuards(sid) {
$.ajax({
dataType: 'JSON',
type: 'POST',
url: '<?php print site_url('roster/check_trained_guards'); ?>',
data: { sid: sid},
beforeSend:function() {
// this is where we append a loading image
$('#sid').addClass('loader-roster');
},
success:function(data) {
var appenddata;
$.each(data, function (key, value) {
appenddata += "<option value = '" + value.gid + " '>" + value.gname + " </option>";
});
$('#trained_guards').html(appenddata);
},
error:function(){
// failed request; give feedback to user
}
});
}
Controller
public function check_trained_guards(){
$this->load->model("guard");
$sid=$this->input->post("sid");
$trainedGuards=$this->guard->getGuardAlreadyWorkedOnSite($sid);
foreach ($trainedGuards as $guard) {
print json_encode(array(
'gid' => $guard->gid,
'gname' => $guard->guard_name
));
}
}
}
When I test it using firebug, I an see the data is coming correct and it is in JSON format as shown below:
[{"gid":"293","gname":"Abc"},{"gid":"96","gname":"guard2"},{"gid":"101","gname":"guard3"},{"gid":"91","gname":"guard4"}]
However, I am just wondering why it is not appending the result into dropdown box?
I, Also tested this by alert(value.gid) in the jquery each loop it says undefined.
Any help will be highly appreciated.
You JSON seems to be in wrong format . Your php part should look like follows :
$arr = array();
foreach ($trainedGuards as $guard) {
$arr[] = $guard;
}
print json_encode($arr);
Now this code will return a valid JSON as Follows. JOSN will the array of objects shown below :
[{"gid":"2","gname":"Gurd1"},{"gid":"3","gname":"Guard2"}]
In your ajax response write following code
var data = [{"gid":"2","guard_name":"Gurd1"},{"gid":"3","guard_name":"Guard2"}];
//This is the response format You can also use JSON.parse if its in the string format
var appenddata = "";
$.each(data, function (key, value) {
appenddata += "<option value = '" + value.gid + " '>" + value.gname + " </option>";
});
$('#trained_guards').html(appenddata);
I have a jQuery function that gets data from a form and puts it as a string (for now) into an #content.
$(document).ready(function() {
$('form').submit(function() {
var results = $(this).serialize();
var url = '<php? echo JURI::base(); ?>index.php?option=com_mls&task=ListData&' + results;
$('#content').html(url);
return false;
});
});
So, I know how to build the query string from the form.
I have a task in my controller that runs a mySQL query string from the URL.
function ListData()
{
error_reporting(E_ALL);
$db =& JFactory::getDBO();
$sort = JRequest::getVar('sort');
...some other stuff...
$query = [some big nasty thing]
$db->setQuery($query);
$array = $db->loadRowList();
return $array;
}
So I know how to query the mySQL DB and get an array().
Then, I have a PHP script that pulls the array data into HTML format:
<?php
$array = $this->disparray;
foreach($array as $key => $value){
$mlsnum = $value['1'];
...some other data gets....
echo '<div>' . $mlsnum . '</div>';
}
?>
Here's where I'm stuck. I don't know how to get the URL query from jQuery to the controller task and then get the array() returned by that task into the PHP script which would build the HTML and then get AJAX/jQuery to put that data into #content.
Action is going on in 3 steps.
First ajax call view.raw.php then you load/add/delete some data from model, and customize it as you want. Then you print it in JSON format - send it back to ajax, and then ajax put that into html.
$(document).ready(function() {
var url = '<php? echo JURI::base(); ?>index.php?option=com_mls&task=ListData&format=raw&' + results;
$.ajax({
url: url,
dataType: 'json',
success: function(json) {
if (json['output']) {
$('#content').html(json['output']);
}
if (json['redirect']) {
location = json['redirect'];
}
}
});
});
this will communicate with
/com_mls/(default_view)/view.raw.php
in there, you should probably do something like
class mlsView_your_view... extends JView
{
public function display($tpl = null) {
$task = JRequest::getCmd('task', 0);
// see what should we do now
switch( $task ){
case 'ListData':
$data = $this->get_data();
break;
}
// Get the document object.
$document = JFactory::getDocument();
// Set the MIME type for JSON output.
$document->setMimeEncoding('application/json');
// Change the suggested filename.
//JResponse::setHeader('Content-Disposition','attachment;filename="resp.json"');
// Output the JSON data.
echo json_encode($data);
}
function get_data() {
// load model
$model = $this->getModel('ajax');
// get data from model
$data = $model->getSomeData();
if( is_null($data) ){
return array( 'error' => 'missing data.');
}
$data['output'] = $model->prepareData($data);
return array( $data );
}
....etc....
}
I'm programming an web page and I really stucked trying to send an Array of JSON objects to my PHP backend script.
this is my javascript code (using jQuery):
var toSend = new Array();
$("input[type=checkbox]").each(
function (indice, item)
{
var dom = $(item);
var domJSON = {
id: dom.attr("value"),
checked: (dom.attr("checked") == "checked" ? true : false)
};
//put object as JSON in array:
toSend.push($.toJSON(domJSON));
}
);
$.ajax({
type:"POST",
url: "salvar_escala.php",
data: {checkbox: toSend},
success: function(response) {
$("#div_salvar").html(response);
},
error: function() {
alert("Erro");
}
}
);
And in PHP I have this:
//Grab the array
$arrayFromAjax = $_POST['checkbox'];
foreach($arrayFromAjax as $aux) {
$temp = json_decode($aux, true);
$id = $temp['id'];
$value = $temp['checked'];
//This line doesn't print anything for $id and $value
echo "Id: $id | Value: $value<br />";
//This line prints an crazy string, but with right values
echo "CHEKBOX[] => $b<br />";
}
In this code, I'm decoding my objects to json, putting then in an array and sending. I also tried but objects in array (without json), and then, convert the array to json, and send them like that:
$.ajax({
type:"POST",
url: "salvar_escala.php",
dataType: "json",
data: {checkbox: $.toJSON(toSend)},
success: function(response) {
$("#div_salvar").html(response);
},
error: function() {
alert("Erro");
}
}
);
But in this case, it's worse, the error function is called.
You should be able to do the following in PHP
<?php
$checkboxes = json_decode($_POST['checkbox']);
foreach($checkboxes as $checkbox) {
$id = $checkbox['id'];
$val = $checkbox['value'];
print $id . ': ' . $val;
}
The problem is that you're trying to loop through a JSON string without first decoding it into a PHP array.