Send value from controller with ajax Codeigniter - javascript

i have javascript like this
$(document).ready(function(){
$("input[type='checkbox']").change(function(){
var menu_id = this.value;
if(this.checked) var statusvalue = "On";
else var statusvalue = "Off";
$.ajax({
type : "POST",
url : "admin/menu/editstatus",
data : "id=" + menu_id + "&value=" + statusvalue,
success : function(data){
$("#testing").html(data);
}
});
});
});
and my controller named menu and have function editstatus()
public function editstatus()
{
$data = "asd";
echo $data;
}
but textbox with id testing not writen anything

change ajax function like below
$(document).ready(function(){
$("input[type='checkbox']").change(function(){
var menu_id = this.value;
if(this.checked)
{
var statusvalue = "On";
}
else
{
var statusvalue = "Off";
}
$.ajax({
type : "POST",
url : "<?php echo base_url()?>admin/menu/editstatus",
data :{
id:menu_id,
value:statusvalue
}
success : function(data){
$("#testing").val(data);
}
});
});
});

I think your url did not found.Try using base url
<?php echo base_url()?>admin/menu/editstatus

You need to use .val() instead of .html()
Corrected code:
$("#testing").val(data);
http://api.jquery.com/val/
https://api.jquery.com/html/

public function editstatus()
{
$data = "asd";
echo json_encode($data);
}
if $data is an array form e.g $data=array('name'=>'abd','id'=>'12') then ,
in Java script access like ,data.name or data.id

Related

Call Controller function from jQuery

