knockout data-binding with ajax php result not working - ajax

I am new to knockout js and i am trying to create a table whose data comes from database using php ajax .data-binding not working with ajax php result, while if i create a table in same page with data-binding variable its working with that table.How can i make ajax results work with knockout . Thanks for helping
Below are my codes
data loading php:
include("db.php");
$result=mysqli_query($conn,"select * from codes");
$par='\$parent';
echo '<table class="table table-striped box" >
<thead>
<tr>
<td align=center> <b>Code</b></td>
<td align=center><b>Starting Date</b></td>
<td align=center><b>Closing Date</b></td>
<td align=center><b>Select</b></td></tr></thead>
';
echo '<tbody data-bind="foreach:{data:rows,as:\'Row\'}">';
echo "<tr>
<td data-bind='text:Row.codes'></td>
<td data-bind='text:Row.sDate'></td>
<td data-bind='text:Row.eDate'></td>
<td align=center><button data-bind='click:$par.selectRow' class='btn btn-orange'>Select</button></td>
</tr>";
while($data = mysqli_fetch_row($result))
{
echo "<tr >";
echo "<td align=center data-bind='text:Row.codes'>$data[1]</td>";
echo "<td align=center data-bind='text:Row.sDate'>$data[2]</td>";
echo "<td align=center data-bind='text:Row.eDate'>$data[3]</td>";
echo "<td align=center><button data-bind='click:$par.selectRow' class='btn btn-orange addd'>Select</button></td>";
echo "</tr>";
}
echo "</tbody></table>";
and my ajax code for loading:
$(document).ready(function(){
$.ajax({
type:"POST",
url:"load.php",
dataType:"html",
success: function(response){
$("#codetable").html(response);
}
});
});
and my knockout script
$(document).ready(function(){
function Row(codes,sDate,eDate){
this.codes=codes;
this.sDate=sDate;
this.eDate=eDate;
}
var myRowViewModel = new function(){
var current= this;
this.SelectedRow = ko.observable(null);
this.rows=ko.observableArray([
new Row("45sd9e","10-08-2018",1000),
new Row("45sd9e","10-08-2018",1000),
]);
this.selectRow = function(Row){
current.SelectedRow(Row)
alert(Row.codes);
}
}
ko.applyBindings(myRowViewModel);
});

Well now i have figured out what problem was.I changed my data to json and its working now.

Related

How to write code insert multiple data to database Laravel

