I want to insert ajax response array into form select input. for the purpose i want to look into array. here is my function;
function _get_student_failed_classes()
{
$failed_classes=$this->db->select('class_student.class_id,course.course_code,course.course_name,course.course_credit')
->join('class','class.class_id=class_student.class_id','LEFT')
->join('course','course.course_id=class.class_course','LEFT')
->where('class.class_status',$active)
->where('class_student.class_marks <=',50)
->where('class_student.student_id',$std_code)
->order_by('class.class_id')
->get('class_student')->result();
echo $failed_classes;
}
and here is my ajax call in form
$.ajax({
url: '<?php echo base_url()."index.php/student/get_student_failed_classes/s-14-1"; ?>',
type: 'POST', data: std_code,
success: function(response)
{
alert(response);
},
error: function()
{
alert(error);
}
I get the response is []
the actual array looks like this
Array
(
[0] => stdClass Object
(
[class_id] => 3
[course_code] => cs3
[course_name] => cs3
[course_credit] => 3
)
[1] => stdClass Object
(
[class_id] => 4
[course_code] => cs4
[course_name] => cs4
[course_credit] => 4
)
[2] => stdClass Object
(
[class_id] => 5
[course_code] => cs5
[course_name] => cs5
[course_credit] => 3
)
)
can some one help me out on this
var objectRet= jQuery.parseJSON(response);
for(var i=0;i<objectRet.length;++i) {
alert(objectRet[i].class_id)
}
success: function(response) {
var $select = $('<select id="mySelect"/>');
var $options = response.map(function(a, i) {
return $('<option />', {
value: a.class_id,
text: a.course_code + ' - ' +
a.course_name + ' (' + a.course_credit +')'
});
});
$options.appendTo($select.appendTo($('#someForm')));
}
Related
I am getting the below array as response using ajax in code igniter.
Array
(
[0] => stdClass Object
(
[monthly_count] => 3
)
[1] => stdClass Object
(
[monthly_count] => 1
)
)
//What i have tried so far is
$.ajax({
url:"<?php echo base_url();?>Admins/get_monthly_orders",
type: 'POST',
//dataType: 'JSON',
success:function (data) {
var result = [];
var array = data;
console.log(data);
array.forEach(function(k , v) {
var result = v.monthly_count;
})
console.log(result);
please help me to traverse and get 3, 1
and i need to get the value of 'monthly_count' like this
Array
(
[0] =>3
[1] => 1
)
or better something like this
[3, 1]
my controller code is this
public function get_monthly_orders(){
$monthlyOrders = $this->Admin_model->get_monthly_orders();
if($monthlyOrders){
print_r($monthlyOrders);
}
else{
return false;
}
}
Try changing the print_r($monthlyOrders) to echo json_encode( $monthlyOrders );. This will return it in JSON. It will be much easier to traverse in JS.
Well if you want to traverse it, you can just:
let result = [];
array.forEach(el => {
result.push(el.monthly);
})
console.log(result);
How to get value from response array to ajax?
let's se my response array
Array ( [files] => Array ( [0] => files/media_post/Hydrangeas.jpg ) [metas] => Array ( [0] => Array ( [date] => Mon, 31 Oct 2016 06:16:13 +0100 [extension] => jpg [file] => files/media_post/Hydrangeas.jpg [name] => Hydrangeas.jpg [old_name] => Hydrangeas [replaced] => [size] => 595284 [size2] => 581.33 KB [type] => Array ( [0] => image [1] => jpeg ) ) ) )
and my javascript
data: null,
type: 'POST',
enctype: 'multipart/form-data',
nama : $("#filer_input2").val(),
url: "<?php echo base_url(); ?>blog-media/ajax_add",
beforeSend: function(){},
success: function(data, el){
alert(data.metas);
var parent = el.find(".jFiler-jProgressBar").parent();
el.find(".jFiler-jProgressBar").fadeOut("slow", function(){
$("<div class=\"jFiler-item-others text-success\"><i class=\"icon-jfi-check-circle\"></i> Success</div>").hide().appendTo(parent).fadeIn("slow");
});
},
error: function(el){
var parent = el.find(".jFiler-jProgressBar").parent();
el.find(".jFiler-jProgressBar").fadeOut("slow", function(){
$("<div class=\"jFiler-item-others text-error\"><i class=\"icon-jfi-minus-circle\"></i> Error</div>").hide().appendTo(parent).fadeIn("slow");
});
}
so i hope i can get value from array because i neet that values for save to database.
When i am trying each loop under Ajax call, i am getting error as:
TypeError: invalid 'in' operand e
Below is my Ajax call code
$.ajax({
type: "POST",
url: "/admin/counselormanagement/centername",
data: 'groupId='+valueSelected,
async: true,
success: function(arrCenter) {
$.each(arrCenter, function( intValue, arrValue ) {
console.log('<option value="' + arrValue['ID'] + '">'+ arrValue['CenterName'] +'</option>');
});
}
});
Response which i am getting back from server is :
Array (
[0] => Array
(
[ID] => 4
[CenterName] => test2
[ParentName] => 2
[Parent] => 3
[GroupName] => test
[Type] => 1
)
[1] => Array
(
[ID] => 8
[CenterName] => test21
[ParentName] => 2
[Parent] => 3
[GroupName] => test
[Type] => 1
)
)
I am using PHP as backend, whose code is :
$arrCenterName = array();
$objCenterMapper = new Application_Model_CentersMapper();
$arrCenter = $objCenterMapper->seekCenters($_POST['groupId']);
print_r($arrCenter[0]);
die();
Use json_encode() in PHP to return response. And your JS code should be like:
PHP:
$arrCenterName = array();
$objCenterMapper = new Application_Model_CentersMapper();
$arrCenter = $objCenterMapper->seekCenters($_POST['groupId']);
echo json_encode($arrCenter[0]);
die();
JQuery:
$.ajax({
type: "POST",
url: "/admin/counselormanagement/centername",
data: 'groupId='+valueSelected,
dataType: 'json',
async: true,
success: function(arrCenter) {
$.each(arrCenter, function( intValue, arrValue ) {
console.log('<option value="' + arrValue.ID + '">'+ arrValue.CenterName +'</option>');
});
}
});
Try to echo out your object using json_encode instead:
<?php
$arrCenterName = array();
$objCenterMapper = new Application_Model_CentersMapper();
$arrCenter = $objCenterMapper->seekCenters($_POST['groupId']);
echo json_encode($arrCenter[0]);
die();
I have a form inside of a dialog box that is displayed when a user click on a button. When a user starts tying inside a field I want to display available options found inside a database.
The available options will need to be read using an AJAX request.
Here is my jQuery code where I try to initialize the autocomplete()
$("#icwsTransferTo")
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).autocomplete( "instance" ).menu.active ) {
event.preventDefault();
}
}).autocomplete({
source: function(request, response) {
$.ajax({
type: 'GET',
url: 'index.php',
data: {method: 'userSearch', term: request.term},
dataType: 'json',
cache: false,
timeout: 30000,
success: function(data) {
console.log(data);
if(!data){
return;
}
var array = $.map(data, function(m) {
return {
label: '<div syle="display: block;"><span>' + m.configurationId.displayName + '</span><span style="float: right"> (' + m.extension + ')</span></div>'
};
});
response(array);
}
});
},
search: function() {
// custom minLength
var term = extractLast( this.value );
if ( term.length < 2 ) {
return false;
}
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
alert('Worked!');
}
});
The field icwsTransferTo is located inside of a form which is displayed in the dialog box.
The problem is that when typing 2+ characters, I see the spinning icon in the field but no results is ever presented.
When I do a manual call to the index.php?method=userSearch&term=mike I get results like this
stdClass Object
(
[items] => Array
(
[0] => stdClass Object
(
[configurationId] => stdClass Object
(
[id] => msmith
[displayName] => Mike Smith
[uri] => /configuration/users/msmith
)
[extension] => 2062
)
[1] => stdClass Object
(
[configurationId] => stdClass Object
(
[id] => mjohns
[displayName] => Mike Jones
[uri] => /configuration/users/mjohns
)
[extension] => 2083
)
)
)
what am I doing wrong here? Why the results are not showing?
I am assuming you are using the Jquery UI autocomplete? According to their documentation here: Documentation you should pass it a JSON array not html.
i want to send a multidimensional array to PHP from JQuery AJAX, but it is receiving in PHP like this
Array
(
[recordid] => 38
[locations] => [object Object],[object Object]
)
i must be doing some stupid mistake. here is the code.
it gets records from a table and send to PHP
$(document).on('click','.savenow',function(){
recordid = $(this).data('id');
locations = [];
$('.selectrec').each(function () {
parent = $(this).parent().parent();
name = parent.find('td').eq(5);
address = parent.find('td').eq(6);
lat = parent.find('td').eq(1);
lng = parent.find('td').eq(2);
row = [name,address,lat,lng];
locations.push(row);
});
locations = locations.toString();
$.ajax({
type: "POST",
url:'/record/saveSearchedLocations',
data: { recordid: recordid,locations:locations },
dataType: 'json',
success: function (data) {
console.log(data);
},
error:function(data){
alert("something went wrong, please try again.");
}
});
});
and this is the PHP function where i am receiving the data:
function saveSearchedLocations(){
print_r($_POST);
}
Use JSON.stringify() instead of toString() like so:
Change your AJAX call to this:
$(document).on('click','.savenow',function(){
recordid = $(this).data('id');
locations = [];
$('.selectrec').each(function () {
parent = $(this).parent().parent();
name = parent.find('td').eq(5);
address = parent.find('td').eq(6);
lat = parent.find('td').eq(1);
lng = parent.find('td').eq(2);
row = [name,address,lat,lng];
locations.push(row);
});
ajaxData = { recordid : recordid,locations : locations }
$.ajax({
type: "POST",
url:'/record/saveSearchedLocations',
data: JSON.stringify(ajaxData),
dataType: 'json',
success: function (data) {
console.log(data);
},
error:function(data){
alert("something went wrong, please try again.");
}
});
});
JSON.stringify() converts your array to an actual json string as opposed to Array.prototype.toString() which joins your array (one level) using a comma as separator.
Take this answer as a reference:
I think you need to use JSON.stringify(selectedData) in order to use it on the serverside.
jQuery:
var obj = { 'risk_cat': risk_cat, 'risk_type': risk_type };
selectedData.push(obj);
$.post('serive.php', { DTO: JSON.stringify(selectedData) },
function(data){ /* handle response, */ });
service.php:
header('Content-type: application/json');
header('Cache-Control: no-cache, must-revalidate');
$foo = json_decode($_POST['DTO']);
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); //example data
echo json_encode($arr);
This should get you started. In your ajax reponse, alert(data.a) would be alerting "1"
sendAjax = function() {
var data = {
foo: 123,
bar: 456,
rows: [{
column1: 'hello',
column2: 'hola',
column3: 'bonjour',
}, {
column1: 'goodbye',
column2: 'hasta luego',
column3: 'au revoir',
}, ],
test1: {
test2: {
test3: 'baz'
}
}
};
$.ajax({
type: 'post',
cache: false,
url: './ajax/',
data: data
});
}
When the button is clicked, the following structured data shows up in PHP's $_POST variable:
Array
(
[foo] => 123[bar] => 456[rows] => Array(
[0] => Array(
[column1] => hello[column2] => hola[column3] => bonjour
)
[1] => Array(
[column1] => goodbye[column2] => hasta luego[column3] => au revoir
)
)
[test1] => Array(
[test2] => Array(
[test3] => baz
)
)
)
This will only work with jQuery 1.4.0+. Otherwise jQuery simply calls .toString() on the nested array at key "rows" and nested object at key "test1", and they get passed to PHP with the useless values "[object Object
here is the link u can check here
https://www.zulius.com/how-to/send-multidimensional-arrays-php-with-jquery-ajax/
Put your data in a form and send form data with serializeArray()