I'm working on some codes. Here's my code
jQuery
duration = 30;
var countdown = setInterval(timer,1000);
var url = window.location.origin + '/pro/index.php/Test';
function timer(){
duration = duration - 1;
if(duration<=0){
clearInterval(countdown);
window.location(url+'/next');
}
}
I want to redirect and run function in Test/next. In next() method, it will rule where the link should go. url helper also has been added automatically in Loader
Controller
public $num;
public $val;
public function index(){
// get the value from GET method
$this->num = $this->input->get('num');
$this->val = $this->input->get('val');
}
public function next(){
$x = $this->num;
$x = $x + 1;
if($x < 4){
redirect(site_url('index.php/Test?x='.$x/.'&num='.$this->num));
}
else{
// it will redirect to another page
// redirect(site_url('index.php/Home'));
echo 'x = '.$x.', num = '.$this->num;
}
(The codes above have been simplified).
The method has been run, but the url was localhost/pro/index.php/Test/next and echo-ing :
x = , num =
It seems like the global property doesn't work for the function called from JS/jQuery. Any explanation or solution for this?
You need ajax calling.
In your View file
<button class="call_ajax" name="submit">Call Ajax</button>
<script type="text/javascript">
$('.call_ajax').click(function(){
var value1 = 'some data';
var value2 = 'some data';
$.ajax({
url: '<?php echo site_url('your_controller/your_function'); ?>',
type: 'POST',
data: {
key1: value1,
key2: value2
},
dataType: 'json',
success: function(url) {
window.location.href = url;
}
});
});</script>
in your Controller
your_function(){
$data1 = $this->input->post('key1');
$data2 = $this->input->post('key2');
// do Data Processing
// For return some data ;
echo "https://some-webiste-url/";
// FOR Array
echo json_encode($any_data_array);
}
NOTE : controller Function called from ajax will not do redirection . If you want to direct to some other url , you have to do that in the Javascript Section Using

CodeIgniter - getting data from database automatically using setInterval

In codeigniter, I want to display the change in the database automatically without reloading the page so i use ajax to run a controller function in my view. I'm using setInterval to run the function over and over again until the controller function listen_auth returns 1 and the view displays 1.
VIEW:
<h4 class="qr-title" id="status"></h4>
<script>
var username = <?php echo(json_encode($username)); ?>;
function checkAuthStatus() {
setInterval(getStatus, 1000);
}
function getStatus() {
var isAuth = <?php echo(json_encode($isAuth)); ?>;
$.ajax({
url: '<?php echo base_url('auth/listen_auth'); ?>',
type: 'post',
data: {username:username},
success: function(data){
console.log(data);
}
});
document.getElementById("status").innerHTML = isAuth;
}
</script>
here's the listen_auth() function in my CONTROLLER:
public function listen_auth(){
$username = $this->input->post('username');
$isApproved = $this->adminmodel->get_auth($username);
if($isApproved == 1){
return 1;
} else{
return 0;
}
}
The problem is that isAuth variable will only change once the page has been reloaded... Am I doing something wrong? Or is there any better way to do this?
The function from server 'listen_auth()' should print text not return.
public function listen_auth(){
$username = $this->input->post('username');
$isApproved = $this->adminmodel->get_auth($username);
if($isApproved == 1){
echo 1;
} else{
echo 0;
}
}
And then get the answer from server in AJAX request:
<script>
var username = <?php echo(json_encode($username)); ?>;
function checkAuthStatus() {
setInterval(getStatus, 1000);
}
function getStatus() {
var isAuth = <?php echo(json_encode($isAuth)); ?>;
$.ajax({
url: '<?php echo base_url('auth/listen_auth'); ?>',
type: 'post',
data: {username:username},
success: function(data){
document.getElementById("status").innerHTML = data;
}
});
}
</script>
You need to declare $isAuth and assign its value in ajax request, because php variable will not change its value without server request.

Numberbox jeasyui not showing value from variable

I have set value to a variable, but when I want to write down the value into numberbox, nothing is happen. I am working with datagrid jQuery Easyui here is my code
function update(){
var pesan='';
var dg =$(dgUpholdstery);
var id_cotation = '<?php echo $id_cotation ?>';
$.map(dg.datagrid('getChecked'), function(row){
var index = dg.datagrid('getRowIndex', row);
var harga=0;
var mat_waste='0';
var kode='';
harga = row.brg_harga;
mat_waste = row.mat_waste;
kode = row.material;
$.ajax({
type : 'POST',
url : "<?php echo site_url(); ?>/cotation/harga_cotation",
data : "kode="+kode+"&type=upholstery",
dataType : 'json',
cache : false,
success : function(data){
var $response=$(data);
if (harga!=$response[0]['harga']){
harga = $response[0]['harga'];
}
if (mat_waste!=$response[0]['mat_waste']){
mat_waste = $response[0]['mat_waste'];
}
}
});
dg.datagrid('beginEdit',index);
var ed_mat_waste = dg.datagrid('getEditor', {index:index, field:'mat_waste'});
var ed_brg_harga = dg.datagrid('getEditor', {index:index, field:'brg_harga'});
// this is part is not working
$(ed_mat_waste.target).numberbox('setValue',mat_waste);
//if I using the code bellow that I comment, it's work fine
//$(ed_mat_waste.target).numberbox('setValue','35');
cotation_uphold(index);
dg.datagrid('endEdit',index);
});
}
when I test to alert the variable, it's show the value
if I write direct value, it's working but if I put the variable, it's do nothing
I solved it.
here is the code
function update(){
var pesan='';
var dg =$(dgUpholdstery);
var id_cotation = '<?php echo $id_cotation ?>';
$.map(dg.datagrid('getChecked'), function(row){
var index = dg.datagrid('getRowIndex', row);
var harga=0;
var mat_waste=0;
var kode='';
harga = row.brg_harga;
mat_waste = row.mat_waste;
kode = row.material;
$.ajax({
type : 'POST',
url : "<?php echo site_url(); ?>/cotation/harga_cotation",
data : "kode="+kode+"&type=upholstery",
dataType : 'json',
cache : false,
success : function(data){
var $response=$(data);
if (harga!=$response[0]['harga'] && mat_waste!=$response[0]['mat_waste']){
dg.datagrid('beginEdit',index);
var ed_mat_waste = dg.datagrid('getEditor', {index:index, field:'mat_waste'});
var ed_brg_harga = dg.datagrid('getEditor', {index:index, field:'brg_harga'});
$(ed_brg_harga.target).numberbox('setValue',$response[0]['harga']);
$(ed_mat_waste.target).numberbox('setValue',$response[0]['mat_waste']);
cotation_uphold(index);
dg.datagrid('endEdit',index);
}
}
});
});
}

How to delete a record from database through AJAX using php and also when link is clicked

How to delete a record from database through AJAX using php and also when link is clicked it returns to same page and new list is updated when a link is clicked and id passes through this link ? I am new to AJAX and php
<a class="delete_data" id="<?php echo $row['id']; ?>">Delete</a>
ajax
$(document).ready(function(){
$(".delete_data").click(function(){
var del_id = $(this).attr('id');
$.ajax({
type:'POST',
url:'delete.php',
data:'delete_id='+del_id,
success:function(data) {
if(data) { // Sucess
} else { // Error }
}
});
});
});
delete.php
$id = $_POST['delete_id'];
$query = "delete from TABLE NAME where ID = $id";
#TOORPIZZZ You can add this to remove the row from the display without refreshing
$(document).ready(function(){
$(".delete_data").click(function(){
var del_id = $(this).attr('id');
var parent = $(this).parent();
$.ajax({
type:'POST',
url:'delete.php',
data:'delete_id='+del_id,
success:function(data) {
if(data) { parent.slideUp(300,function() {
parent.remove();
} else { // Error }
}
});
});
});
Make sure you don't have } in a comment by //Error. It took a while until I discovered this.
$(document).ready(function(){
$(".delete_data").click(function(){
var del_id = $(this).attr('id');
var parent = $(this).parent();
$.ajax({
type:'POST',
url:'delete.php',
data:'delete_id='+del_id,
success:function(data) {
if(data) { parent.slideUp(300,function() {
parent.remove();
} else { // Error } <----------------
}
});
});
});

how to use javascript this keyword with change function

I'm having a trouble using change function. I have a 2 different dropdowns attached to each other. When the first one is changes, the second one changes too. I did it using jquery ajax. But when i use ID's jquery can only work one time. So i did a research about javascript's this,parent and children keyword but i can't find the suitable way.
so my javascript is like below :
<script>
$(document).ready(function() {
// alert('js working');
$(".catSelectedClass").change(function() {
// alert('i'm inside the function dude');
function ustCat() {
alert(this);
var mainCatID = $(this).val();
alert('mainCatID captured');
var id = $(this).parent().$(".catIDClass").val();
// alert(id);
// alert(mainCatID);
$.ajax({
type: "POST",
url: "panel/catGroupPost.php",
data: {id: id, mainCatID: mainCatID}
}).done(function(data) {
var responseData = data;
alert(responseData);
$('#subCat').html($(data));
});
}
ustCat();
});
$(".subCatClass").change(function() {
function subCat() {
var mainCatID = $(this).val();
var id = $('#catID').val();
$.ajax({
type: "POST",
url: "panel/subCatPost.php",
data: {id: id, mainCatID: mainCatID}
}).done(function() {
alert('its done. its gone. Yes Mr.Frodo. Its all over now !!');
});
}
subCat();
});
});
</script>
And this is how a fill dropdowns :
while ($cat = mysql_fetch_array($cat_query)) {
$catTable.= '<label>' . $cat['name'] . '</label>';
$catTable.= '<div class="catContainer"><div id="catPost" class="catPostClass">';
$catTable.= '<input type="text" id="catID" class="catIDClass" value="' . $cat['id'] . '"><select id="catSelected" class="catSelectedClass" name="catSelected"><option value="0">Seçiniz...</option>' . catOption($cat['mainCatID']) . '</select></div>';
$kategoriTablosu.= '<div id="subCat"><select id="subCatID" class="SubCatClass"><option value="0">Seçiniz...</option>' . subCatOption($cat['mainCatID']) . '</select></div></div>';
}
My both functions:
function catOption($id) {
$query = mysql_query("SELECT * FROM mainCats WHERE id=mainCatID") or die(mysql_error());
$arrCat = "";
while ($row = mysql_fetch_array($query)) {
$arrCat .= '<option value="' . $row['mainCatID'] . '"';
if ($row['id'] == $id) {
$catSelected = 'selected="selected"';
} else {
$catSelected = "";
}
$arrCat .= '' . $catSelected . '>' . $row['name'] . '</option>';
}
return $arrCat;
}
And :
function subCatOption($subID) {
$subCat = mysql_query("SELECT * FROM mainCats WHERE mainCatID='$subID' ORDER BY id ") or die(mysql_error());
$subArrCat = "";
while ($row = mysql_fetch_array($subCat)) {
$subArrCat .= '<option value="' . $row['mainCatID'] . '"';
if ($row['mainCatID'] == $subID) {
$catSelected = 'selected="selected"';
} else {
$catSelected = "";
}
$subArrCat .= '' . $catSelected . '>' . $row['name'] . '</option>';
}
return $subArrCat;
}
Thanks for any help !
You need to change your code as
$(".catSelectedClass").change(function() {
var mainCatID = $(this).val();
//Rest of code....
});
Instead of
$(".catSelectedClass").change(function() {
// alert('i'm inside the function dude');
function ustCat() {
var mainCatID = $(this).val();
//Rest of code....
}
});
Same with $(".subCatClass").change(function() {
General Syntax
$(selector).change(function() {
//do something
});
If you have already defined function use
$(selector).change(your_defined_function);
in your case you can use
$(".catSelectedClass").change(ustCat);
the problem is that you call a function in the event handler. If you instead put the code inside the event handler or you turn the function in the handler it should fix your problem. I suggest to make the function the event handler. So just put the ustCat on its own and use the following to make the function the handler
$(".catSelectedClass").change(ustCat);
You don't need the functions inside the change function. You can simply do:
$(".catSelectedClass").change(function () {
// alert('i'm inside the function dude');
alert(this);
var mainCatID = $(this).val();
alert('mainCatID captured');
var id = $(this).parent().$(".catIDClass").val();
// alert(id);
// alert(mainCatID);
$.ajax({
type: "POST",
url: "panel/catGroupPost.php",
data: {
id: id,
mainCatID: mainCatID
}
}).done(function (data) {
var responseData = data;
alert(responseData);
$('#subCat').html($(data));
});
});
$(".subCatClass").change(function () {
var mainCatID = $(this).val();
var id = $('#catID').val();
$.ajax({
type: "POST",
url: "panel/subCatPost.php",
data: {
id: id,
mainCatID: mainCatID
}
}).done(function () {
alert('its done. its gone. Yes Mr.Frodo. Its all over now !!');
});
});
The way you did it this was in the wrong scope. this would be window.
Several ways to do it.
You don't really need to define ustCat, you can just put the code inside the change function :
$(".catSelectedClass").change(function() {
var mainCatID = $(this).val();
....
});
Or assign the parent before you call your inner function :
$(".catSelectedClass").change(function() {
(function ustCat(self){
var mainCatID = self.val();
......
})($(this));
});
Or put the ustCat function elsewere and just pass it to the change handler :
function ustCat(){ var mainCatID = $(this).val(); ...... };
$(".catSelectedClass").change(ustCat);

Categories

Resources