I want to fill and insert a lot of duplicates into the database. In the same table But i don't know how to write code on the controller. Laravel
html
<table class="table ">
<thead>
<tr>
<td width="5%"><center>ลำดับ</center></td>
<td width="20%"><center>เลขบัญชี</center></td>
<td width="40%"><center>ชื่อบัญชี</center></td>
<td width="35%"><center>จำนวนเงิน</center></td>
<td width="10%"><center></td>
</tr>
</thead>
<tbody class="resultbody">
</tbody>
</table>
Script
$(function () {
$('.add').click(function () {
var n = ($('.resultbody tr').length - 0) + 1;
var tr =
'<tr><td width="5%" class="no" name="svae_no"><center>' + n + '</center></td>' +
'<td width="20%"><input type="text" class="name form-control" name="rows[0][save_id]"></td>'+
'<td width="40%"><input type="text" class="fname form-control" name="rows[0][save_name]"></td>'+
'<td width="35%"><input type="text" class="fname form-control" name="rows[0][save_money]"></td>'+
'<td width="10%"><input type="button" class="btn btn-danger delete" value="x"></td></tr>';
$('.resultbody').append(tr);
});
$('.resultbody').delegate('.delete', 'click', function () {
$(this).parent().parent().remove();
});
});
controller add data
public function add(Request $request){$save_no = $request->input('save_no');
$save_id = $request->input('save_id');
$save_name = $request->input('save_name');
$save_money = $request->input('save_money');$data_save=array(
'mem_died_id'=>$mem_died_id,
'save_no'=>$save_no,
'save_id'=>$save_id,
'save_name'=>$save_name,
'save_money'=>$save_money);
DB::table('died_save')->insert($data_save);return back();
If we work on big project and then we maybe require to add multiple rows on database using laravel eloquent. Laravel provide insert method for bulk records create on db.
In bellow example you can see i use multidimensional $myItems array variable and that insert multiple records same time using DB::insert(). So let's see and try this.
Example:
$myItems = [
['title'=>'HD Topi','description'=>'It solution stuff'],
['title'=>'HD Topi 2','description'=>'It solution stuff 2'],
['title'=>'HD Topi 3','description'=>'It solution stuff 3']
];
DB::table("items")->insert($myItems);

data getting lost after any operation on data-table while loading rows using ajax

I am fetching dataTable rows using Ajax from my controller in CodeIgniter.
I have fetched it successfully, but the problem is rows get lost while doing any operation on dataTable like sorting, searching.
But after refreshing a page it came back.
Here is my Ajax Script:
$('#dataTable_choose').DataTable({
responsive: true
});
$('body').on('click', '.getJobApplication', function(e) {
//alert();
var noteId = $(this).data('noteId');
var note_id = { id : noteId }
$.ajax({
type: 'POST',
async: true,
dataType: 'Json',
url: get_table_rows,
data: note_id,
success: function (response) {
if(response.length > 0){
for (i = 0; i < response.length; i++) {
innerhtml += "<tr>" +
"<td>"+response[i].column1+"</td>" +
"<td>"+response[i].column2+"</td>" +
"<td>"+response[i].column3+"</td>" +
"<td>"+response[i].column4+"</td>" +
"<td><span class='label label-info'>"+column5+"</span></td>" +
"<td>"+
"<button type='button' class='btn btn-success waves-effect waves-light' data-secid="+response[i].id2+" " +
" data-fiid = "+response[i].id+" >Choose</button>" +
"</td>" +
"</tr>";
$('#table_body').html(innerhtml);
}
} else {
console.log('error');
}
},
error: function (msg)
{
console.log('error');
}
});
});
Here is the Table HTML Code:
<table id="dataTable_choose" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>Job Title</th>
<th>Qualification</th>
<th>Qualification Major</th>
<th>Candidate Name</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody id="table_body">
</tbody>
</table>
After changing your DataTable's content with ajax, you need to clear the DataTable and redraw it. Below is a code that works for me (tried to add your ID's, please verify that they are correct and implement right in your code):
success: function (response) {
//DRAW YOUR innerhtml HERE, as you already do
$("#dataTable_choose").dataTable().fnClearTable(); //clear the table
$('#dataTable_choose').dataTable().fnDestroy(); //destroy the datatable
$('#table_body').html(innerhtml); //add your new data
$('#dataTable_choose').DataTable({ //redraw with new data
//YOUR OPTIONS HERE
});
});

Searching data using Ajax in CakePHP

