Getting error while using each loop under ajax - javascript

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

Related

How to traverse this ajax response as array?

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

jQuery autocomplete issue - each character on separate line

I am trying to get an autocomplete text box working. Here is the code that I have so far:
if ($action == 'find_products')
{
$dept = $_POST['dept'];
$stk_adddep = "
SELECT * FROM stocktake_products WHERE stocktake_id = '{$stocktake_id}' AND is_deli = 0 AND department_description LIKE '{$dept}%' LIMIT 10; ";
$result = db::c()->query($stk_adddep);
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$data[] = array(
'full_name' => $row['product_name'],
'value' => $row['product_name']);
}
echo json_encode($data);
die();
}
Div to display the text box:
<input type="text" placeholder="Name" id="customerAutocomplte" />
JS code:
$('#customerAutocomplte').autocomplete({
source: function( request, response ) {
var dept = $('#customerAutocomplte').val();
$.ajax({
url: '<?php echo Navigation::gUrl('/users/admin/stocktake_details_nonbcodeditems.php', array('stocktake_id' => $stocktake_id, 'action' => 'find_products'));?>',
type: 'POST',
data: {'dept':dept},
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item,
value: item
}
}));
}
});
},
autoFocus: true,
minLength: 0
});
PHP part seems to be working fine, the response that I get is as follows:
[{"full_name":"Prince Hubert Cristal","value":"Prince Hubert Cristal"},{"full_name":"Schloer","value"
:"Schloer"},{"full_name":"Underberg 20ml","value":"Underberg 20ml"},{"full_name":"Odessa Vodka 20cl"
,"value":"Odessa Vodka 20cl"},{"full_name":"Marula","value":"Marula"},{"full_name":"Maderia Verdelho
15yr old","value":"Maderia Verdelho 15yr old"},{"full_name":"Madeira Malsmey 15yr old","value":"Madeira
Malsmey 15yr old"},{"full_name":"Hennessey 5cl","value":"Hennessey 5cl"},{"full_name":"Jack Daniels
35cl","value":"Jack Daniels 35cl"},{"full_name":"Madeira Bual 10 yr old","value":"Madeira Bual 10 yr
old"}]
However, the way that the results are displayed in the text box is incorrect. What gets displayed is the whole line "value":"Jack Daniels 35cl" for example which each character being a separate entry in the text box.
Try to use item.value in the callback function:
label: item.value value: item.value
$('#customerAutocomplte').autocomplete({
source: function( request, response ) {
var dept = $('#customerAutocomplte').val();
$.ajax({
url: '<?php echo Navigation::gUrl('/users/admin/stocktake_details_nonbcodeditems.php', array('stocktake_id' => $stocktake_id, 'action' => 'find_products'));?>',
type: 'POST',
data: {'dept':dept},
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item.value,
value: item.value
}
}));
}
});
},
autoFocus: true,
minLength: 0
});

Send multidimentional array from JQuery AJAX to PHP

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

Ajax response array

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

Looping through jsonp object

I've been looking for a week now and I can't find an answer for this situation.
I request data through jsonp.
$.ajax({
type:'GET',
dataType: "jsonp",
url: "http://www.domain.com/app/loadFeedsApp.php",
sync: true,
contentType: "application/json",
dataType: 'jsonp',
success: function(data) {
console.log(data);
}
});
In my server side i sent info like this:
$jarr = array();
$af = 0;
while( $row = mysql_fetch_array($result) )
{
$html = array("Appfeed".$af."" => array(
"cnty" => stripcslashes($row['cnty']),
"feed" => stripslashes($row['feed']),
"feedId" => stripslashes($row['feedId']),
"nickname" => stripslashes($row['nickname']),
"state" => str_replace("\r\n",'', $row['state']),
"date" => date("d/m/y", strtotime($row['date'])))
);
array_push($jarr, $html);
$af++;
}
echo $_GET['callback'] . '(' . json_encode($jarr) . ');';
And it returns the data:
jQuery21007744578921701759_1395250905357({
"Appfeed0":
{
"cnty":"MEXICO",
"feed":"text",
"feedId":"201",
"nickname":"chaparra",
"state":"Tamaulipas",
"date":"27\/02\/14"
}
});
jQuery21007744578921701759_1395250905357({
"Appfeed1":
{
" cnty ":"MEXICO",
"feed":"text ",
"feedsId":"198",
"nickname":"estudiante",
" state ":"Tamaulipas",
"date":"26\/02\/14"
}
});
jQuery21007744578921701759_1395250905357({
"Appfeed2":
{
" cnty ":"MEXICO",
"feed":"text ",
"feedsId":"197",
"nickname":"el roger",
" state ":"Tamaulipas",
"date":"26\/02\/14"
}
});
But when I try to loop through this in java script It just shows the last feed (Appfeed2). Also in when I print the data in console.log(). It looks like just received the last feed too.
Object {Appfeed2: Object}
1. Appfeed2: Object
1. state: "Tamaulipas"
2. date: "26/02/14"
3. feed: "Ayer fui a sacar mi licencia, sin saber manejar, no hice fila y solo me costo 200 pesos mas. Creo que sere taxista "
4. feedId: "197"
5. nickname: "el roger"
6. cnty: "MEXICO"
7. __proto__: Object
2. __proto__: Object
Any ideas? I was thinking about the way jsonp is returning the data, so I tried with square brackets, with and w/o the get callback, but it fails.
Thank you so much for your help!
You need to make sure that in your PHP code, you are only echoing out the JSON(P) once after the loop finishes. You need to build the array you want then echo it out at the end.
$jarr = array();
$af = 0;
while( $row = mysql_fetch_array($result) )
{
$jarr["Appfeed".$af] = array(
"cnty" => stripcslashes($row['cnty']),
"feed" => stripslashes($row['feed']),
"feedId" => stripslashes($row['feedId']),
"nickname" => stripslashes($row['nickname']),
"state" => str_replace("\r\n",'', $row['state']),
"date" => date("d/m/y", strtotime($row['date'])))
);
$af++;
}
echo $_GET['callback'] . '(' . json_encode($jarr) . ');';
P.S. Your AJAX call has a few too many options:
$.ajax({
type:'GET',
dataType: "jsonp",
url: "http://www.domain.com/app/loadFeedsApp.php",
success: function(data) {
$.each(data, function(i, v){
console.log(i);
console.log(v);
});
}
});

Categories

Resources