Add items into dropdown using ajax/jquery using codeigniter - php

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);

Related

Populate dropdown with JSON data using jquery & ajax

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>'))
}
)
})

How to copy json array variable data to php variable?

This is a web page for student results and 3 fields data i.e stu_class, section, exam is sending to controller and a json array data variable is coming back from controller to this page now i wanted to show that json variable's data on the webpage. So help me how to do so?
$(document).ready(function(){
$('#examination').change(function(){
var exam = $('#examination').val();
$('#exam').val(exam);
});
$('#enter').click(function(){
var stu_class = $('#stu_class').val();
var section = $('#section').val();
var exam = $('#examination').val();
$.ajax(
{
type : "POST",
dataType: "json",
url : "<?php echo base_url('index.php/marksheet/student_result_database'); ?>",
data : {
stu_class : stu_class,
section : section,
exam : exam
},
success: function(stu_data)
{
var items = [];
$.each( stu_data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val['student'] + "</li>" );
});
alert(items);
}
});
});
});
And i need to copy the data of stu_data variable of jquery to php variable $stu_data so that i can run a loop to show the values in below fields like this-
<?php foreach($stu_data as $data):
echo $data['id'];
echo $data['student'];
Something like this.
So programmers please help me..!
json_decode($str, true) -> turns a json-object into a php assoc array.
json_decode($str, false) -> turns a json-object into a php object.

Calling a control method in an Ajax call and error for converting array to string

I'm trying to call my controller method which calls a model method in an Ajax call.
Here is my Ajax call:
$.ajax({
type: "POST",
async: false,
dataType: "json",
url: "<?php echo base_url('siteController/fetchEmployees') ?>",
success: function(data)
{
html = "<table id='myTable'><thead><tr id='test'><th>ID</th><th>FName</th><th> LName</th></tr></thead><tbody id='contentTable'>";
for (var i = 0; i < data.length; i++)
{
html = html + "<tr id='trResponses' ><td><div >" + data[i]['ID'] + "</div></td><td><div >" + data[i]['FName'] + "</div></td><td><div >" + data[i]['LName'] + "</div></td></tr>";
}
html = html + "</tbody></table>";
$("#resultFrm2").html(html);
},
error: function() {
alert('error');
}
});
and my siteController has the following method:
public function fetchEmployees()
{
$this->load->model('user_model');
return json_encode($this->user_model->getAll());
}
and my Model method is as following:
public function getAll()
{
$q = $this->db->get('users');
if ($q->num_rows() > 0) {
foreach ($q->result() as $row) {
$data[] = $row;
}
return $data;
}
}
but since my return in controller is an array I get the following error:
A PHP Error was encountered
Severity: Notice
Message: Array to string conversion
Do you know how I can handle this issue?
If my question is not clear please let me know which part you need more clarification?
ADDED:
I did all of your suggestions and mentioned all of my changes in here too! but now there is no out put for Ajax however if in my controller instead of return json_encode($this->user_model->getAll()); I use var_dump( json_encode($this->user_model->getAll())); I can see data in response!
Thanks
EDITED:
You need to return a json array
In your ajax call set
dataType: "json"
and in your fetchEmployees() function
echo json_encode($this->user_model->getAll());
This will transmit the php array as a string which will the be turned into a javascript array when received by your ajax function.
You've got an issue with your siteController - echo accepts and returns a string, and you're passing it an array. You want to change echo($this->user_model->getAll()); to return json_encode($this->user_model->getAll());
An AJAX response is in the form of JSON (JavaScript Object Notation), you'll get a JavaScript ParseError if you don't json_encode first.

AJAX not posting or receiving apparently

