How to update the id attribute on $get callback jquery - javascript

I am trying to update the id attribute of a button on its click event through jquery, the success call is getting executed fine but id attribute is not updating as per the requirement, or is something i am doing wrong on success callback to check the selector class .. ( $(this).attr("id", "add_"+$id); )
<script>
$(document).ready(function() {
$(document).on('click', '.mybtnclass', function( onclick, e){
$id=$(this).attr('id');
$("#flash").show();
$("#flash").fadeIn(400);
$.get('abc.php',{id:$id},function(msg){
array=msg.split('/');
if( msg == 0) // tocheck the value is deleted
{
$('#'+$id).html('Add ');
$('#'+$id).removeClass('btn-danger');
$('#'+$id).addClass('btn-success');
$(this).attr("id", "add_"+$id);
$("#flash").hide();
}
else if( msg == 1) // tocheck the value is added
{
$('#'+$id).html('Remove');
$('#'+$id).removeClass('btn-success');
$('#'+$id).addClass('btn-danger');
$(this).attr("id", "delete_"+$id);
$("#flash").hide();
}
});
});
});
</script>
HTML
....
<button type="button" class="btn btn-<?php echo in_array($q->id, $myarray)? 'danger' : 'success' ; ?> btn-sm mybtnclass" id="<?php echo in_array($q->id, $myarray)? 'delete_'.$q->id : 'add_'.$q->id ; ?>"> <?php echo in_array($q->id, $myarray)? 'Remove ' : 'Add' ; ?> </button>
abc.php
<?php
$getval=explode('_', $_GET['id']);
$id=$getval['1'];
$action = $getval['0'];
if($action == 'delete')
{
//code for delete
echo 'add/'.$id ;
}
else
{
// code to add ...
echo 'delete/'.$id ;
}
?>

i believe the problem you have is about "this"
<script>
$(document).ready(function() {
$(document).on('click', '.mybtnclass', function( onclick, e){
$id=$(this).attr('id');
var $this_obj = $(this); // save this to a variable
$.get('abc.php',{id:$id},function(msg){
// use $this_obj instead of $(this)
// because now you are in another block, 'this' is different
});
});
});
</script>

As you are using $('#'+$id) for other oprations. Use it for changing id also
$('#'+$id).prop("id", "add_"+$id);
OTHERWISE
var self = this; //Create another variable
$.get('abc.php',{id:$id},function(msg){
$(self).attr("id", "add_"+$id); //Use other variable to perform operation
});

