I'm now self-practicing Codeigniter with the help of internet. I'm able to create almost all operations now , but today I'm tried to fetch data using ajax call. Nothing is retrieving from database, but while debugging with Chrome's debugger, no error is showing. I'm hitting my head for six hours for this problem.I tried everything and reached finally here.
This is my Model
public function member_id($postData)
{
$response = array();
if($postData['member_id'] ){
$this->db->select('*');
$this->db->where('member_id', $postData['member_id']);
$q = $this->db->get('tbl_test');
$response = $q->result_array();
}
return $response;
}
Controller
function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->database();
$this->_init();
}
private function _init()
{
$this->output->set_template('default');
$this->load->css('assets/themes/default/css/my.css');
$this->load->css('assets/themes/default/css/bootstrap.css');
$this->load->css('assets/themes/default/css/bootstrap-theme.css');
}
public function index()
{
$data['title'] = "My Real Title";
$this->load->view('pages/home',$data);
}
public function feeDetails()
{
$postData = $this->input->post();
$this->load->model('Model');
$data = $this->Model->member_id($postData);
echo json_encode($data);
}
View
<input class="form-control in2" id="txtmemid" placeholder="Member id " name="txtmemid" value="" style="text-transform:uppercase" type="text">
<button type="submit" id="btnmemfeeview" class="btn btn-default ho showser fl ">Search</button>
Bill No: <span id='bno'></span><br/>
Bill date: <span id='bdate'></span><br/>
Member id: <span id='mid'></span><br/>
and finally this is my ajax
<script type='text/javascript'>
$(document).ready(function(){
$("#btnmemfeeview").click(function(){
var member_id = $('#txtmemid').val();
$.ajax({
url:'<?=base_url()?>index.php/Pages/feeDetails',
method: 'post',
data: {member_id: member_id},
dataType: 'json',
success: function(response){
var len = response.length;
if(len > 0){
// Read values
var bno = response.BILL_NO;
var bdate = response.BILL_DATE;
var mid = response.MEMBER_ID ;
$('#bno').text(bno);
$('#bdate').text(bdate);
$('#mid').text(mid);
}else{
$('#bno').text('');
$('#bdate').text('');
$('#mid').text('');
}
}
});
});
});
</script>
Related
I'm not able to filter table data using Ajax. When I select BANK CREDIT from drop down it should fetch employee details with modeofpay(table column) as "BANK CREDIT" and when I select NEFT it should display employee details with modeofpay(table column) as "NEFT". As of Now nothing happens when i select drop down.
Controller:
public function filter($key = '')
{
$this->load->helper('url');
if ( $key == 'BANK CREDIT' ) {
$this->load->model('JcMeetingExpense_model');
$data = $this->JcMeetingExpense_model->getCredit($key);
}
else
{
$this->load->model('JcMeetingExpense_model');
$data = $this->JcMeetingExpense_model->getNeft($key);
}
echo json_encode($data);
}
Model:
public function getCredit($key)
{
$sql = "SELECT * FROM employee WHERE modeofpay = '$key'";
$data = $this->db->query($sql);
return $data->result_array();
}
public function getNeft($key)
{
$sql = "SELECT * FROM employee WHERE modeofpay = '$key'";
$data = $this->db->query($sql);
return $data->result_array();
}
View:
<script type="text/javascript">
var paymode = $("#mode").change(function(){
$.ajax({
type:"POST",
url:url:'<?php echo base_url("JcMeetingExpense/filter/key/") ?
>'+paymode,
data:"key="+paymode,
dataType:'json',
success:function(data){
$("#viewjcexpense").html(data);
},
error:function(XMLHttpRequest){
alert(XMLHttpRequest.responseText);
}
});
});
</script>
<select name="mode" id="mode" >
<option value="BANK CREDIT">CREDIT</option>
<option value="NEFT">NEFT</option>
</select>
is your onchange event working ?
let's check with
$("#mode").change(function(){
alert(1);
});
if when u selected an option would be show the alert that's mean ur event working ,
now if that's working fine let's try to playing with ajax and do little recode, here i used post method
[ VIEW ]
$("#mode").change(function(){
$.ajax({
type : 'POST',
url : '<?=base_url(); ?>JcMeetingExpense/filter/',
data : { key : $("#mode").val() },
success : function(data){
console.log(data);//let's check on console what's response is
}
});
})
[CONTROLLER]
public function filter()
{
$this->load->helper('url');
$this->load->model('JcMeetingExpense_model');
$dataKey = $this->JcMeetingExpense_model->get_data_by_key();
echo json_encode($datadataKey);
}
[MODEL]
public function get_data_by_key()
{
//do post here let's say
$key = $this->input->post("key");
// i looked your query is vulnerable to SQL Injection
/* $sql = "SELECT * FROM employee WHERE modeofpay = '$key'";
$data = $this->db->query($sql);
return $data->result_array(); */
//so let's use query builder
$this->db->select("*");
$this->db->from("employee");
$this->db->where("modeofpay",$key);
$q = $this->db->get();
return $q->result_array();
}
now check response in console
<script type="text/javascript">
$("body").on('change','#mode',function(){
$.ajax({
type:"POST",
url:url:'<?php echo base_url("JcMeetingExpense/filter/key/") ?
>'+paymode,
data:"key="+paymode,
dataType:'json',
success:function(data){
$("#viewjcexpense").html(data);
},
error:function(XMLHttpRequest){
alert(XMLHttpRequest.responseText);
}
});
});
</script>
try this script instead of your previous script
i have changed $("#mode").change(function(){}); with $("body").on('change','#mode',function(){});
Ajax:
<script type="text/javascript">
$(document).ready(function () {
$('#finalSubmit').click(function() {
var form1 = $('#priceform').serialize();
var form2 = $('#formdescription').serialize();
var form3 = $('#additionaldescription').serialize();
//var form4 = new FormData($("#imagesform").get(0));
//alert(form4);
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN':
$('meta[name="_token"]').attr('content') }
});
$.ajax({
url :"{{url('/dbvalue')}}",
type: 'POST',
data: {form1: form1, form2: form2,form3: form3},
dataType:'json',
success:function(data){
alert(data);
}
});
});
});
</script>
This is my ajax code.Here I'm passing the values of four forms
Controller:
public function finalSubmit(Request $request)
{
var_dump($_POST);
$var1 = $this->addPriceDetails1($request->form1);
$var2 = $this->addProductDetails1($request->form2);
$var3 = $this->addAdditionalInformation1($request->form3);
//$var4 = $this->addImages($imagesform);//you dont't have
$imagesform
return response()->json(["response"=>"success"]);
}
Eg. for function:
public function addPriceDetails1($request)
{
$priceInfo = new priceInfo ;
$priceInfo->id=$this->getpriceDetailsId();
$priceInfo->SKUID=$request->input('skuid');
echo($priceInfo->id);
//return $request->all();
}
Also here when I'm trying to echo the values of $priceInfo->Id it echoes '0'.I don't know why
With this I'm getting FatalErrorException..call to member function input() on string
var_dump($_POST) gives me an array of forms values.
UPdate:
public function getpriceDetailsId()
{
$id = mt_rand(1000000, 9999999);
$id="PD".$id;
$count=priceInfo::select('id')->where('id',$id)->count();
if($count==0)
{
return $id;
}
else
{
$this->getpriceDetailsId();
}
}
here is my function for getpriceDetailsId().
You get that error because your input query when you access as object when it is string, you can convert your query string to an array to access like so.
public function addPriceDetails1($request)
{
parse_str($request, $input);
$priceInfo = new priceInfo ;
$priceInfo->id = $this->getpriceDetailsId();
$priceInfo->SKUID = $input['skuid'];
echo($priceInfo->id);
}
Hope this help
I am using code igniter, google charts with php and MySQL to display charts. It works using fixed query. I am trying to add a dropdown to display the chart based on the option (sql column "status") selected
Here is what I have so far. How can I modify this to accept dropdown values?
model.php
public function get_chart_data()
{
$query = $this->db->get($this->db_mgmt);
$this->db->select('rating, COUNT(rating) AS Count');
$this->db->from('db_mgmt');
$this->db->where('status =', $status);
$this->db->group_by('rating');
$query = $this->db->get();
$results['chart'] = $query->result();
}
controller.php
$this->load->model('model', 'chart');
public function index() {
$results = $this->chart->get_chart_data();
$data['chart'] = $results['chart'];
$this->load->view('index.php', $data);
}
view.php
<?php
foreach ($chart as $object) {
$open_all[] = "['".$object->rating."', ".$object->Count."]";
}
?>
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart_open);
function drawChart_open() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Rating');
data.addColumn('number', 'Count');
data.addRows([
<?php echo implode(",", $open_all);?>
]);
var options = {
pieSliceText: 'value-and-percentage',
};
var chart = new google.visualization.PieChart(document.getElementById('open_div'));
chart.draw(data, options);
}
<div id="open_div" class="chart"></div>
Thanks in advance!
UPDATE:
I have tried the below using ajax but it doesn't seem to work. I am definitely sure I am doing something wrong here but not sure where. Using Inspect in chrome also doesn't give any errors.
model.php
public function fetch_result($status)
{
$query = $this->db->get($this->db_mgmt);
$this->db->select('rating, COUNT(status) AS Status_Count');
$this->db->from('db__mgmt');
$this->db->where('status =', $status);
$this->db->group_by('rating');
$query = $this->db->get();
return $query;
}
controller.php
$this->load->model('model', 'chart');
public function mychart() {
if(!empty($_POST["val"])) {
$val=$_POST["val"];
$result_new=$this->chart->fetch_result($val);
$array = array();
$cols = array();
$rows = array();
$cols[] = array("id"=>"","label"=>" Rating","pattern"=>"","type"=>"string");
$cols[] = array("id"=>"","label"=>"Count","pattern"=>"","type"=>"number");
foreach ($result_new as $object) {
$rows[] = array("c"=>array(array("v"=>$object->risk_rating,"f"=>null),array("v"=>(int)$object->Status_Count,"f"=>null)));
}
$array = array("cols"=>$cols,"rows"=>$rows);
echo json_encode($array);
}
}
view.php
function drawChart_open_all(num) {
var PieChartData = $.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "dashboard/chart/mychart",
data:'val='+num,
dataType:"json"
}).responseText;
alert(PieChartData);
// Create the data table.
var data = new google.visualization.DataTable(PieChartData);
var options = {
pieSliceText: 'value-and-percentage',
};
var chart = new google.visualization.PieChart(document.getElementById('open_new'));
chart.draw(data, options);
}
<div><span> <b>Pie Chart<br /><br /></span></div>
<form>
<select name="status" onchange="drawChart_open_all(this.value)">
<option value="WIP">WIP</option>
<option value="Close">Close</option>
</select>
</form>
<div id="open_new" class="chart"></div>
Thanks in advance!!
I think the easiest thing would be to send a GET request with the <option> value
First, go back to your first version.
Next, send the value in your onchange event
function drawChart_open_all(num) {
location = "<?php echo base_url(); ?>" + "dashboard/chart/mychart?option=" + num;
}
Then in Model --
get_chart_data()
you should be able to access the value with --
$_GET['option']
use that to modify your query
here's an old answer with similar concept -- difference is it uses POST vs. GET
and a <form> with a <input type="submit"> button to send the request
How to pass JavaScript variables to PHP?
I managed to figure out what the problem was and used ajax in the end. #WhiteHat solution led to also in the right direction. Thanks for that!
model.php
public function fetch_result($status)
{
$query = $this->db->get($this->db_mgmt);
$this->db->select('rating, COUNT(status) AS status_count');
$this->db->from('db_mgmt');
$this->db->where('status =', $status);
$this->db->group_by('rating');
$query = $this->db->get();
$results_new = $query->result(); // <-- Forgot to add this!
return $results_new;
}
controller.php
$this->load->model('model', 'chart');
public function mychart() {
if(!empty($_POST['option'])) {
$val = $_POST['option'];
$result_new=$this->chart->fetch_result($val);
$array = array();
$cols = array();
$rows = array();
$cols[] = array("id"=>"","label"=>" Rating","pattern"=>"","type"=>"string");
$cols[] = array("id"=>"","label"=>"Count","pattern"=>"","type"=>"number");
foreach ($result_new as $object) {
$rows[] = array("c"=>array(array("v"=>(string)$object->rating),array("v"=>(int)$object->status_count)));
}
$array = array("cols"=>$cols,"rows"=>$rows);
echo json_encode($array);
}
}
view.php
function drawChart_open_all(status) {
var PieChartData = $.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>" + "dashboard/chart/mychart",
data: { 'option':status }, // <-- kept as option instead of val
dataType:"json",
global: false, // <-- Added
async:false, // <-- Added
success: function(data){ // <-- Added
return data; // <-- Added
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
}).responseText;
// Create the data table.
var data = new google.visualization.DataTable(PieChartData);
var options = { pieSliceText: 'value-and-percentage', };
var chart = new google.visualization.PieChart(document.getElementById('open_new'));
chart.draw(data, options);
}
<div><span> <b>Pie Chart<br /><br /></span></div>
<form>
<select name="status" onchange="drawChart_open_all(this.value)">
<option value="WIP">WIP</option>
<option value="Close">Close</option>
</select>
</form>
<div id="open_new" class="chart"></div>
Hello guys im trying to create a simple voting for comments like and dislike but i want to do that with jquery Ajax so i don't want to refresh the page when someone like it.
And this is my jquery code
$(document).ready(function(){
$(".vote-btn").click(function() {
var voteId = this.id;
var upOrDown = voteId.split('_');
// alert(upOrDown); = provides --> id,name
// var all = 'voteId:'+upOrDown[0]+ ',upOrDown:' +upOrDown[1];
// alert(all);
$.ajax({
type: "POST",
url: "http://localhost/Dropbox/cipr/index.php/demo",
cache: false,
dataType:'json',
data:{'voteId='+upOrDown[0] + '&upOrDown=' +upOrDown[1],
success: function(response){
try{
if(response=='true'){
var newValue = parseInt($("#"+voteId+'_result').text()) + 1;
$("#"+voteId+'_result').html(newValue);
}else{
alert('Sorry Unable to update..');
}
}catch(e) {
alert('Exception while request..');
}
},
error: function(){
alert('Error while request..');
}
});
});
});
this is my Controller code Demo.php
<?php
class Demo extends CI_Controller {
function Demo(){
parent::Controller();
$this->load->model('sygjerimet');
}
public function index(){
$voteId= $this->input->post('voteId');
$upOrDown= $this->input->post('upOrDown');
$status ="false";
$updateRecords = 0;
if($upOrDown=='voteup' || true){
$updateRecords = $this->sygjerimet->updateUpVote($voteId);
}else{
$updateRecords = $this->sygjerimet->updateDownVote($voteId);
}
if($updateRecords>0){
$status = "true";
}
echo $status;
}
And this is my model code sygjerimet.php
<?php
Class Sygjerimet extends CI_Model
{
function shtoSygjerimin()
{
$permbajtja = $this->input->post('idea');
$data = array(
'permbajtja' => $permbajtja
);
$this->db->insert('pr_sygjerimet', $data);
}
function updateDownVote($voteId){
$sql = "UPDATE pr_sygjerimet set vote_down = vote_down+1 WHERE ID =?";
$this->db->query($sql, array($voteId));
return $this->db->affected_rows();
}
function updateUpVote($voteId){
$sql = "UPDATE pr_sygjerimet set vote_up = vote_up+1 WHERE ID =?";
$this->db->query($sql, array($voteId));
return $this->db->affected_rows();
}
}
And this is my view Code
<?php
$query = $this->db->query('SELECT * FROM pr_sygjerimet');
foreach ($query->result() as $row)
{
echo "<div class='sygjerimi'>";
echo htmlspecialchars($row->permbajtja);
if(!$log_in):
echo '<br>';
echo ' <button id="'.$row->ID.'_votedown" class="vote-btn"><i class="fa fa-thumbs-down">'.htmlentities($row->vote_down).'</i></button> ';
echo ' <button id="'.$row->ID.'_voteup" class="vote-btn"><i class="fa fa-thumbs-up">'.htmlentities($row->vote_up).'</i></button> ';
endif;
echo "</div>";
}
?>
That's it guys when i cilck vote it executes this code
alert('Error while request..');
If anyone can help that would be Great :) Thanks
Most likely this is the CI CSRF protection; if you use POST, CI automatically checks the CSRF hidden field and since you are building the ajax post yourself, it's not sending the hidden field so it bags on you.
Check the several $config['csrf_*'] lines in your config/config.php file. You can disable (but I don't recommend this). You can also serialize the form in jQuery and send that, and it should work for you, and keep you a bit more protected from CSRF attacks.
Just to rule this in or out, you can disable the 'csrf_protection' and if it works then, you can enable it again and then change your javascript to serialize the form and use that as your data with your ajax post.
try this
$.ajax({
//pull the toke csrf like this
data:{'<?php echo $this->security->get_csrf_token_name();?>':'<?php echo $this->security->get_csrf_hash();?>'},
});
I want to validate a form without refreshing the page using the .post() jQuery method.
I use codeigniter for validation. Could you please tell me how to make it right? I find it pretty confusing ...
Here is the jQuery code:
$(document).ready(function(){
$(".form_errors").hide();
$("#send").on("click",function(){ //the submit button has the id="send"
$(".form_errors").hide(); //these are <p> for each input to show the error
var user=$("input.box");
var data={};
var names=$("input.box").attr("name");
for(i=0;i<user.length;i++){
name=names[i];
value=user[i].val();
data.name=value;
}
$.post('ksite/account',
data,
function(result){
$("div.answer").html(result);
for(i=0;i<user.length;i++){
error_message=<?php echo form_error("?>names[i]<?php ");?>;
$("p#error_"+names[i]+".form_errors").html(error_message).show();
}
}
return false;});
});
form_error is a CodeIgniter function. (I suppose someone who used ci is familiar with).
The form:
<p id="error_user" class="form_errors"></p>
<input type="text" class="box" name="user">
<p id="error_password" class="form_errors"></p>
<input type="password" class="box" name="password">
<input type="submit" id="send">
Is the form tag neccessary ? And if yes,do i have to mention action and method ?
Do I have to specify the type of the response?
And in ksite/account I do:
/* ...... */
if (!this->form_validation->run(''account")) {
echo "The account couldn't be made";
} else {
echo "The account was successfully created ";
}
P.S.Although you may not be familiar with codeigniter, I would appreciate if someone could tell me if the code is correct and what improvements could be made.
Here is what I did.
You have to Ajax for getting data without refreshing the page.
HTML Page
$form = $(form);
var url = $form.attr('action');
dataString = $form.serialize();
$.ajax({
type: "POST",
url: url,
data: dataString,
dataType: "json",
success: function(data) {
$(data).each(function(j,details){
var status = details.status;
var message = details.message;
$('#message_ajax_register').show();
$('#message_ajax_register').html('<div class="alert alert-success">'+message+'</div>');
});
}
});//end of $.ajax**
I am first setting up the rules in my controller method and then validating it.
Controller
public function update_fest()
{
if($this->input->post())
{
$this->form_validation->set_rules('txtgpluswebsite', 'Google Plus Page URL', 'trim|xss_clean|prep_url');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
if($this->form_validation->run() == false){
$message = validation_errors();
$data = array('message' => $message,'status'=>0);
}
else{
$message = $this->add_fest_database();
$data = $message;
}
}
else{
$message = "Fest details are required";
$data = array('message' => $message,'status'=>0);
}
$this->output->set_content_type('application/json');
$json = $this->output->set_output(json_encode($data));
return $json;
}
If validation run is not false, then go to add_fest_database(other function). In that function,
function add_fest_database()
{
$youtubeWebsite = $this->input->post('txtyoutubewebsite');
$gplusWebsite = $this->input->post('txtgpluswebsite');
$this->load->model('model_fest');
$data = array("fest_youtube"=>$youtubeWebsite,"fest_gplus"=>$gplusWebsite);
return data;
}