I tell you what, getting AJAX to work is one pain in the wazoo! It took me ages to get a simple string to pass and then I got a json array working and felt good, now I've tried to make a little adjustment and broke the whole thing again. Why is following giving an ajax error and how can I get under the hood to see what's going on?
jQuery:
$('#upload_form option[value="addnew"]').click(function(){
// Show modal window
$('#add-new').modal('show');
// Get the class
var Classofentry = $(this).attr("class");
//console.log(Classofentry);
$('#add-new-submit').on('click', function(){
// Get new option from text field
var value = $('#add-new-text').val();
console.log(value);
$.ajax({
type: "POST",
url: "<?php echo site_url(); ?>main/change_options",
data: {new_option: value, new_option_class: Classofentry},
//dataType: "html",
dataType: "json",
error: errorHandler,
success: success
});
function success(data)
{
if (data[1]) // Only add new entry if unique
{
// Add new entry
//$('#animal_species').append("<option value='" + data + "'selected=\"selected\">" + data + "</option>");
$('#'+Classofentry).append("<option value='" + data[0] + "'selected=\"selected\">" + data[0] + "</option>");
//alert(data[0]);
}
else
{
// Select the nonunique value by emptying it and appending
$('#'+Classofentry).empty("<option value=''selected=\"selected\">" + data[0] + "</option>").append("<option value='" + data[0] + "'selected=\"selected\">" + data[0] + "</option>");
//alert(data[1]);
}
alert(data[1]);
//alert('Success!');
}
function errorHandler()
{
//alert('Error with AJAX!');
alert(data[0]);
}
$('#add-new-submit').unbind('click'); // This fixes the problem for multiple entries
$('#add-new').modal('toggle');
});
});
php:
public function change_options()
{
# Receives and sends back user-entered new option and adds it to database
# Get strings from ajax in view
$value = $_POST['new_option'];
$value_class = $_POST['new_option_class'];
#Make array to send to model
$value_array = array('Options' => $value);
$unique = true;
echo json_encode(array($value, $unique));
}
In the console I get: ReferenceError: data is not defined. I've spent the last couple days working on logic to determine $unique and now the ajax won't work, even when I strip it back to it's bare bones. What going on here?
Th code I posted should've worked. I found the issue and it wasn;t with ajax, it was with me passing the wrong thing to the model. Here's the working code, with the logic to determine $unique:
(BTW, this solves the problem posed in Form Validation in Codeigniter: using set_rules to check text input from a modal window without using Form Validation):
public function change_options()
{
# Receives and sends back user-entered new option and adds it to database
# Get strings from ajax in view
$value = $_POST['new_option'];
$value_class = $_POST['new_option_class'];
//print_r($value_class); die;
#Make array to send to model
$value_array = array('Options' => $value);
$unique = true;
$this->load->model('data_model');
$elements = $this->data_model->get_options($value_class);
foreach ($elements as $element)
{
if (preg_match("/$element/", $value, $matches))
{
$unique = false;
break;
}
}
# Add new option to dropdown in database
if ($unique) {$this->data_model->add_option($value_class, $value_array);}
//echo $value;
echo json_encode(array($value, $unique));
}

pass an array from jQuery to PHP (and actually go to the page after submit)

This seems like it would have been simple, but what i was doing was creating an array in jQuery and sending it to a php via ajax and inserting the records into a db. But what i want to do now is create the array exactly the same but instead of ajax, i'd like to go to the php page and view what it has received.
How would i go about doing this?
I'm using this jQuery:
$('#preview').live('click',function(){
var postData = {};
$('#items tr').not(':first').each(function(index, value) {
var keyPrefix = 'data[' + index + ']';
postData[keyPrefix + '[index]'] = index;
postData[keyPrefix + '[supp_short_code]'] = $(this).closest('tr').find('.supp_short_code').text();
postData[keyPrefix + '[project_ref]'] = $(this).closest('tr').find('.project_ref').text();
postData[keyPrefix + '[om_part_no]'] = $(this).closest('tr').find('.om_part_no').text();
postData[keyPrefix + '[description]'] = $(this).closest('tr').find('.description').text();
postData[keyPrefix + '[quantity_input]'] = $(this).closest('tr').find('.quantity_input').val();
postData[keyPrefix + '[cost_of_items]'] = $(this).closest('tr').find('.cost_of_items').text();
postData[keyPrefix + '[cost_total_td]'] = $(this).closest('tr').find('.cost_total_td').text();
});
$.ajax
({
type: "POST",
url: "preview.php",
dataType: "json",
data: postData,
cache: false,
success: function()
{
}
});
});
And this PHP:
if (isset($_POST['data']) && is_array($_POST['data'])) {
foreach ($_POST['data'] as $row => $data) {
echo $data['index'];
echo $data['project_ref'];
echo $data['supp_short_code'];
echo $data['om_part_no'];
echo $data['description'];
echo $data['quantity_input'];
echo $data['cost_of_items'];
echo $data['cost_total_td'];
}
}
You can store the received data in a session:
if (isset($_POST['data']) && is_array($_POST['data'])) {
session_start();
$_SESSION['data'] = $_POST['data'];
}
And then link to another PHP page that retrieves the data from the session and displays it:
session_start();
if (isset($_SESSION['data']) && is_array($_SESSION['data'])) {
foreach ($_SESSION['data'] as $row => $data) {
echo $data['index'];
echo $data['project_ref'];
echo $data['supp_short_code'];
echo $data['om_part_no'];
echo $data['description'];
echo $data['quantity_input'];
echo $data['cost_of_items'];
echo $data['cost_total_td'];
}
}
What you can do, following on from what dnagirl said, is to generate the POST form using jQuery and submit it.
$('#preview').live('click',function(){
var cForm = $('<form method="post">').attr('action', "preview.php");
$('#items tr').not(':first').each(function(index, value) {
var keyPrefix = 'data[' + index + ']';
cForm.append($('<input type="hidden">').attr('name', keyPrefix + '[index]').val(index));
cForm.append($('<input type="hidden">').attr('name', keyPrefix + '[supp_short_code]').val($(this).closest('tr').find('.supp_short_code').text());
// etc
});
cForm.hide().append('body').submit();
return false;
});
The reason for using attr() in places rather than inline within the creation string is to avoid issues with escaping, and it looks cleaner in my opinion.
Why not use JSON
PHP JSON
So you are current creating a POST string using jQuery and then sending it using ajax to a php script. Now you actually want to POST directly to PHP. Is that correct?
If I've got that right, there are 2 options:
actually POST from a form that
the user fills out
have a skeleton form consisting of
the <form> tags and a submit
button. Use jQuery to create and
populate hidden form fields when the
user hits the submit button and
before the submit action is
completed.

Categories