I am using CakePHP 2.3.6. In one of my projects, I have to implement the Searching feture, using AJAX. Normally, this is working, but I want that the page won't reload, the result table will be immediately updated with the data.
This is the Controller code:
public function searchData(){
$this->set(............);
$this->set(............);
$this->set(............);
if($this->request->is('post')){
$this->layout='ajax';
$this->autoRender=false;
if(!empty($data)){
$data=$this->request->data;
// Generating options
.
.
.
$result=$this->ModelName->find('all',$options);// "$options" is generated options
if(!empty($result)){
$this->set(compact($result));
$this->set('_serialize',array('result'));
print_r(json_encode($result));
$this->Session->setFlash("Searching Applicants Successful");
$this->set('result',$result);
}else
$this->Session->setFlash("No data found");
}else
$this->Session->setFlash("You didn't give any info to search for");
}
}
My View file(search_data.ctp) :
<h3>Search Result</h3>
<?php
echo $this->form->create();
echo $this->Form->input('field1',array('type'=>'text,'div'=>false));
echo $this->Form->input('field2',array('type'=>'text,'div'=>false));
echo $this->Form->input('field3',array('type'=>'text,'div'=>false));
echo $this->Form->input('field4',array('type'=>'text,'div'=>false));
echo $this->Form->submit('Search');
echo $this->Form->end();
<div id="searchResult">
<?php if(!empty($result)){?>
<table class="table table-striped table-bordered table-hover">
<thead>
<th>Field 1</th>
<th>Field 2</th>
<th>Field 3</th>
<th>Field 4</th>
</thead>
<tbody>
<?php foreach($result as $applicant){?>
<tr>
<td><?php echo $result['ModelName']['field1'];?></td>
<td><?php echo $result['ModelName']['field2'];?></td>
<td><?php echo $result['ModelName']['field3'];?></td>
<td><?php echo $result['ModelName']['field4'];?></td>
</tr>
<?php }?>
</tbody>
</table>
<?php
}else
echo "No data found";
?>
</div>
Here, what I want is, when I submit the form, the "result" div will immediately appear, with the result data, organized in the table. I want to use Ajax here, so that users will get the result immediately, it'll improve the performance and user experience.
I've seen some youtube videos, where they load another page with the result, and shows that page in a div (it is called "success" div most of the time :) ), using Ajax. I can do it. But, I just want to do everything in 1 page, I don't want to use 2 pages to do it.
I tried this for ajax request and update my "result" div(in my search_data.ctp file) :
$this->Js->get('.search-form')->event('submit',$this->Js->request(array('controller'=>'cntrlr_name','action'=>'searchData'),array('async'=>true,'update'=>'#searchResult')));
And when I run the page, this is the output :
[{"Applicant":{"id":"3","name":"Name 2","email":"ssaha.316#gmail.com","mobile":"9082730572","contact_phone":"3465360980","office_phone":"2437845693","correspondence_address":"Correspondence Address 2","permanent_address":"Permanent Address 2","preferred_work_areas":"Field 1, Field 2, Field 3","created":"2014-05-31 18:22:17","modified":"2014-05-31 18:22:17"},"ApplicantAcademicQualification":[{"id":"2","applicant_id":"3","level":"Bachelor(Pass)","degree_title":"B.A.","passing_year":"1999","institution":"Institution 2","result":"4.2","major":"Bengali Literature","created":"2014-05-31 18:22:17","modified":"2014-05-31 18:22:17"}],"ApplicantEmploymentHistory":[{"id":"2","applicant_id":"3","employer":"Employer 2","position_held":"Position 2","industry":"Industry 2","department":"Department 2","major_responsibilities":"Responsibility 2","job_location":"Local","key_achievement":"Achievement 2","served_from":"1999-08-15","served_till":"2010-02-12","created":"2014-05-31 18:22:17","modified":"2014-05-31 18:22:17"}],"ApplicantOther":[{"id":"2","applicant_id":"3","academic_activities":"Academic Activities 2","non_academic_activities":"Non Academic Activities 2","main_reason_for_applying":"Reason 2","worked_before":"0","last_position":"","work_location_constraint":"1","ready_to_join_on":"2008-08-14","expected_salary":"30k+","created":"2014-05-31 18:22:17","modified":"2014-05-31 18:22:17"}],"ApplicantProfessionalQualification":[{"id":"2","applicant_id":"3","name_of_certificate":"Certificate 2","institute":"Institute 2","from":"2002-10-17","to":"2007-10-12","location":"Local Ins.","created":"2014-05-31 18:22:17","modified":"2014-05-31 18:22:17"}],"ApplicantTraining":[{"id":"2","applicant_id":"3","title":"Title 2","institute":"Institute 2","training_year":"1995","location":"In Company","created":"2014-05-31 18:22:17","modified":"2014-05-31 18:22:17"}]},{"Applicant":{"id":"2","name":"Name 1","email":"user1#email.com","mobile":"715414918934","contact_phone":"2357295090","office_phone":"083656987398","correspondence_address":"Address 1_1","permanent_address":"Address 1_2","preferred_work_areas":"Field 1, Field 2, Field 3","created":"2014-05-18 16:48:08","modified":"2014-05-18 17:20:12"},"ApplicantAcademicQualification":[{"id":"1","applicant_id":"2","level":"Secondary","degree_title":"S.S.C","passing_year":"2009","institution":"Institute 1","result":"4","major":"Science","created":"2014-05-18 16:48:08","modified":"2014-05-18 17:20:12"}],"ApplicantEmploymentHistory":[{"id":"1","applicant_id":"2","employer":"Employer 1","position_held":"Position 1","industry":"Industry 1","department":"Department 1","major_responsibilities":"Responsibilities 1","job_location":"Local","key_achievement":"Achievements 1","served_from":"2005-03-12","served_till":"2007-11-26","created":"2014-05-18 16:48:08","modified":"2014-05-18 17:20:12"}],"ApplicantOther":[{"id":"1","applicant_id":"2","academic_activities":"Academic Activities 1","non_academic_activities":"Non Academic Activities 1","main_reason_for_applying":"Reason 1","worked_before":"1","last_position":"Last Position 1","work_location_constraint":"1","ready_to_join_on":"2008-07-10","expected_salary":"20k-25k","created":"2014-05-18 16:48:08","modified":"2014-05-18 17:20:12"}],"ApplicantProfessionalQualification":[{"id":"1","applicant_id":"2","name_of_certificate":"Certificate 1","institute":"Institute 1","from":"2011-10-11","to":"2012-09-11","location":"Local Ins.","created":"2014-05-18 16:48:08","modified":"2014-05-18 17:20:12"}],"ApplicantTraining":[{"id":"1","applicant_id":"2","title":"Title 1","institute":"Institute 1","training_year":"2013","location":"Local Ins.","created":"2014-05-18 16:48:08","modified":"2014-05-18 17:20:12"}]}]
Is it possible ? How can I do it ? Please help me.
Thanks.
update your function searchData:
public function searchData(){
//just empty for showing the form only
}
add ajax function:
public function ajax_search(){
$this->layout="ajax";
$result = array();
$field1 = $_POST["field1"];
$field2 = $_POST["field2"];
$field3 = $_POST["field3"];
$field4 = $_POST["field4"];
if( $field1 && $field2 && $field3 && $field4 ){ //change this depending on your queries
$data=$this->request->data;
// Generating options
.
.
.
$result=$this->ModelName->find('all',$options);// "$options" is generated option
}
$this->set("result", $result);
}
add view ajax_search.ctp:
<?php if($result):?>
<table class="table table-striped table-bordered table-hover">
<thead>
<th>Field 1</th>
<th>Field 2</th>
<th>Field 3</th>
<th>Field 4</th>
</thead>
<tbody>
<?php foreach($result as $applicant){?>
<tr>
<td><?php echo $result['ModelName']['field1'];?></td>
<td><?php echo $result['ModelName']['field2'];?></td>
<td><?php echo $result['ModelName']['field3'];?></td>
<td><?php echo $result['ModelName']['field4'];?></td>
</tr>
<?php }?>
</tbody>
</table>
<?php else:?>
No results.
<?php endif;?>
update you searchData.ctp:
<h3>Search Result</h3>
<?php
echo $this->Form->create("Search",array("default"=>false, "id"=>"SearchForm"));
echo $this->Form->input('field1',array('type'=>'text,'div'=>false));
echo $this->Form->input('field2',array('type'=>'text,'div'=>false));
echo $this->Form->input('field3',array('type'=>'text,'div'=>false));
echo $this->Form->input('field4',array('type'=>'text,'div'=>false));
echo $this->Form->submit('Search');
echo $this->Form->end();
<div class="result">
;?>
<script type="text/javascript">
$(document).on('submit','#SearchForm',function(){
$.ajax({
type: "POST",
data:{
field1:$("#SearchField1").val, // the ids of your input or you can modify these if you have assigned ids to the input
field2:$("#SearchField2").val,
field3:$("#SearchField3").val,
field4:$("#SearchField4").val
},
beforeSend: function(){
$("#result").html("loading...");
}
url: "<?php echo $this->base;?>/{insert your controller name here}/ajax_search/",
success:function(data) {
$("#result").html(data);
}
});
});
</script>
Here are the steps:
Your search method returns data as JSON.
Then on your page loop data in jquery template.
Here is an example of how to use jQuery templates, and here it's documentation
Here is another approach
UPDATE
simple return json results from your search method:
public function searchData(){
$this -> layout = 'ajax';
$this -> autoRender = false;
if($this->request->is('post')){
if(!empty($data)){
$data=$this->request->data;
// Generating options
...
$result = $this->ModelName->find('all',$options);// "$options" is generated options
$this -> set(compact($result));
$this -> set('_serialize',array('result'));
echo json_encode($result);
}
}
}
Use and loop JSON results data

Ajax loading image did not show before ajax content load; image and content load at the same div

I want to load an image loader first in <div id="ajax-content-container"> before a data content will be showed in the same div <div id="ajax-content-container"> using ajax. However, the image loader did not even show up, the content showed directly without loading the image loader first. If I place return false under beforeSend, it shows reverse and the load didn't stop.
beforeSend: function(){
$('#ajax-content-container').html('<img src="<?php echo base_url()?>/img/ajax-
loader.gif" width="200" height="200" style="margin-left:450px; margin-top:300px;" />');
return false;
}`
How to get this done? Here are my codes. Thanks for the help.
View:
<?php if (!isset($ajax_req)): ?>
<div class="row">
<div class="span3"> <?php echo
form_dropdown('courses',$dropdown,$selected_value,'id="select_id"');?> </div>
<div class="span3"> <?php echo
form_dropdown('schedule',$dropdown_sched,$date_value,'id="date_option"');?> </div>
<div class="span2"> <?php echo
form_dropdown('status',$dropdown_status,$status_value,'id="status_id"');?></div>
</div>
<?php endif; ?>
<div id="ajax-content-container">
<table class="table table-bordered table-condensed table-striped table-hover">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email Address</th>
<th>Phone Number</th>
<th>Status</th>
</tr>
<?php foreach ($student_list as $key=>$value): ?>
<tr>
<td><?php echo $value->first_name; ?></td>
<td><?php echo $value->last_name; ?></td>
<td><?php echo $value->email; ?></td>
<td><?php echo $value->phone_no; ?></td>
<td><?php echo $value->status; ?></td>
</tr>
<?php endforeach; ?>
</table>
</div>
javascript:
<script type="text/javascript">
$(document).ready(function () {
ajax_courses();
ajax_sched();
ajax_status();
});
function ajax_courses() {
$('#select_id').change(function () {
var course_id = $("#select_id").val();
var postData = {'course_id':course_id};
var timeout;
$.ajax({
url: "<?php echo base_url(); ?>/ajax_student_controller/get_ajax_course_student/",
async: false,
type: "POST",
data: postData,
dataType: "html",
beforeSend: function(){
$('#ajax-content-container').html('<img src="<?php echo base_url()?>/img/ajax-
loader.gif" width="200" height="200" style="margin-left:450px; margin-top:300px;"
/>');
},
success: function(data) {
$('#ajax-content-container').html(data);
},
})
});
}
</script>
How about this , you don't need to wrap a change function inside ajax_courses() just put it in ready and when onchange function is called the loader image will be added in the ajax-content-container and when ajax request is completed the ajax-content-container div will have the desired content in a container .
Note Make sure Your loading image path is correct otherwise image will not be shown
<script type="text/javascript">
$(document).ready(function () {
//ajax_courses();
ajax_sched();
ajax_status();
$('#select_id').change(function () {
$('#ajax-content-container').html('<img src="<?php echo base_url()?>/img/ajax-loader.gif" width="200" height="200" style="margin-left:450px; margin-top:300px;" />');
var course_id = $("#select_id").val();
var postData = {'course_id':course_id};
var timeout;
$.ajax({
url: "<?php echo base_url(); ?>/ajax_student_controller/get_ajax_course_student/",
async: false,
type: "POST",
data: postData,
dataType: "html",
success: function(data) {
setTimeout(function(){
$('#ajax-content-container').html(data);
},3000); // 3 seconds delay
},
});//end ajax
}); // end onchange
});//end ready
</script>
Other way i will recommend that place the loading image in the ajax-content-container div with display:none and when onchange happened use $(".loading_image").show() when ajax completed then if loading_image exists use $(".loading_image").hide()
Hope it helps you

Joomla plugin database mistakes? What is wrong here?

i've just started learning Jplugin development, so here i made a little voting script. Everything here works fine, but i want conf.php file to be made in joomla framework style. As you see here, 1 and 2 files works perfectly together. I want to use third example instead of second, in which i use simple php code. The last example i tried to do is using joomla framework, but it doesnt work. I have no idea what's wrong with that code. Anyone see could tell where I made a mistake or maybe far away from doing it right ?
<?php
defined( '_JEXEC' ) or die;
?>
<?php
class plgSystemRatingx extends JPlugin
{
public function onContentBeforeDisplay()
{
?>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".like").click(function()
{
var id=$(this).attr("id");
var name=$(this).attr("name");
var dataString = 'id='+ id + '&name='+ name;
$("#votebox").slideDown("slow");
$("#flash").fadeIn("slow");
$.ajax
({
type: "POST",
url: "conf.php",
data: dataString,
cache: false,
success: function(html)
{
$("#flash").fadeOut("slow");
$("#content").html(html);
}
});
});
$(".close").click(function()
{
$("#votebox").slideUp("slow");
});
});
</script>
<body>
<div style="margin:50px">
Like -- Dislike
<div id="votebox">
<span id='close'>X</span>
<div style="height:13px">
<div id="flash">Loading........</div>
</div>
<div id="content">
</div>
</div>
</div>
<?php
return true;
}
}
this piece of code works perfectly
<?php
$mysql_hostname = "localhost";
$mysql_user = "px";
$mysql_password = "px";
$mysql_database = "jum";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)
or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");
if($_POST['id'])
{
$id=mysql_real_escape_string($_POST['id']);
$name=mysql_real_escape_string($_POST['name']);
mysql_query("update messages set $name=$name+1 where id='$id'");
$result=mysql_query("select up,down from messages where id='$id'");
$row=mysql_fetch_array($result);
$up_value=$row['up'];
$down_value=$row['down'];
$total=$up_value+$down_value;
$up_per=($up_value*100)/$total;
$down_per=($down_value*100)/$total;
?>
<div style="margin-bottom:10px">
<b>Ratings for this blog</b> ( <?php echo $total; ?> total)
</div>
<table width="700px">
<tr>
<td width="30px"></td>
<td width="60px"><?php echo $up_value; ?></td>
<td width="600px"><div id="greebar" style="width:<?php echo $up_per; ?>%"></div></td>
</tr>
<tr>
<td width="30px"></td>
<td width="60px"><?php echo $down_value; ?></td>
<td width="600px"><div id="redbar" style="width:<?php echo $down_per; ?>%"></div></td>
</tr>
</table>
<?php
}
?>
and this made in joomla style doesnt work at all
<?php
defined( '_JEXEC' ) or die;
?>
<?php
if(JRequest::getVar('id'))
{
$id = JRequest::getInt('id');
$name = JRequest::getInt('name');
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query2 = $db->getQuery(true);
$queryup = $db->getQuery(true);
$querydown = $db->getQuery(true);
$query->update('messages');
$query->set("message = 1");
$query->where("id = $id");
$query2->select('up,down');
$query2->from('messages');
$query2->where("id = $id");
$queryup->select('up');
$queryup->from('messages');
$queryup->where("id = $id");
$querydown->select('down');
$querydown->from('messages');
$querydown->where("id = $id");
$db->setQuery( $query );
$db->query();
$db->setQuery( $query2 );
$db->query();
$db->setQuery( $queryup );
$data0 = $db->query();
$db->setQuery( $querydown );
$data1 = $db->query();
$up_value= $db->insertid($data0);;
$down_value = $db->insertid($data1);
$total=$up_value+$down_value;
$up_per=($up_value*100)/$total;
$down_per=($down_value*100)/$total;
?>
<table width="700px">
<tr>
<td width="30px"></td>
<td width="60px"><?php echo $up_value; ?></td>
<td width="600px"><div id="greebar" style="width:<?php echo $up_per; ?>%"></div></td>
</tr>
<tr>
<td width="30px"></td>
<td width="60px"><?php echo $down_value; ?></td>
<td width="600px"><div id="redbar" style="width:<?php echo $down_per; ?>%"></div></td>
</tr>
</table>
<?php
}
Try this
$query->where('id = ' . $db->qn($id));
etc

Resources