Not as per the question asked but still a working method
$(document).ready(function() {
$('.mybtnclass').click(function(){
$id=$(this).attr('name');
$("#flash").show();
$("#flash").fadeIn(400);
$.getJSON('abc.php',{id:$id},function(data){
alert(data.action + '-' + data.id); // to troubleshoot
if( data.action == "add")
{
$('[name ='+ $id +']').html('Add ');
$('[name ='+ $id +']').removeClass('btn-danger');
$('[name ='+ $id +']').addClass('btn-success');
$("#flash").hide();
$('[name ='+ $id +']').attr('name', data.action+'_'+data.id);
}
else if( data.action == "delete")
{
$('[name ='+ $id +']').html('Remove');
$('[name ='+ $id +']').removeClass('btn-success');
$('[name ='+ $id +']').addClass('btn-danger');
$("#flash").hide();
$('[name ='+ $id +']').attr('name', data.action+'_'+data.id);
}
});
I am passing the value from abc.php as
echo json_encode( array("action"=>"add","id"=>$id) );

Related

how to select id which is dynamically change in jquery?

here is my html:
<?php echo ($row['status'] == 1)? ?>
<span id='slide_".$row['id']."' name="slid_id" class='label label-danger'>Inactive</span>
<?php : ?>
<span id='slide_".$row['id']."' name="slid_id" class='label label-success'>Active</span>
<?php ; ?>
here is my jquery code:
$(document).ready(function()
{
$("span").click(function()
{
var id = $(":input[name=slide_id]").val();
alert(id);
});
});
i didn't get anything , i want to get the
ID & its dynamic generated value
of the span element and then perform some action like on click i want to change the status from active to inactive or vise versa.
thanks in advance.
var id = $(":input[name=slide_id]").attr('id'); should do the job. .val() only returns the current value of input elements.
Your HTML is missing from the question, but eliminating the colon in your jQuery selector might do the trick in selecting an input field - i.e. $("input[name=slide_id]").val().
If you want to get the ID attribute of a span element, this would work:
$('span_selector').attr('id');
okay finally i got the way to solve this things. m just sharing this if anyone have same issue one day then this might helpful.
html codes:
<tr class="tr">
<td class="td">
<div id="status">
<?php
echo ($row['status'] == 1)?
"<span id='".$row['id']."' class='label label-danger'>Inactive</span>":
"<span id='".$row['id']."' class='label label-success'>Active</span>";
?>
</div>
</td>
</tr>
my jquery code:
$(document).ready(function()
{
$("#status > span") .click(function()
{
var id = $(this).attr('id');
var tempelement = $(this);
var texts = $(this).closest(".tr").find("#texts").val();
var author = $(this).closest(".tr").find("#author").val();
var status = $(this).text();
$.ajax({
type: 'POST',
url: 'manage_feedback.php',
data: {id:id, texts:texts, author:author, status:status},
success: function(data)
{
if (data == "Active")
{
$(tempelement).removeClass("label label-danger");
$(tempelement).addClass("label label-success");
$(tempelement).html(data);
alert('status changed');
}
else if (data == "Inactive")
{
$(tempelement).removeClass("label label-success");
$(tempelement).addClass("label label-danger");
$(tempelement).html(data);
alert('status changed');
}
else
{
alert(data);
}
}
});
});
php script
//ajax status changer code
if (isset($_POST['id']) && isset($_POST['texts']) && isset($_POST['status']) && isset($_POST['author']))
{
$id = $_POST['id'];
$texts = trim($_POST['texts']);
$author = trim($_POST['author']);
$status = $_POST['status'];
$qry = "SELECT count(id) as count FROM tbl_testimonials WHERE texts = '".$texts."'
AND author = '".$author."' AND id != ".$id." ";
$sql = mysql_query($qry);
$data = mysql_fetch_assoc($sql);
if ($data['count'] == 0)
{
if($status == 'Inactive')
{
$qry = "UPDATE tbl_testimonials SET status = 0 WHERE id = ".$id." " ;
$sql = mysql_query($qry);
if($sql == 1)
{
echo 'Active';
exit;
}
}
elseif ($status == 'Active')
{
$qry = "UPDATE tbl_testimonials SET status = 1 WHERE id = ".$id." " ;
$sql = mysql_query($qry);
if($sql == 1)
{
echo 'Inactive';
exit;
}
}
}
else
{
echo "name already taken";
exit;
}
}
hope it will help someone.

Passing a variable into javascript, codeigniter

I am not able to pass a variable from Codeigniter's view to controller and then model that shoots the query that is required to fetch the data from database.
here's my Controller(snippet):
public function read() {
echo json_encode( $this->random_model->getAll() );
}
Model:
public function getAll() {
$id = $this->input->post('id');
$id = intval( $id );
// print_r($sg_id);
// var_dump($sg_id);
$query = $this->db->where('id',$id)->limit( 100 )->get( 'table_name' );
if( $query->num_rows() > 0 ) {
return $query->result();
} else {
return array();
}
}
I'm sending the "$id" from another function :
function test1()
{
$blaa['id'] = $this->input->post('id');
if ($query = $this->model_name->getAll($blaa))
{
$blaa['records'] = $query;
}
//$this->model_name->getAll($blaa);
$this->load->view('view_name', $blaa);
}
this is the test1 view:
<?php $attributes = array("class" => "", "id" => "", "name" => "");
echo form_open("test/test1/", $attributes);?>
<input type="text" id="id" name="id" >
<?php echo form_submit('submit', 'Submit')?>
<?php echo form_close(); ?>
this is the view_name that shows all the data, I'm using dataTables.:
All.js that is rendered in the view_name (read data snippet):
var readUrl = 'index.php/controller_name/read'
function readUsers() {
//display ajax loader animation
$( '#ajaxLoadAni' ).fadeIn( 'slow' );
$.ajax({
url: readUrl,
dataType: 'json',
success: function( response ) {
for( var i in response ) {
response[ i ].updateLink = updateUrl + '/' + response[ i ].id;
response[ i ].deleteLink = delUrl + '/' + response[ i ].id;
}
//clear old rows
$( '#records > tbody' ).html( '' );
//append new rows
$( '#readTemplate' ).render( response ).appendTo( "#records > tbody" );
//apply dataTable to #records table and save its object in dataTable variable
if( typeof dataTable == 'undefined' )
dataTable = $( '#records' ).dataTable({"bJQueryUI": true});
//hide ajax loader animation here...
$( '#ajaxLoadAni' ).fadeOut( 'slow' );
}
});
The results that I get are only of the data having the id "0" , no matter which value I send through the test controller.
Change your model code to this :
public function getAll($id = null) {
if ($id == null)
$id = $this->input->post('id');
$id = intval( $id );
// print_r($sg_id);
// var_dump($sg_id);
$query = $this->db->where('id',$id)->limit( 100 )->get( 'table_name' );
if( $query->num_rows() > 0 ) {
return $query->result();
} else {
return array();
}
}
Try this
function getAll(id)
{
var id = id;
$.ajax({
url:"<?php echo site_url('controllerName/getAll');?>/"+id,
success:function(data)
{
alert(data);
}
});
}
Get All
In your controller try to fetch id like this
public function getAll($id)
{
echo $id;
}
for more try this : http://w3code.in/2015/10/how-to-edit-delete-and-update-data-without-refreshing-page-in-codeigniter/
add the id you want to post in ajax like this, Then you can use $this->input->post("id"); in model or controller.
$.ajax({
url: readUrl,
data:{id: id which you want to pass.}
dataType: 'json',// change this to post
success: function( response ) {
}
});

ajax on update data in database using codeigniter

<button id="survey_act" method="post" class="tiny ui blue button" type="button" value="<?php echo $surv['id']; ?>" >Activate Survey</button>
This is my button on click -
<script>
$(document).ready(function(){
$(document).on("click","#survey_act", function(){
alert(this.value);
idx = this.value;
$.ajax({
type: "POST",
url: "<?php echo base_url('index.php/admin/survey/act_surveyby_id/')?>/"+idx,
}).done(function(msg){
if(msg=="success"){
alert('You Successfully Activated the Survey!');
}
});
});
});
</script>
This is my javascript -
public function act_surveyby_id($id){
$this->load->model('survey_m');
if($this->survey_m->insert_activate($id)){
echo "success";
}else{
echo "invalid";
}
}
This is my controller -
public function insert_activate($id){
$date = date('m-d-Y',now());
$stat = 'Active';
$data = array(
'issued_date' => $date ,
'status' => $stat
);
$this->db->update('survey', $data)->where('survey_id', $id);
if($this->db->affected_rows()>0){
return true;
}else{
return false;
}
}
}
This is my model -
Problem: when i click the activate survey it wont change/update the details of the survey. I really badly need a help regarding with this. Thanks . . .
change $.ajax function like below
$.ajax({
url: '<?php echo base_url(); ?>index.php/admin/survey/act_surveyby_id',
type: "POST",
data: {
idx : idx;
},
and controller like below
public function act_surveyby_id(){
$id=$_POST['idx'];
$this->load->model('survey_m');
if($this->survey_m->insert_activate($id))
{
echo "success";
}else{
echo "invalid";
}
}

How to return with jquery an php json array object?

Hello i have an ajax form submit and i want to return json data. For some reason it doesnt work as it should. When data.error is return it should give me the message Email is incorect. Same for the other responses. What did i do wrong? My php has json header and also datatype is json.
$(function() {
$("form#login").on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "log.php",
data: $('form#login').serialize(),
dataType:"json",
success: function(data){
if(data.error == "yes")
{
$("#msg").html('Email is incorect.')
}
else if (data.mandatory == "yes")
{
$("#msg").html('please complete email and pass')
}
else if (data.tip =='user')
{
alert('it works'+ data.id);
}
},
error: function(){
alert("failure");
}
});
});
});
my php
<?php
header('Content-Type: application/json');
session_start();
include ('core/dbconfig.php');
$password=$_POST['password'];
$usernume=$_POST['email'];
$hash = hash('sha512', $password);
if ($password=='' or $usernume=='')
{
$arr[] = array('mandatory' => 'yes');
echo json_encode($arr);
}
else
{
$stmt = $dbh->prepare("SELECT * FROM Users where Email=:username and Password= :hashed");
$stmt->bindParam(':username', $usernume);
$stmt->bindParam(':hashed', $hash);
$stmt->execute();
if ($row = $stmt->fetch())
{
$_SESSION['id_user']=$row['ID_User'];
$arr[] = array(
'tip' => 'user',
'id' => '3'
);
echo json_encode($arr);
}
else
{
$arr[] = array('error' => 'yes',);
echo json_encode($arr);
}
}
?>
turn all your php instances of $arr[] = to $arr =
if(data.error != undefined) ///i think this is the right way
{
$("#msg").html('Email is incorect.')
}else if(data.length == 0){
alert("No users available");
}else {
/*
you will have to do an iteration here of your
"data" parent object through your child objects
*/
for(var x in data){
if (data[x].mandatory == "yes")
{
$("#msg").html('please complete email and pass')
}
else if (data[x].tip =='user')
{
alert('it works'+ data[x].id);
}
} //close for
} //close else

Checkbox Input doesn't work at all in chrome. Doesn't function in other browsers

Basically I want a checkbox to onClick change whether or not to show explicit content. I'll get right to the code HTML (and PHP):
</form>
<?php if (login_check($mysqli) == true) {
$username = $_SESSION['username'];
echo '
<form name="explicit">
<input type="checkbox" onClick="changeexplicit();" value="Filter Explicit Content" id="explicitcheckbox" ' ;
if (checkadult($mysqli,$username)!=1){echo "checked";}
echo ' /> <label for="explicitcheckbox" class="explicit">Filter Explicit Content</label>
</form>';}?>
Jquery: (i left the error handling blank because I didn't realize JQuery doesn't have a built in popup alert)
<script>
changeexplicit()
{
!(function($){
$(function() {
$.post('includes/changeadult.php', $('form[name="explicit"]').serialize(), function(data){
data = $.parseJSON(data);
if(data.success){
window.location.reload(true);
}
else if(data.error){
}
else{
}
});
});
})(window.jQuery);
}
</script>
PHP:
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start(); // Our custom secure way of starting a PHP session.
$response = array();
if (login_check($mysqli) == true) {
$username=$_SESSION['username'];
$result=mysqli_query($mysqli,'SELECT isAdult FROM members WHERE username = "'.$username.'"');
$userinfo = mysqli_fetch_array($result);
$isAdult=$userinfo['isAdult'];
if ($isAdult==1)
{mysqli_query($mysqli,'UPDATE members SET isAdult=0 WHERE username="'.$username.'"');}
else{
{mysqli_query($mysqli,'UPDATE members SET isAdult=1 WHERE username="'.$username.'"');}}
$response['success'] = true;
}
else if(login_check($mysqli) == false) {
$response['error'] = true;
}
echo json_encode($response);
<script>
function changeexplicit(){
$.post('includes/changeadult.php', $('form[name="explicit"]').serialize(), function(data){
data = $.parseJSON(data);
if(data.success){
window.location.reload(true);
}else if(data.error){
}else{}
});
}
</script>
Try change onClick toonchange?

Categories