how to retrieve much data in view (codeigniter) using while(). if I use foreach, I can't get the desired result. this is my code:
//my view home.php
$(document).ready(function(){
$('#check').click(function(event){
event.preventDefault();
var form_data = {
name: "xxxx"
};
$.ajax({
url: 'http://localhost:8000/jqjx/index.php/cont/getname',
type: 'POST',
async : false,
data: form_data,
dataType: 'html',
success: function(resp){
$('#content').html(resp);
}
});
return false;
});
});
//my controller cont.php
public function getname()
{
$data = array();
$namex = $this->input->post('name');
if($q = $this->my_model->detail_data($namex))
{
$data['data_detail'] = $q;
$this->load->view('tamp_page', $data);
}
}
my helper page (view) tamp_page.php
<?php
if(isset($data_detail))
{
foreach ($data_detailas $row) {
echo $row['name']."<br/>";
echo $row['birthday']."<br/>";
}
}
?>
if I use :
<?php
if(isset($data_detail))
{
echo $name_data['id_transactions'] . "<br/>";
echo $name_data['goods'] . "<br/>";
}
?>
it's still work but just for 1 data result. so how I can loop more much data.. thanks..
<?php
if(isset($data_detail))
{
foreach ($data_detail as $row)
{
echo $row['name']."<br/>"; //$row['name] was not properly closed. single quote(') was missing
echo $row['birthday']."<br/>";
}
}
?>
Just basic use of foreach:
if(isset($data_detail)){
foreach ($data_detailas as $row) {
echo $row['name'] . "<br/>";
echo $row['birthday'] . "<br/>";
}
}
Related
I want to insert while loop user data in jQuery array.
<?php
while($get_users_table_details = mysql_fetch_array($deatails)) {
if(empty($get_users_table_details["photo"])) { $pics = "photos/avatar.gif"; } else { $pics = "photos/".strip_tags($get_users_table_details["photo"]).""; }
?>
Script code between while loop
$(document).ready(function(){
$("#full").mention({
users: [{
name: '<?php echo $get_users_table_details['fullname'];?>',
username: '<?php echo $get_users_table_details['username'];?>',
image: '<?php echo $pics;?>'
}] });
});
</script>
end of script
}
end of while loop
The problem is that this shows the user details of only one user. However, I want all user details to be shown, as in this picture:
You should first build the array of users in php:
<?php
$users = []; // instatiate an empty array
while($get_users_table_details = mysql_fetch_array($deatails)) {
// build a user-array as needed later
$user = [];
$user['name'] = $get_users_table_details['fullname'];
$user['username'] = $get_users_table_details['username'];
if(empty($get_users_table_details["photo"])) {
$user['image'] = "photos/avatar.gif";
} else {
$user['image'] = "photos/".strip_tags($get_users_table_details["photo"]);
}
$users[] = $user; // add this user to the array of users
}
?>
Then pass (=echo) that to javascript via json_encode:
<script>
$(document).ready(function(){
$("#full").mention({
users: <?php echo json_encode($users); ?>
});
});
</script>
Please try this sample javascript code.
var users = <?php echo json_encode($get_users_table_details ) ?>;
$.each(users, function(key, value) {
console.log('stuff : ' + key + ", " + value);
// Do everything you want
});
I am dynamically adding table rows by selecting options from dropdown and then I am trying to send html table rows to php function using ajax as array in json format. However php function does not print all rows in the console log, when I am submitting more than one row. I got the desired output like once or twice. I think I am missing something in the php function. Please check once. If anymore information about the code is required, let me know, I will update.
Javascript:
function storeClgValues() {
var CollegeData= new Array();
$('#collegetable tr').each(function(row, tr){
CollegeData[row]={
"college" : $(tr).find('td:eq(0)').text()
}
});
CollegeData.shift();
return CollegeData;
}
$('#submit').click(function() {
CollegeData=storeClgValues();
CollegeData=$.toJSON(CollegeData);
$.ajax({
type:"POST",
url: '<?php echo base_url();?>ajaxController/insertcollege',
data: "CollegeData=" + CollegeData,
success: function(msg) {
console.log(CollegeData);
console.log(msg);
}
});
});
PHP function in AjaxController class:
public function insertcollege()
{
$data=array();
$data=stripcslashes($_POST['CollegeData']);
$data=json_decode($data, TRUE);
//echo $data[0]['college'].'<br>';
//echo $data[1]['college'].'<br>';
if (is_array($data) || is_object($data))
{
foreach ($data as $key => $item) {
echo $item['college'].'<br>';
}
}
}
Output in console in three tries:
[{"college":"College of Agriculture"}]
College of Agriculture
[{"college":"College of Agriculture"},{"college":"College of Business"}]
College of Agriculture
College of Business
[{"college":"College of Agriculture"},{"college":"College of Business"}, {"college":"College of Comm & Educati"}]
<!--nothing gets printed-->
Try like this...
<?php
$json = '[{"college":"College of Agriculture"},{"college":"College of Business"}, {"college":"College of Comm & Educati"}]';
$data = json_decode($json,TRUE);
//print_r($data);
if (is_array($data) || is_object($data))
{
foreach ($data as $key => $item) {
$output[]=$item['college'].'<br>';
}
}
echo json_encode($output);
?>
OR
<?php
$json = '[{"college":"College of Agriculture"},{"college":"College of Business"}, {"college":"College of Comm & Educati"}]';
$data = json_decode($json,TRUE);
//print_r($data);
if (is_array($data) || is_object($data))
{
foreach ($data as $key => $item) {
foreach($item as $value){
$output[] = $value."</br>";
}
}
}
echo json_encode($output);
?>
I need to get the value from second page member_verify.php in my jQuery resonse which is in first page. I need to get $age value in first page. Now message displays correctly.
I need to get the age which I fetched in member_verify.php with $age=$fet['Age'];:
function memberid(em) {
var memid=$("#memid").val();
$.ajax({
type:'post',
url:'member_verify.php',
data:{memid: memid},
success:function(msg){
if (msg.length> 0) {
alert(msg);
}
else{
$("#disableDiv :input").attr("disabled", false);
}
}
});
}
member_verify.php
<?php
$s=$_POST['memid'];
include "common/config.php";
$echeck="select * from insmemberdetails where LoginId='".$_POST['memid']."'";
$echk=mysqli_query($conn,$echeck);
$fet=mysqli_fetch_assoc($echk);
$age=$fet['Age'];
$ecount=mysqli_num_rows($echk);
if($ecount=='0')
{
echo "Member Id Not exists";
}else
{
$fet=mysqli_fetch_assoc($echk);
$verify=$fet['verify'];
if($verify=='0')
echo "Member Id not Verified";
}
?>
Change your member_verify.php to get age in ajax response otherwise you will get validation message.
<?php
$s=$_POST['memid'];
include "common/config.php";
$echeck="select * from insmemberdetails where LoginId='".$s."'";
$echk=mysqli_query($conn,$echeck);
$ecount=mysqli_num_rows($echk);
if($ecount <= 0)
{
echo "Member Id Not exists";
}
else
{
$fet=mysqli_fetch_assoc($echk);
$age=$fet['Age'];
$verify=$fet['verify'];
if($verify==0)
{
echo "Member Id not Verified";
}
else
{
echo $age;
}
}
?>
And below is your JS file.
function memberid(em) {
var memid=$("#memid").val();
$.ajax({
type:'post',
url:'member_verify.php',
data:{memid: memid},
success:function(data){
console.log(data);
}
else{
$("#disableDiv :input").attr("disabled", false);
}
}
});
}
Hope this will help you.
May be you could know something about json.
php code:
if($ecount!=0){
echo json_encode(array(
errno: 0,
data: $age
));
}else{
echo json_encode(array(
errno: 500,
errmsg: 'your error info'
));
}
your js here:
$.ajax({
// add this option
dataType: 'json'
})
And if you try that :
<?php
$age=$fet['Age'];
$champAgeExist = isset($age);
if (champAgeExist == true) {
echo $age
?>
I am using the Jquery function,
function ajax_fun(id,val)
{
$.ajax({
type: "GET",
url: "data.php",
dataType: "json",
data: { pid: 1, cart_id: id, val: val },
success: function (returndata){
console.log(returndata);
}
});
}
Call
ajax_fun(1,100);
data.php
<?php
if(isset($_GET['pid']) && $_GET['pid']==1)
{
$cart_id = $_GET['cart_id'];
$val = $_GET['val']+0.06;
$arr = array('cart_id'=> $cart_id, 'total' => $val);
json_encode($arr);
}
?>
Console returns 'null' . It didn't return cart_id and total.
Can anyone help?
.
json_encode($arr);
shoule be
echo json_encode($arr);
You forget to echo the result.
Full code:
<?php
if(isset($_GET['pid']) && $_GET['pid']==1) {
$cart_id = $_GET['cart_id'];
$val = $_GET['val']+0.06;
$arr = array('cart_id'=> $cart_id, 'total' => $val);
echo json_encode($arr); // write echo before json_encode($arr)
}
?>
RE-Write this line as...
echo json_encode($arr);
You need to add 'echo' before json_encode which return the data
<?php
if(isset($_GET['pid']) && $_GET['pid']==1)
{
$cart_id = $_GET['cart_id'];
$val = $_GET['val']+0.06;
$arr = array('cart_id'=> $cart_id, 'total' => $val);
echo json_encode($arr);
}
?>
I have another question:
Ajax Forms are working well. Most of them need to do mysql stuff and only return values if the entry could be written or not. I used just echo statements. For example echo "1"; if the values could be written and echo "2"; if the values could not be written.
Now I need to call back 3 variables. I know that I can write them in an array. My problem is just, that I can't return this variable into my visible site.
This is my JavaScript Code:
//Show statistic
$('.statistic_submit').click(function(){
if ($('#month').val() == 'none' || $('#year').val() == 'none') {
$("#dialog_empty").dialog( "open" );
return false;
}
var form = $('#statistic_view');
var data = form.serialize();
$.ajax({
url: "include/scripts/user_statistic.php",
type: "POST",
data: data,
success: function (reqCode) {
if (reqCode == 1) {
//Show generated table
$('.done').fadeOut('slow');
$('.done').fadeIn('slow');
}
if (reqCode == 2) {
//No values found
$('.done').fadeOut('slow');
$("#dialog_error").dialog( "open" );
}
}
});
return false;
});
This is my html code:
<div>
<form id="statistic_view" action="include/scripts/user_statistic.php" method="post">
<select name="month" id="month">
<option value="none" class="bold italic">Monat</option>
<?php
for($i=1; $i<=12; $i++){
if($i == $month)
echo "<option value=\"".$i."\" selected>".$month_name[$i]."</option>\n";
else
echo "<option value=\"".$i."\">".$month_name[$i]."</option>\n";
}
?>
</select>
<select name="year" id="year">
<option value="none" class="bold italic">Jahr</option>
<?php
for($i=2012; $i<=$year; $i++){
if($i == $year)
echo "<option value=\"".$i."\" selected>".$i."</option>\n";
else
echo "<option value=\"".$i."\">".$i."</option>\n";
}
?>
</select>
<br/><br/>
<div id="user_statistic">
<input type="submit" id="small" class="statistic_submit" value="Daten anzeigen">
</div>
</form>
<br />
<div class="done">
<p class="bold center"><?php echo "Besucher ".$month_name[$month]." ".$year; ?></p>
<canvas id="cvs" width="680" height="250">[No canvas support]</canvas>
<script>
chart = new RGraph.Line('cvs', <?php print($data_string) ?>);
chart.Set('chart.tooltips', <?php print($labels_tooltip) ?>);
chart.Set('chart.tooltips.effect', 'expand');
chart.Set('chart.background.grid.autofit', true);
chart.Set('chart.gutter.left', 35);
chart.Set('chart.gutter.right', 5);
chart.Set('chart.hmargin', 10);
chart.Set('chart.tickmarks', 'circle');
chart.Set('chart.labels', <?php print($labels_string) ?>);
chart.Draw();
</script>
</div>
</div>
And this my user_statistic.php:
... (mysql stuff)
/******************************/
/** Create diagram
/******************************/
$labels = array();
$data = array();
for ($j=1; $j<=$days; $j++) {
$labels[$j] =$j;
$data[$j] = $day_value[$j];
}
// Aggregate all the data into one string
$data_string = "[" . join(", ", $data) . "]";
$labels_string = "['" . join("', '", $labels) . "']";
$labels_tooltip = "['" . join("', '", $data) . "']";
//data written
echo "1";
So echo "1"; tells my script that everything is fine. But now I need $data_string, $labels_string and $labels_tooltip. So how can I return these values from user_statistic.php into my side?
Avoid converting arrays to strings on your own. If you need to pass a PHP array back to your jQuery, you should do so with the json_encode function:
echo json_encode( $array );
This will come through as a JSON object which you can then handle client-side. Your JSON string will be returned into the callback of your $.ajax method:
$.ajax({
url: "include/scripts/user_statistic.php",
type: "POST",
data: data,
dataType: 'json',
success: function ( response ) {
/* response is your array, in JSON form */
}
});
For instance, if our PHP script did the following:
$response = array(
'message' => 'Success',
'allData' => array( 'Jonathan', 'Mariah', 'Samuel', 'Sally' )
);
echo json_encode( $response );
We could alert the message from our jQuery like this:
success: function ( response ) {
alert( response.message );
}
The best approach here would be to return a json object. Create an array on server side -
$response['error_code'] = '1'; //everything ok. 0 if not ok
$response['data_string'] = 'this will have some data';
$response['labels_string'] = 'labels';
$response['labels_tooltip' = 'here goes the tooltips';
echo json_encode($response);
and in your javascript code, mention the return datatype as json -
$.ajax({
url: "include/scripts/user_statistic.php",
type: "POST",
data: data,
dataType: json,
success: function (reqCode) {
if (reqCode.error_code == 1) {
alert('this is the data string '+resCode.data_string);
//Show generated table
$('.done').fadeOut('slow');
$('.done').fadeIn('slow');
}
if (reqCode.error_code == 2) {
//No values found
$('.done').fadeOut('slow');
$("#dialog_error").dialog( "open" );
}
}
});