Undefined index and Invalid argument supplied for foreach() in CodeIgniter - php

In this below code when i update without checking any value it displays all the values from db.And error Undefined variable: records and Invalid argument supplied for foreach() at 113 and 119
Undefined variable: row in line 123
Trying to get property of non-object in 123in student_detail_view.
Please any one help me.
Controller student_site:
function index()
{
$data = array();
if($query = $this->student_model->get_exam_data())
{
$data['exam_data'] = $query;
}
$this->load->view('student_view', $data);
}
function studentupdate()
{
$data = array();
$exam_name = $this->input->post('exam_name');
$course_name = $this->input->post('course_name');
if($query = $this->student_model->get_exam_data())
{
$data['exam_data'] = $query;
}
if($query = $this->student_model->get_records($exam_name))
{
$data['records'] = $query;
}
if($query = $this->student_model->get_course_code_records($exam_name))
{
$data['course_records'] = $query;
}
if($query = $this->student_model->get_all_coursesubject_records())
{
$data['all_coursesubject_records'] = $query;
}
$this->load->view('student_detail_view', $data);
}
function studentcreate()
{
$data = array();
$exam_name = $this->input->post('exam_name');
$data['exam_name'] = $exam_name;
/*if($query = $this->student_model->get_exam_data())
{
$data['exam_data'] = $query;
}*/
if($query = $this->student_model->get_course_code_records($exam_name)) //get unique records of coursecode from the coursesubject table
{
$data['course_records'] = $query;
}
/*if($query = $this->student_model->get_subject_code_records($exam_name)) //write seperate function to get the the subject codes frm the coursesubject table based on the selected course code.
{
$data['subject_records'] = $query;
} */
$this->load->view('student_update', $data);
}
function subject_records()
{
$data = array();
$exam_name = $this->input->post('exam_name');
$course_name = $this->input->post('course_name');
if($query = $this->student_model->get_subject_records($exam_name,$course_name))
{
$data['subject_records'] = $query;
}
$this->load->view('subject_view', $data);
}
function create_student()
{
/*$data = $this->input->post();
print_r($data);
var_dump($this->input->post());
$data=$this->input->post();*/
$j=1;
$createstudent = $this->input->post('createstudent');
if( $this->input->post('createstudent') != false ){
foreach($createstudent as $row_id)
{
$this->form_validation->set_rules("register_number_" . $row_id, "Register No", "required|min_length[2]");
//$this->form_validation->set_rules("name_". $row_id,"`Name`","required|xss_clean|min_length[1]");
}
}
if ($this->form_validation->run() == FALSE){
$data["message"]="";
$this->load->view("student_detail_view",$data);
//$this->load->view("master_data/view_master_data_footer");
}
while($j<=$this->uri->segment(3))
{
$data = array(
'exam_name' => $this->input->post('exam_name'),
'register_number' => $this->input->post('register_number_'.$j),
'name' => $this->input->post('name_'.$j),
'course_code' => $this->input->post('course_name_id'.$j),
'subject_code' => $this->input->post('subject_name'),
);
// $exam_name = mysql_real_escape_string($_POST["exam_name_id".$j]);//
$register_number=$this->input->post('register_number_'.$j);
if ($register_number != "")
{
$this->student_model->add_record($data);
}
$j++;
}
redirect('student_site', 'refresh');
}
function delete()
{
$this->student_model->delete_row();
redirect('student_site', 'refresh');
}
function manage_student()
{
$data['title']="Manage Student";
//query model to get data results for form
$data=array();
if($query=$this->student_model->get_student_records()){
$data['records']=$query;
}
$editstudent = $this->input->post('editstudent');
if( $this->input->post('editstudent') != false ){
foreach($editstudent as $row_id)
{
$this->form_validation->set_rules("register_number_" . $row_id, "register_number", "required|min_length[2]");
}
}
if ($this->form_validation->run() == FALSE){
$data["message"]="";
//$this->load->view("master_data/view_master_data_header",$data);
//$this->load->view("master_data/view_master_data_nav");
$this->load->view("student_detail_view",$data);
//$this->load->view("master_data/view_master_data_footer");
} else {
// single update - working
if( $this->input->post('editstudent') != false )
{
foreach ($editstudent as $row_id)
{
$data = array(
'register_number' => $this->input->post('register_number_'.$row_id),
'name' => $this->input->post('name_'.$row_id),
'course_code' => $this->input->post('course_code_id'.$row_id),
'subject_code' => $this->input->post('subject_code_id'.$row_id),
);
$this->student_model->update_student_records( $row_id, $data );
}
$this->session->set_flashdata('dbaction', 'Selected Records have been updated successfully');
redirect('student_site', 'refresh');
}
}
}
$data = array(
'exam_name' => $this->input->post('exam_name_id'),
'register_number' => $this->input->post('register_number'),
'name' => $this->input->post('name'),
'subject_code' => $this->input->post('subject_code'),
'course_code' => $this->input->post('course_code'),
);
$exam_name = $this->input->post('exam_name');
$register_number = $this->input->post('register_number');
$name = $this->input->post('name');
$course_code = $this->input->post('course_code');
$subject_code = $this->input->post('subject_code');
$this->student_model->update_student_record($exam_name,$register_number,$name,$course_code,$subject_code,$data);
$data = array();
$query = $this->student_model->get_records($exam_name);
echo "<pre>";
print_r($query);
exit;
if($query)
{
$data['records'] = $query;
}
$this->load->view('student_detail_view', $data);
function crud()
{
}
function deleting()
{
}
model:student_model
function get_records($exam_name)
{
$this->db->where('exam_name',$exam_name);
$query = $this->db->get('student_table');
return $query->result();
}
function get_exam_data()
{
$this->db->distinct();
$this->db->select("CONCAT(exam_name, ' ', month,' ',year) AS fullexamname", FALSE);//this will concat the value
$query = $this->db->get('exam_table');
return $query->result();
}
function get_course_records($exam_name)
{
//echo "exam_name".$exam_name;
$this->db->select('exam_name,course_code');
$this->db->where('exam_name',$exam_name);
$query = $this->db->get('student_table');
return $query->result();
}
function get_subject_records($exam_name,$course_name)
{
//echo "exam_name inside get_subject_records".$exam_name;
$this->db->select('subject_code');
//$this->db->where('exam_name',$exam_name);
$this->db->where('course_code',$course_name);
$query = $this->db->get('coursesubject');
return $query->result();
}
function get_all_coursesubject_records()
{
//echo "exam_name inside get_subject_records".$exam_name;
$this->db->select('course_code');
$this->db->select('subject_code');
$query = $this->db->get('coursesubject');
return $query->result();
}
function get_course_code_records($course_name)
{
$query = $this->db->get('coursesubject');
return $query->result();
}
function get_subject_code_records()
{
$this->db->distinct();
$this->db->select('subject_code');
$query = $this->db->get('coursesubject');
return $query->result();
}
function update_student_record($exam_name,$register_number,$name,$course_code, $subject_code,$data)
{
echo "exam_name".$exam_name;
echo "register_number".$register_number;
echo "name".$name;
$this->db->where('exam_name',$exam_name);
$this->db->where('register_number',$register_number);
//$this->db->where('name',$name);
//$this->db->where('course_code',$course_code);
//$this->db->where('subject_code',$subject_code);
$this->db->update('student_table',$data);
}
view :student_detail_view
<script type="text/javascript" src="<?php echo base_url();?>js/jquery.dataTables.js" ></script>
<script type="text/javascript" src="<?php echo base_url();?>js/jquery.dataTables.min.js" ></script>
<section id="tables">
<script>
jQuery(document).ready(function() {
oTable = jQuery('#studenttable').dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers"
});
});
</script>
<script type="text/javascript" charset="utf-8">
function get_studentdetails() {
var exam_name = jQuery('#exam_name_id').val();
//alert("exam_name"+exam_name);
jQuery.ajax({
data: {
exam_name: exam_name,
},
type: 'POST',
url: 'student_site/studentupdate',
success: function(data){
//alert("inside change");
console.log(data);
jQuery('#details').html(data);
jquery('#deleting').html(data);
}
});
jQuery(document).ready(function(){
jQuery.ajax({
data: {
exam_name: exam_name,
},
type: 'POST',
url: 'student_site/studentcreate',
success: function(data){
//alert("inside change");
console.log(data);
jQuery('#crud').html(data);
jquery('#deleting').html(data);
}
});
});
}
function CheckBoxVerification(From)
{
alert('hai');
alert('hai:' $("table input[type=checkbox]:checked").length);
if(From == "Insert")
{
if(!!$('#rowInsert input:checked').length == false)
{
alert('please select at least one check box to Create ...!');
}
}
if(From == "Update")
{
if(!!$('#rowUpdate input:checked').length == false)
{
alert('please select at least one check box to Update ...!');
}
}
}
function get_subjectdetails() {
//var index = jQuery('#index').val();
var course_name = jQuery('#course_name_id').val();
//alert("course_name"+course_name);
//var exam_name = jQuery('#course_name_id>option:selected').text();
var exam_name = jQuery('#exam_name_id').val();
var ssubject_code = jQuery('#ssubject_code_id').val();
//var partsArray = exam_name.split('.');
//alert("ssubject_code"+ssubject_code);
//alert("course_name"+course_name);
//alert("exam_name"+exam_name);
jQuery.ajax({
data: 'exam_name='+exam_name+'&course_name=' + course_name,
type: 'POST',
url: 'student_site/subject_records',
success: function(data){
//alert("inside change");
console.log(data);
//alert ("data"+data);
//for(var j = course_name; j < ssubject_code; j++)
//{
jQuery('#ssubject_code').empty().append(data);
//}
}
});
}
</script>
<?php
$attributes=array(
'name'=>'updatecustomer',
'id'=>'updatecustomer'
);
echo form_open('student_site/manage_student',$attributes);
?>
<div id="validation_failed">
<?php
echo validation_errors();
?>
<?php $data = array();
foreach ($records as $row)
{
$data[$row->course_code] = $row->course_code;
}
$subject_data = array();
foreach ($records as $row)
{
$subject_data[$row->subject_code] = $row->subject_code;
}
var_dump($row->course_code );
?>
<div id="Processy">
<table class="display table table-bordered table-striped" id='studenttable'>
<thead>
<tr font style='font-size:13px'>
<th> </th>
<th> </th>
<th>Register Number</th>
<th>Name </th>
<th>Course Code</th>
<th>Subject Code</th>
</tr></thead>
<?php if(isset($records)) : foreach($records as $row) : ?>
<tr >
<td>
<?php echo anchor('student_site/delete/'.$row->id, 'Delete',array('onClick'=>"return confirm('Are you sure want to delete..?')")); ?>
</td>
<td id="rowUpdate">
<input type=checkbox name="editstudent[]" id="editstudent[]" value="<?php echo $row->id ?>">
</td>
<td ><input class="inputmedium span2" type="text" name="register_number_<?php echo $row->id ?>" id="register_number_<?php echo $row->id ?>" value="<?php echo $row->register_number; ?>" ></td>
<td ><input class="inputmedium span2" type="text" name="name_<?php echo $row->id ?>" id="name_<?php echo $row->id ?>" value="<?php echo $row->name; ?>" ></td>
<td >
<?php
$js = 'class="dropdown_class" id="course_code_id'.$row->id.'" onChange="get_subjectdetails()" ';
$js_name = 'course_code_id'.$row->id;
echo form_dropdown($js_name, $data, $row->course_code, $js);
?>
</td>
<td>
<?php
$js = 'class="dropdown_class" id="subject_code_id'.$row->id.'"';
$js_name = 'subject_code_id'.$row->id;
echo form_dropdown($js_name, $subject_data, $row->subject_code, $js);
?>
<div id="ssubject_code" ></div>
<input type="hidden" name="ssubject_code" id="ssubject_code" value="ssubject_code"/>
</td>
</tr>
<?php endforeach; ?>
</table>
</div>
<center>
<br /><input type="submit" class="btn-success btn" value="Update Student"></center>
<?php else : ?>
<h2>No records were returned.</h2>
<?php endif; ?>

you should check if $record is set and then use foreach.
Try something like:
if(isset($records)){
foreach($records as $row){
//do things here
}
}

Try echo on the records you get from the query as follows:
function update()
{
$data = array(
'exam_name' => $this->input->post('exam_name_id'),
'register_number' => $this->input->post('register_number'),
'name' => $this->input->post('name'),
'subject_code' => $this->input->post('subject_code'),
'course_code' => $this->input->post('course_code'),
);
$exam_name = $this->input->post('exam_name');
$register_number = $this->input->post('register_number');
$name = $this->input->post('name');
$course_code = $this->input->post('course_code');
$subject_code = $this->input->post('subject_code');
$this->student_model->update_student_record($exam_name,$register_number,$name,$course_code,$subject_code,$data);
$data = array();
$query = $this->student_model->get_records($exam_name);
echo "<pre>";
print_r($query);
exit;
if($query)
{
$data['records'] = $query;
}
$this->load->view('student_detail_view', $data);
}

Related

Pagination, searching and sorting is not working in jquery datatable in codeigniter using ajax

Currently i am working on eCommerce website in that i have to display all data from database to datatable. Data is coming properly in datatable but searching, sorting and pagination is not working.If any body know solution than please help. Below is my code
Controller.php
Public function transaction_data()
{
$id = $this->session->Vendordetail['id'];
$transactionData = $this->Mdl_vendor_payment->get_order_list($id);
$requestData= $_REQUEST;
$totalData = count($transactionData);
$totalFiltered = count($transactionData);
$return_days = $this->Mdl_common->get_setting('shipping_charge');
foreach($transactionData as $transaction){
$product = $this->Mdl_common->product_id($transaction['prodouct_id']);
$data['order_id'] = $transaction['order_id'];
$data['created'] = $transaction['created'];
if($transaction['status'] == 5){
$data['status'] = '<h5><span class="label label-danger">Cancelled</span></h5>';
}else if($transaction['status'] == 4){
$data['status'] = '<h5><span class="label label-default">Return</span></h5>';
}else if($transaction['status'] == 3){
$data['status'] = '<h5><span class="label label-success">Success</span></h5>';
}else if($transaction['status'] == 2){
$data['status'] = '<h5><span class="label label-primary">Dispatch</span></h5>';
}else if($transaction['status'] == 1){
$data['status'] = '<h5><span class="label label-primary">Ready To Dispatch</span></h5>';
}else{
$data['status'] = '<h5><span class="label label-primary">Approve</span></h5>';
}
$data['price'] = '<i class="fa fa-rupee"></i> '.$transaction['price']*$transaction['qty'];
$data['settlement_price'] = '<i class="fa fa-rupee"></i> '.$transaction['settlement_price']*$transaction['qty'];
$shipping_charge = $return_days['value'] * ($transaction['qty'] * $product['weight']);
$data['shipping_charge'] = '<i class="fa fa-rupee"></i> '.$shipping_charge;
$data['commission_fee'] = ($transaction['price']*$transaction['qty'])-($transaction['settlement_price']-$transaction['qty']);
$data['payable_amount'] = ($transaction['settlement_price']*$transaction['qty'])-$shipping_charge;
$data['order'] = $transaction;
$data['product'] = $product;
$assignment_datas[] = $data;
}
$json_data = array(
"draw" => intval( $requestData['draw'] ),
"recordsTotal" => intval( $totalData ),
"recordsFiltered" => intval( $totalFiltered ),
"data" => $assignment_datas
);
echo json_encode($json_data);
die;
}
Below is the code for view file
View.php
$(document).ready(function() {
var dt = $('#datatable_example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url":"<?php echo base_url(); ?>index.php/Vendor_payment/transaction_data",
"type":"POST",
},
"columns": [
{
"class": "details-control",
"orderable": false,
"data": null,
"defaultContent": ""
},
{ "data": "order_id" },
{ "data": "created" },
{ "data": "status" },
{ "data": "price" },
{ "data": "settlement_price" },
{ "data": "shipping_charge" }
],
"order": [[0, 'asc']]
} );
// Array to track the ids of the details displayed rows
var detailRows = [];
$('#datatable_example tbody').on( 'click', 'tr td.details-control', function () {
var tr = $(this).closest('tr');
var row = dt.row( tr );
var idx = $.inArray( tr.attr('id'), detailRows );
if ( row.child.isShown() ) {
tr.removeClass( 'details' );
row.child.hide();
// Remove from the 'open' array
detailRows.splice( idx, 1 );
}
else {
tr.addClass( 'details' );
row.child( format( row.data() ) ).show();
// Add to the 'open' array
if ( idx === -1 ) {
detailRows.push( tr.attr('id') );
}
}
} );
// On each draw, loop over the `detailRows` array and show any child rows
dt.on( 'draw', function () {
$.each( detailRows, function ( i, id ) {
$('#'+id+' td.details-control').trigger( 'click' );
} );
} );
} );
This code is work fine for me...
In view page:
<table id="user_datatable" class="table table-bordered table-striped">
<thead>
<tr>
<th style="width: 5%;">ID</th>
<th>Client name</th>
<th>Mobile</th>
<th>Email</th>
<th class="col-md-2">Action</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script type="text/javascript">
$(document).ready(function () {
$('#user_datatable').DataTable({
'pageLength': 1,
'processing': true,
'serverSide': true,
'serverMethod': 'post',
'ajax': {
'url': '<?php echo base_url(); ?>user/userList'
},
'columns': [{
data: 'id'
},
{
data: 'name'
},
{
data: 'mobile'
},
{
data: 'email'
},
{
data: 'action'
},
]
});
});
</script>
In Controller page
public function userList() {
$postData = $this->input->post();
$data = $this->Data_model->getUserList($postData);
echo json_encode($data);
}
In Model page
Set the table name in $table variable
// $table = 'clients';
Add column name whatever you add in datatable
$searchQuery = " (name like '%".$searchValue."%' or mobile like '%".$searchValue."%' or email like'%".$searchValue."%' ) ";
function getUserList($postData=null) {
$response = array();
$table_name = 'clients';
## Read value
$draw = $postData['draw'];
$start = $postData['start'];
$rowperpage = $postData['length']; // Rows display per page
$columnIndex = $postData['order'][0]['column']; // Column index
$columnName = $postData['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $postData['order'][0]['dir']; // asc or desc
$searchValue = $postData['search']['value']; // Search value
## Search
$searchQuery = "";
if($searchValue != ''){
$searchQuery = " (name like '%".$searchValue."%' or mobile like '%".$searchValue."%' or email like'%".$searchValue."%' ) ";
}
## Total number of records without filtering
$this->db->select('count(*) as allcount');
$records = $this->db->get($table_name)->row();
$totalRecords = $records->allcount;
## Total number of record with filtering
$this->db->select('count(*) as allcount');
if($searchValue != '')
$this->db->where($searchQuery);
$records = $this->db->get($table_name)->row();
$totalRecordwithFilter = $records->allcount;
## Fetch records
$this->db->select('*');
if($searchValue != '')
$this->db->where($searchQuery);
$this->db->order_by($columnName, $columnSortOrder);
$this->db->limit($rowperpage, $start);
$records = $this->db->get($table_name)->result();
$data = array();
foreach($records as $key => $record) {
$data[] = array(
"id"=> ($key + 1),
"name"=>$record->name,
"mobile"=>$record->mobile,
"email"=>$record->email,
"action"=>"<a href='".base_url()."user/update/".$record->id."' type='button' class='btn btn-success'>Update</a><a href='".base_url()."user/delete/".$record->id."' type='button' class='btn btn-danger' style='margin-left: 5px;'>Delete</a>",
);
}
## Response
$response = array(
"draw" => intval($draw),
"recordsTotal" => $totalRecordwithFilter,
"recordsFiltered" => $totalRecords,
"data" => $data
);
return $response;
}

trying to do facebook like automatic content scrolling but the data is not showing correctly

designing a Facebook like scrolling system the data shows but it does not show the first 5 values and it shows the values in repetition
here is my code:
view:
$(document).ready(function() {
var total_record = 0;
var total_groups = <?php echo $total_data; ?>;
$('#results').load("<?php echo base_url() ?>user/load_more", {'group_no':total_record}, function() {total_record++;});
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height())
{
if(total_record <= total_groups)
{
loading = true;
$('.loader_image').show();
$.post('<?php echo site_url() ?>user/load_more',{'group_no': total_record},
function(data){
if (data != "") {
$("#results").append(data);
$('.loader_image').hide();
total_record++;
}
});
}
}
});
});
then my controller
public function load_more()
{
$group_no = $this->input->post('group_no');
//print_r($group_no);
$content_per_page = 10;
$start = ceil($group_no * $content_per_page);
//print_r($start);
$this->load->model('Pmodel');
$user_id = $this->session->userdata('user_id');
$all_content = $this->Pmodel->get_all_content($user_id,$start,$content_per_page);
// echo '<pre>';
//print_r($all_content);
if(isset($all_content) && is_array($all_content) && count($all_content)) :
foreach ($all_content as $key => $content) :
echo '<li>'.$content->status.'</li>';
echo '<p>'.$content->status_image.'</p>';
endforeach;
endif;
// echo '<pre>'; print_r($this->data['labels_message']); exit;
}
and then my model
public function get_all_content($id,$start,$content_per_page)
{
$query=$this->db->select('*')
->from('post_status')
->where('user_id',$id)
->limit($start,$content_per_page)
->get();
//echo "<pre>";
//print_r($query);
//var_dump($query);
$result = $query->result();
//echo "<pre>";
//print_r($result);
return $result;
}
how to show the data according to the database
let me add a image for database

Running Ajax within bootstrap

I'm working on a CMS and the main core of the theming is with bootstrap. My issue arises with Ajax. I have my login module and it works fine to login and run the ajax, but the issue that is my dropdown menu does not work when I include the ajax libraries.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="http://www.bootstrapcdn.com/twitter-bootstrap/2.2.1/js/bootstrap.min.js"></script>
Those are the libraries I'm including to run ajax, and my ajax code
plus the form that I'm using
<form name="panel_login" id="panel_login" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="process" id="process" value="panel_login">
<p><label for "username">Username</label>
<input type="text" id="username" name="username" class="text"></p>
<p><label for "password">Password</label>
<input type="password" id="password" name="password" class="text"></p>
<p>
<p id="error"></p>
<input type="submit" id="submit_login" class="button" value="Login"></p>
</form>
<script>
$(function() {
$('#submit_login').click(function(event) {
$.ajax({
type: $("#panel_login").attr("method"),
url: $("#panel_login").attr('action'),
data: $("#panel_login").serialize(),
success: function(data){
if(data == "0" ) {
$("#error").html("Incorrect Username or Password");
}
else {
location.reload();
}
}
});
event.preventDefault();
});
});
</script>
The process is thrown within a case switch which works fine, the only issue at this point is the broken dropdown menu.
The Dropdown Menu Code: (nav.dropdown.php)
<li class="dropdown">
<?php echo $this->dtitle; ?> <b class="caret"></b>
<ul class="dropdown-menu">
<?php $perms = $this->perms; ?>
<?php self::GetChildren($perms); ?>
</ul>
Which is included through a PHP function file
class DViews {
protected $db;
public $tprefix;
public $theme;
public function __construct() {
$this->db = new DDB();
$this->tprefix = TPREFIX;
$this->theme = theme_p;
}
public function LoadNavigation($perm, $menu) {
switch($perm) {
case "all";
self::AllNavigation($perm, $menu);
break;
case "user";
self::AllNavigation($perm, $menu);
break;
case "guest";
self::AllNavigation($perm, $menu);
break;
}
}
public function AllNavigation($perm, $menu) {
$query = <<<SQL
SELECT id,title,content,menuid,identifier
FROM {$this->tprefix}pages
WHERE active = :true
AND visibility = :all
AND menuid = :menu
SQL;
$resource = $this->db->db->prepare( $query );
$resource->execute( array (
':true' => 1,
':all' => $perm,
':menu' => $menu,
));
foreach($resource as $row)
{
$this->perms = $perm;
$this->id = $row['id'];
$this->title = $row['title'];
$this->identifier = $row['identifier'];
self::CheckParent($perm);
}
}
public function CheckParent($perm) {
$query = <<<SQL
SELECT parent
FROM {$this->tprefix}pages
WHERE parent = :id
AND active = :1
AND visibility = :perms
SQL;
$resource = $this->db->db->prepare( $query );
$resource->execute( array (
':id' => $this->id,
':1' => 1,
':perms' => $perm,
));
if(PRETTYURLS == true) {
$this->dlink = $this->identifier;
}
else {
$this->dlink = "?id=".$this->identifier."";
}
$this->dtitle = $this->title;
if($resource->rowCount() > 0 ) {
include($this->theme.'/'.ACTIVETHEME.'/nav.dropdown.php');
}
else {
include($this->theme.'/'.ACTIVETHEME.'/nav.single.php');
}
}
public function GetChildren($perm) {
$query = <<<SQL
SELECT id,title,content,menuid,identifier
FROM {$this->tprefix}pages
WHERE active = :true
AND visibility = :all
AND parent = :parent
SQL;
$resource = $this->db->db->prepare( $query );
$resource->execute( array (
':true' => 1,
':all' => $perm,
':parent' => $this->id,
));
foreach($resource as $row)
{
$this->title = $row['title'];
$this->dtitle = $this->title;
$this->identifier = $row['identifier'];
if(PRETTYURLS == true) {
$this->dlink = $this->identifier;
}
else {
$this->dlink = "?id=".$this->identifier."";
}
include($this->theme.'/'.ACTIVETHEME.'/nav.single.php');
}
}
Tried Adding
var $j = jQuery.noConflict();
$j(function() {
$j('#submit_logout').click(function(event) {
$j.ajax({
type: $("#panel_logout").attr("method"),
url: $("#panel_logout").attr('action'),
data: $("#panel_logout").serialize(),
success: function(data){
location.reload();
}
});
event.preventDefault(); // Prevent the form from submitting via the browser.
});
});
to no avail.
Not sure why it worked, but I stumbled into a resolution on the millions of bootstrap forums that it seems are out there.
Linking to the external
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
Instead of local seems to have resolved the issue between Jquery and Bootstrap conflicts

Ajax calls resulting in an error[object Object]

I am getting an error[object Object] while trying to pass a value through ajax calls. I am using jquery selector to get value of checkbox. And trying to pass it through ajax so that I can get only the checkbox value that I have selected. But getting an error. Thanks.
Here is my code:
dashboard.php
if($param['aktion'] == 'save-widget-vehicle')
{
$page['register-fahrzeuge'] = array(
1 => array( 'Fahrzeug','aktiv',$page['script'],''),
0 => array( 'Edit-Fahrzeug','enabled',$page['script'],'',''),
);
$opts = !empty($param['filterOpts']) ? $param['filterOpts'] : array();
$tmp = array();
foreach ($opts as $opt) {
$tmp[] = '"'.$opt.'"';
}
$query =
'SELECT Fahrzeuge.dsnr,name
FROM Fahrzeuge
INNER JOIN ohne_fahrzeuge ON Fahrzeuge.dsnr = ohne_fahrzeuge.dsnr
WHERE Fahrzeuge.name IN ('.implode(",", $tmp).')';
$result = mysql_query($query, $myConnection);
$data = array();
$html = '<table width="538" cellspacing="0" cellpadding="0" border="0">
<tr>
<td>
<div>'.CreateRegister($page['register-news']).'</div>
'.CreateMessage().'
<div class="cont-liste-verlauf register"> ';
while($row = mysql_fetch_array($result)){
//$news_result = $fahrzeuge['name'];
$html .= '<table id="fahrzeuge">
<tr>
<td>
'. $data[] = $row .'
</td>
</tr> ';
}
$html .= '</table>
</div>
</td>
</tr>
</table>';
$return = array(
'status' => 1,
'html' => $html
);
echo json_encode($return);
die();
$param['aktion'] = 'get-widget-vehicle';
}
dashboard.js
function getFahrzeuge() {
var opts = [];
$("input[type=checkbox]").each(function () {
if (this.checked) {
opts.push($(this).attr("id"));
}
});
return opts;
}
function saveFahrzeugeWidget(opts){
if(!opts || !opts.length){
opts = allFahrzeuge;
}
$.ajax({
type: "POST",
url: "ajax/dashboard.php",
dataType : 'json',
cache: false,
data: {filterOpts: opts, 'aktion' : 'save-widget-vehicle'},
success: function(data){
// $('#fahrzeuge').html(makeTable(records));
$('#fahrzeuge').html(data.html);
},
error: function(data){
alert('error' + data);
}
});
}
$('#fahrzeuge .butt-rahmen').live('click', function(){
if($(this).attr('id') == 'submitId')
var opts = getFahrzeuge();
saveFahrzeugeWidget(opts);
});
var allFahrzeuge = [];
$("input[type=checkbox]").each(function(){
allFahrzeuge.push($(this)[0].id)
})

Javascript Password Change Form Validation doesn't work on IE8

got this function to validate two fields from a changing password form and it's doesn't seem to work at IE8. FF, Opera, Safari and Chrome work.
function chk_form_pw()
{
if(document.getElementById('new_passwd').value == '')
{
alert("<?php _e('Please enter New Password') ?>");
document.getElementById('new_passwd').focus();
return false;
}
if(document.getElementById('new_passwd').value.length < 5 )
{
alert("<?php _e('Please enter New Password minimum 5 chars') ?>");
document.getElementById('new_passwd').focus();
return false;
}
if(document.getElementById('cnew_passwd').value == '')
{
alert("<?php _e('Please enter Confirm New Password') ?>");
document.getElementById('cnew_passwd').focus();
return false;
}
if(document.getElementById('cnew_passwd').value.length < 5 )
{
alert("<?php _e('Please enter Confirm New Password minimum 5 chars') ?>");
document.getElementById('cnew_passwd').focus();
return false;
}
if(document.getElementById('new_passwd').value != document.getElementById('cnew_passwd').value)
{
alert("<?php _e('New Password and Confirm New Password should be same') ?>");
document.getElementById('cnew_passwd').focus();
return false;
}
}
This is the form:
<form name="registerform" id="registerform" action="<?php echo get_option( 'siteurl' ).'/?page=account&chagepw=1'; ?>" method="post">
<p><label><?php _e('New Password'); ?> <span class="indicates">*</span></label></p>
<p><input type="password" name="new_passwd" id="new_passwd" class="lostpass_textfield" /></p>
<p><label><?php _e('Confirm New Password'); ?> <span class="indicates">*</span></label></p>
<p><input type="password" name="cnew_passwd" id="cnew_passwd" class="lostpass_textfield" /></p>
<p><input type="submit" name="Update" onclick="return chk_form_pw();" value="<?php _e('Update Password') ?>" class="btn grey"/></p>
</form>
And here is the chagepw=1 thing:
<?php
if($_POST)
{
if($_REQUEST['chagepw'])
{
$new_passwd = $_POST['new_passwd'];
if($new_passwd)
{
$user_id = $current_user->data->ID;
wp_set_password($new_passwd, $user_id);
$message1 = "Password Changed successfully.You need to sign back in.";
}
}else
{
$user_id = $userInfo['ID'];
$user_add1 = $_POST['user_add1'];
$user_add2 = $_POST['user_add2'];
$user_city = $_POST['user_city'];
$user_state = $_POST['user_state'];
$user_country = $_POST['user_country'];
$user_postalcode = $_POST['user_postalcode'];
$buser_add1 = $_POST['buser_add1'];
$buser_add2 = $_POST['buser_add2'];
$buser_city = $_POST['buser_city'];
$buser_state = $_POST['buser_state'];
$buser_country = $_POST['buser_country'];
$buser_postalcode = $_POST['buser_postalcode'];
$user_address_info = array(
"user_add1" => $user_add1,
"user_add2" => $user_add2,
"user_city" => $user_city,
"user_state" => $user_state,
"user_country" => $user_country,
"user_postalcode"=> $user_postalcode,
"buser_name" => $_POST['buser_fname'].' '.$_POST['buser_lname'],
"buser_add1" => $buser_add1,
"buser_add2" => $buser_add2,
"buser_city" => $buser_city,
"buser_state" => $buser_state,
"buser_country" => $buser_country,
"buser_postalcode"=> $buser_postalcode,
);
update_usermeta($user_id, 'user_address_info', serialize($user_address_info)); // User Address Information Here
$userName = $_POST['user_fname'].' '.$_POST['user_lname'];
$updateUsersql = "update $wpdb->users set user_nicename=\"$userName\", display_name=\"$userName\" where ID=\"$user_id\"";
$wpdb->query($updateUsersql);
$message = "Information Updated successfully.";
}
}
$userInfo = $General->getLoginUserInfo();
$user_address_info = unserialize(get_user_option('user_address_info', $user_id));
$user_add1 = $user_address_info['user_add1'];
$user_add2 = $user_address_info['user_add2'];
$user_city = $user_address_info['user_city'];
$user_state = $user_address_info['user_state'];
$user_country = $user_address_info['user_country'];
$user_postalcode = $user_address_info['user_postalcode'];
$display_name = $userInfo['display_name'];
$display_name_arr = explode(' ',$display_name);
$user_fname = $display_name_arr[0];
$user_lname = $display_name_arr[2];
$buser_add1 = $user_address_info['buser_add1'];
$buser_add2 = $user_address_info['buser_add2'];
$buser_city = $user_address_info['buser_city'];
$buser_state = $user_address_info['buser_state'];
$buser_country = $user_address_info['buser_country'];
$buser_postalcode = $user_address_info['buser_postalcode'];
$bdisplay_name = $user_address_info['buser_name'];
$display_name_arr = explode(' ',$bdisplay_name);
$buser_fname = $display_name_arr[0];
$buser_lname = $display_name_arr[2];
if($_SESSION['redirect_page'] == '')
{
$_SESSION['redirect_page'] = $_SERVER['HTTP_REFERER'];
}
if(strstr($_SESSION['redirect_page'],'page=checkout'))
{
$login_redirect_link = get_option( 'siteurl' ).'/?page=checkout';
}
?>
A smoother solution would be jQuery. There you can load a loading-animation, put color like red/green on wrong/correct and simplified print out text depending on what happening to the form.
Download jQuery from: http://docs.jquery.com/Downloading_jQuery
Then you insert it in the html code like this:
<script type="text/javascript" src="jquery.js">
</script>
Then you can have a valid.js like this:
$(document).ready(function () {
var validatefield = $('#validatefield');
$('#validatefield').keyup(function () {
var t = this;
if (this.value != this.lastValue) {
if (this.timer) clearTimeout(this.timer);
validatefield.html('<img src="images/Here_you_can_put_your_gif_animation"
alt="Loading..."
height="16" width="16"/>');
this.timer = setTimeout(function () {
$.ajax({
url: 'check_field.php',
data: 'action=check_field&field=' + encodeURIComponent(t.value),
dataType: 'json',
type: 'post',
success: function (j) {
if (j.ok) {
validatefield.html(j.msg);
}
else if ($("#validatefield").val() == "")
{
validatefield.html('');
}
else {
validatefield.html(j.msg);
}
}
});
}, 200);
this.lastValue = this.value;
}
});
});
Then in the check_field.php, have this;
echo json_encode(check_field($_POST['field']));
function check_field($field) {
$fieldSum = stripslashes(strip_tags(trim(htmlspecialchars($field))));
$response = array();
if (strlen($fieldSum) > 15) {
$response = array(
'ok' => false,
'msg' => "The field characters were over 15!");
}
else
{
$response = array(
'ok' => true,
'msg' => "Correct");
}
return $response;
}
The id #validatefield is an id inside the html code that you have to create in order to print things out.
Example:
<div id="validatefield">Here comes the text etc, from the valid.js</div>
Finally got it done using the JQuery script posted before:
http://code.google.com/p/form-validation-engine/downloads/list
It's been really easy to fit into my previous code and works flawlessly through every browser tested.
Thank you all for your help!

Categories