Unable to change button UI on AJAX getJSON .done - ajax

After creating add post to favorite and posted at codereview i had to improve my code as bellow,
And after changing code the button UI doesn't change when clicked
post_page.php
<?php
$email = 'user#mail.com';
// Query to get the user_id
$stmt = $conn->prepare('SELECT memberID FROM members WHERE email = :email AND active="Yes" ');
$stmt->execute(array(':email' => $email));
$row = $stmt->fetch();
$mbid = $row['memberID'];
$pid = '4';
// Query to Get the Director ID
$stmt = $conn->prepare('SELECT * FROM allpostdata WHERE id =:id');
$stmt->execute(array(':id' => $pid));
$result = $stmt->fetchAll();
foreach ($result as $row) {
echo "<p>Director: " . $row['tit'] . "</p> ";
$fav_image = checkFavorite($mbid, $pid, $conn);
echo "Favorite? : " . $fav_image . "";
}
function checkFavorite($mbid, $pid, $conn) {
$stmt = $conn->prepare("SELECT * FROM favorite WHERE memberID=:mid AND id=:id");
$stmt->execute(array(':mid' => $mbid, ':id' => $pid));
$count = $stmt->rowCount();
if ($count == 0) {
echo "<div class='button btn btn-block btn-outline-danger' method='Like' data-user=" . $mbid . " data-post=" . $pid . "> Add<i class='mi mi_sml ml-2' id=" . $pid . ">favorite_border</i></div>";
} else {
echo "<div class='button btn btn-block btn-outline-danger' method='Unlike' data-user=" . $mbid . " data-post=" . $pid . ">Remove<i class='mi mi_sml ml-2' id=" . $pid . ">favorite</i></div>";
}
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script>
$(document).ready(function () {
$('.button').click(function (e) {
e.preventDefault();
$.getJSON('favs.php',
{user_id: $(this).attr('data-user'),
director_id: $(this).attr('data-post'),
method: $(this).attr('method')})
.done(function (json) {
switch (json.feedback) {
case 'Like' :
$(this).attr('method', 'Unlike');
$(this).html('<i class="mi mi_sml text-danger" id="' + json.id + '">favorite</i>Remove Favorite').toggleClass('button mybtn'); // Replace the image with the liked button
break;
case 'Unlike' :
$(this).html('<i class="mi mi_sml" id="' + json.id + '">favorite_border</i>Add Favorite').toggleClass('mybtn button');
$(this).attr('method', 'Like');
break;
case 'Fail' :
alert('The Favorite setting could not be changed.');
break;
}
})
.fail(function (jqXHR, textStatus, error) {
alert("Error Changing Favorite: " + error);
});
});
});
</script>
favs.php
<?php
include("$_SERVER[DOCUMENT_ROOT]/include/config.php");
include("$_SERVER[DOCUMENT_ROOT]/classes/function.php");
$method = clean_input($_GET['method']);
$user_id = clean_input($_GET['user_id']);
$director_id = clean_input($_GET['director_id']);
switch ($method) {
case "Like" :
$query = 'INSERT INTO favorite (memberID, id) VALUES (:mID, :pID)';
break;
case "Unlike" :
$query = 'DELETE FROM favorite WHERE memberID=:mID and id=:pID';
break;
}
$feedback = 'Fail'; // start with pessimistic feedback
if (isset($query)) {
$stmt = $conn->prepare($query);
$stmt->bindParam(':mID', $user_id, PDO::PARAM_INT, 12);
$stmt->bindParam(':pID', $director_id, PDO::PARAM_INT, 12);
if ($stmt->execute()) {
$feedback = $method;
} // feedback becomes method on success
}
echo json_encode(['id' => $director_id,
'feedback' => $feedback]);
?>
My problem is when button is clicked and when ajax return success the button should change its UI.
where else in my case its not changing when on page load it show Add even after clicking on button and ajax return success still it is same.

The problem with your code is $(this) i.e: In ajax success function jquery is not able to find which element is clicked and where to apply required changes. To solve this you can store $(this) in some variable and use the same. Like below :
$('.button').click(function(e) {
//getting current element which is clicked
var button = $(this);
e.preventDefault();
$.getJSON('favs.php', {
user_id: $(this).attr('data-user'),
director_id: $(this).attr('data-post'),
method: $(this).attr('method')
})
.done(function(json) {
switch (json.feedback) {
case 'Like':
button.attr('method', 'Unlike');
button.html('<i class="mi mi_sml text-danger" id="' + json.id + '">favorite</i>Remove Favorite').toggleClass('button mybtn'); // Replace the image with the liked button
break;
case 'Unlike':
button.html('<i class="mi mi_sml" id="' + json.id + '">favorite_border</i>Add Favorite').toggleClass('mybtn button');
button.attr('method', 'Like');
break;
case 'Fail':
alert('The Favorite setting could not be changed.');
break;
}
})
.fail(function(jqXHR, textStatus, error) {
alert("Error Changing Favorite: " + error);
});
});

Related

how to create a new div of json response array from controller

I have a case of wanting to create a div element based on the element div obtained from json response I checked in the console data successfully passed to view blade, the error is to fail add new element div based on json response obtained. Can anyone help?
my code
public function getIDpotongan($id)
{
$data = array();
$list = PotonganPenggajianModel::where('nip', $id)->get();
foreach ($list as $row) {
$val = array();
$val[] ='<h3> ' . "'" . $row['jenis_potongan'] . "'" . '</h3>';
$data[] = $val;
}
$output = array("data" => $data);
return response()->json($output);
}
AJAX
$('#nama').on('change', function () {
var optionText = $("#nama option:selected").val();
$.ajax({
url: "<?php echo url('/'); ?>" + "/getidpotongan/" + optionText,
type: "GET",
dataType: "JSON",
success: function (data) {
alert(data);
$('#potonganku').html(data);
},
error: function (request, status, error) {}
});
});
blade
<div id="potonganku" class="form-group row"> </div>
Best way in that case is to build markup on the client side. Return raw JSON data from controller, and then build HTML via JS.
Controller:
public function getIDpotongan($id)
{
return response()->json([
'data' => PotonganPenggajianModel::where('nip', $id)
->select('jenis_potongan', 'some_field')
->get(),
]);
}
JS
$('#nama').on('change', function () {
var optionText = $("#nama option:selected").val();
var buildHTML = function (data) {
var html = '';
for (i in data) {
html += '<h3>' + data[i].jenis_potongan + '</h3>';
// someting with data[i].some_field
}
return html;
};
$.ajax({
url: "<?php echo url('/'); ?>" + "/getidpotongan/" + optionText,
type: "GET",
dataType: "JSON",
success: function (response) {
$('#potonganku').html(buildHTML(response.data));
},
error: function (request, status, error) {}
});
});
You're creating a new empty $val = array(); array for every foreach. lets put it outside.
So your Controller would be:
public function getIDpotongan($id)
{
$data = array();
$list = PotonganPenggajianModel::where('nip', $id)->get();
$val = array();
foreach ($list as $row) {
$val[] ='<h3> ' . "'" . $row['jenis_potongan'] . "'" . '</h3>';
$data[] = $val;
}
$output = array("data" => $data);
return response()->json($output);
}

How to change 'active/inactive status of user' through ajax?

I am display list of users in datatable based on 2 parameters through AJAX in codeigniter. I want to change the status of user in database and display in table. I have 3 status 0-> inactive, 1->active, -1->left. I want to change the status and display in datatable without reloading the page.
I have tried changing the status but the status is changing only once. After first AJAX call there is no change when i again change the status.
//view
<script>
$(document).ready(function()
{
$('#academicTable_wrapper').hide();
$('#studentTable').DataTable();
showStudents();
function showStudents()
{
$('#submitBtn').on('click',function(){
var courseId = $('#courseId').val();
var classId = $('#classId').val();
$.ajax({
type : 'POST',
url : "<?php echo base_url();?>Student/getStudentsList",
// async : true,
data : {courseId:courseId,classId:classId},
dataType : 'json',
success : function(data){
//alert(data);
var html = '';
var i;
for(i=0; i<data.length; i++){
var studentId = data[i].studentId;
if(data[i].status == 1)
var status = "Approved";
else if(data[i].status == 0)
var status = "Pending";
else
var status = "Left";
html += '<tr>'+
'<td>'+data[i].studentId+'</td>'+
'<td>'+data[i].studentName+'</td>'+
'<td>'+data[i].studentPhoneNum+'</td>'+
'<td>'+data[i].created_on+'</td>'+
'<td id="changeStatus">'+status+'</td>'+
'<td>'+
'View'+
' '+
'<a id="activateBtn" data-id="'+data[i].id+'" data-status="'+data[i].status+'" class="btn btn-primary btn-sm text-white">Activate/Deactivate</a>'+
' '+
'Delete'+
'</td>'+
'</tr>';
}
$('#studentTable').DataTable().destroy();
$('#showData').html(html);
$('#studentTable').DataTable();
$('#academicTable_wrapper').show();
}
});
});
}
$(document).on('click','#activateBtn',function()
{
var id = $(this).data('id');
var status = $(this).data('status');
$.ajax({
method: 'POST',
url: "<?php echo base_url();?>Student/approveStudent",
data:{id:id,status:status},
success : function(data)
{
alert(data);
$('#changeStatus').text('');
if(data == 0)
{
showStudents();
$('#changeStatus').html('Inactive');
}
else{
showStudents();
$('#changeStatus').html('Approv');
}
},
error:function(data)
{
console.log(data);
}
},1000);
});
});
</script>
//controller
function approveStudent()
{
$id = $this->input->post('id');
$status = $this->input->post('status');
$col = 'id';
$query = $this->Admin_model->activate($col,$id,$status,$this->studentDetail);
if($query){
$result = $this->Admin_model->getData($col,$id,$this->studentDetail);
}
$status = 1;
if ($result[0]->status == 0)
{
$status = 0;
}
echo $status;
}
I expect whenever I click activateBtn the status should change in database and also in datatable.

Wordpress ajax: submit form then go to homepage instead of replacing html tag

I tried many times but it does not work as I expect to. I have a form submit a company name back to wordpress ajax to query AD in order to get a list of users. However, everytime I hit submit button, it just loads the homepage of the website. Please look at and show me the incorrect point in my code
Here is the code in function.php
function load_scripts() {
wp_enqueue_script('jquery');
wp_register_script('directory_script',get_template_directory_uri().'/js/directory.js',array('jquery'));
wp_enqueue_script('directory_script');
wp_register_script('directory1_script',get_template_directory_uri().'/js/directory1.js',array('jquery'));
wp_enqueue_script('directory1_script');
}
add_action ('wp_enqueue_scripts','load_scripts');
// buildDirectory function
function buildDirectory () {
$Company = $_GET["companyname"];
$ad = "ad1.p.local";
$result1;
exec("ping -n 3 " . $ad, $output, $result1);
if ($result1 != 0) {
$ad = "ad2.p.local";
exec("ping -n 3 " . $ad, $output, $result1); }
elseif ($result1 != 0) {
$ad = "ad3.p.local";
exec("ping -n 3 " . $ad, $output, $result1); }
//else { echo "Unable to get contact"; }
$ldap_connection = ldap_connect($ad);
ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3) or die("Unable to set LDAP protocol version");
ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, 0);
$result;
$ldap_password = "abc";
$ldap_username = "cde";
$bind = ldap_bind($ldap_connection, $ldap_username, $ldap_password);
//$Company = "Patrick Industries";
//if (TRUE === $bind)
// {echo "Binding is successful<br />";}
//else {echo "Binding is unsuccessful<br />";}
if (TRUE === $bind) {
$ldap_base_dn = "DC=p,DC=local";
$search_filter = "(&(objectCategory=person)(objectClass=user)(company=$Company))";
$attributes = array();
$attributes[] = 'givenname';
$attributes[] = 'mail';
$attributes[] = 'samaccountname';
$attributes[] = 'sn';
$attributes[] = 'telephonenumber';
$attributes[] = 'company';
$result = ldap_search($ldap_connection, $ldap_base_dn, $search_filter, $attributes);
if (FALSE !== $result) {
$entries = ldap_get_entries($ldap_connection, $result);
// echo "<br />Found " . $entries["count"] . " entries <br />";
echo "<h4>List of contacts:</h4><br />";
echo "<table><tr>
<th style='font-weight:bold;font-size:16px;width:150px'>Name</th>
<th style='font-weight:bold;font-size:16px;width:120px'>Phone</th>
<th style='font-weight:bold;font-size:16px;width:220px'>Email</th>
<th style='font-weight:bold;font-size:16px;width:160px'>Company</th>
</tr><tr>";
$count1 = 0;
for ($x=0; $x<$entries['count']; $x++){
if (!empty($entries[$x]['givenname'][0]) &&
!empty($entries[$x]['mail'][0]) &&
!empty($entries[$x]['samaccountname'][0]) &&
!empty($entries[$x]['telephonenumber'][0]) &&
!empty($entries[$x]['sn'][0]))
{ echo "<td>". $entries[$x]['givenname'][0] . " " . $entries[$x]['sn'][0] . "</td>";
echo "<td>". $entries[$x]['telephonenumber'][0] . "</td>";
echo "<td>" . $entries[$x]['mail'][0] . "</td>";
echo "<td>". $entries[$x]['company'][0] . "</td></tr>";
$count1++; }
// { $user = $entries[$x]['givenname'][0] . " " . $entries[$x]['sn'][0] . " , " . $entries[$x]['telephonenumber'][0] . " , " . "" . $entries[$x]['mail'][0] . "" . " , " . $entries[$x]['company'][0] . " .<br />";}
}
// echo "There are " . $count1 . " contacts";
echo "</table>";
}
}
die();
}
add_action('wp_ajax_bDirectory','buildDirectory');
add_action('wp_ajax_nopriv_bDirectory','buildDirectory');
Here is js file
// Have to include in .js file
var $j = jQuery.noConflict();
var ajaxurl = "http://<ip>/wordpress/wp-admin/admin-ajax.php";
// build directory through form submission
$j("#company").submit(function(){
//var cname = $j("#cname").val();
var str = $(this).serialize();
$j.ajax({
url: ajaxurl,
type: "GET",
data: { action: "bDirectory", "cname": str },
success: function(html) {
$j("#company").replaceWith(html);
$j("#load").hide();
}
});
});
Here is HTML code
<form id="company" action="#">
<input id="cname" name="companyname" type="text"/>
<button type="submit">Submit</button>
</form>
You have to prevent the form from being submitted "the normal way":
$j("#company").submit(function(e){
e.preventDefault(); // Prevents the form default action to be triggered
var str = $(this).serialize();
$j.ajax({
url: ajaxurl,
type: "GET",
data: { action: "bDirectory", "cname": str },
success: function(html) {
$j("#company").replaceWith(html);
$j("#load").hide();
}
});
});
EDIT
In functions.php you use $_GET["companyname"]; but in your javascript you send data: { action: "bDirectory", "cname": str },, this should be corrected before anything.

stop page reloading when using ajax

I've created a wordpress plugin to vote on a post, using ajax.
When you click the 'vote' link the jquery popup works, your vote is added but then the page reloads
add_action("wp_ajax_my_user_vote", "my_user_vote");
add_action("wp_ajax_nopriv_my_user_vote", "my_must_login");
function my_user_vote() {
if ( !wp_verify_nonce( $_REQUEST['nonce'], "my_user_vote_nonce")) {
exit("No naughty business please");
}
$user_id = get_current_user_id();
date_default_timezone_set('GMT+2');
$dateVoted = get_user_meta($user_id, 'date');
$today = date('d M Y');
if ($dateVoted === $today){
//Already Voted
echo '<script language="javascript">';
echo 'alert("already voted")';
/*
echo 'alert("User ID: ' . $user_id . '")';
echo 'alert("Date Voted: ' . $dateVoted . '")';
echo 'alert("Today: ' . $today . '")';
*/
echo '</script>';
}else{
$vote_count = get_post_meta($_REQUEST["post_id"], "votes", true);
$vote_count = ($vote_count == '') ? 0 : $vote_count;
$new_vote_count = $vote_count + 1;
$vote = update_post_meta($_REQUEST["post_id"], "votes", $new_vote_count);
if($vote === false) {
$result['type'] = "error";
$result['vote_count'] = $vote_count;
}
else {
$result['type'] = "success";
$result['vote_count'] = $new_vote_count;
}
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
}
else {
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
update_user_meta( $user_id, 'date', $today );
}
die();
}
function my_must_login() {
echo "You must log in to vote";
die();
}
add_action( 'init', 'my_script_enqueuer' );
function my_script_enqueuer() {
wp_register_script( "my_voter_script", WP_PLUGIN_URL.'/video-of-the- day/my_voter_script.js', array('jquery') );
wp_localize_script( 'my_voter_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'my_voter_script' );
}
I also have a jquery file:
jQuery(document).ready( function() {
jQuery(".user_vote").click( function() {
post_id = jQuery(this).attr("data-post_id")
nonce = jQuery(this).attr("data-nonce")
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "my_user_vote", post_id : post_id, nonce: nonce},
success: function(response) {
if(response.type == "success") {
}
else {
alert("Your vote could not be added")
}
}
});
})
});
why is the ajax not working?
Try this
jQuery(".user_vote").click( function(e) {
e.PreventDefault();
});

$ajax is being send but is missing a value

Ok, so my script tries to request from php results from mysql and load them into a div. The results are based on nid value which is has to send this value is extracted from id="record-#" the record- is removed and the # is left to be used by ajax as id for the nid.
here is the ajax data function
$(document).ready(function() {
$(".note").live('click',function() {
$("#note_utm_con").show();
$("#note_utm_nt").html("<img src='http://www.ajaxload.info/images/exemples/4.gif' />");
$.ajax({
type: "GET",
url: "_class/view.php",
data: "ajax=1&nid=" + parent.attr('id'),
success: function(html){
$("#note_utm").html(html);
$("#note_utm_nt").html("");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {$("#note_utm_nt").html(errorThrown);}
});
});
$("#note_utm_con_cls").click(function() {
$("#note_utm_con").hide();
});
});
and here is the rest of the page
<div id="note_utm_con" style="display: none;">
<button id="note_utm_con_cls" style="width: 20px;float: right; padding: 2px;clear: both;">X</button>
<div id="note_utm"></div>
<div id="note_utm_nt"></div>
</div>
<?php
class notes {
var $host;
var $username;
var $password;
var $table;
public function display_notes() {
$q = "SELECT * FROM `notice` ORDER BY nid ASC LIMIT 12";
$r = mysql_query($q);
if ( $r !== false && mysql_num_rows($r) > 0 ) {
while ( $a = mysql_fetch_assoc($r) ) {
$nid = stripslashes($a['nid']);
$note = stripslashes($a['note']);
$type = stripslashes($a['type']);
$private = stripslashes($a['private']);
$date = stripslashes($a['date']);
$author = stripslashes($a['author']);
if($type == 1) {
$type = "posted a comment."; $icon = "http://cdn1.iconfinder.com/data/icons/Basic_set2_Png/16/megaphone.png";
} elseif($type == 2) {
$type = "raised a support ticket."; $icon = "http://cdn1.iconfinder.com/data/icons/basicset/help_16.png";
} elseif($type == 3) {
$type = "added new photo."; $icon = "http://cdn1.iconfinder.com/data/icons/Basic_set2_Png/16/photo.png";
} elseif($type == 4) {
$type = "updated profile details."; $icon = "http://cdn1.iconfinder.com/data/icons/Basic_set2_Png/16/user_info.png";
} else { }
$entry_display .= <<<ENTRY_DISPLAY
<ul class="list">
<li id="$nid">
<a href="javascript:;" id="$nid" onClick="retun false;" class="note">
<img src="$icon" />
$author,
$type
</a>
</li>
</ul>
ENTRY_DISPLAY;
}
} else {
$entry_display = <<<ENTRY_DISPLAY
<ul class="list">
<li>
<p>
<img src="http://cdn1.iconfinder.com/data/icons/basicset/monitor_16.png" />
Nothing to display
</p>
</li>
</ul>
ENTRY_DISPLAY;
}
return $entry_display;
}
public function connect() {
mysql_connect($this->host,$this->username,$this->password) or die("Could not connect. " . mysql_error());
mysql_select_db($this->table) or die("Could not select database. " . mysql_error());
return $this;
}
private function note_type() {
if($type == 1) { $type = "posted a comment!"; } elseif($type == 2) { $type = "raised a support ticket!"; } else { }
return $type;
}
}
?>
so when a LI with a class="note" is clicked it triggers AJAX call. The call then uses the ID in the href to extract the $nid from the id="record-
In my case it seems as AJAX is sending the request since view.php returns the fields where the data should be but it does not seem to pass much needed nid so PHP is uable to select proper nid from MySQL to use.
Can some one tell me whats wrong with it and how it can be fixed to get the id?enter code here
Your quotation marks are wrong. Try this:
data: "ajax=1&nid=" + parent.attr('id').replace('record-',''),
Edit: Unless you haven't posted the full code still, you don't actually set parent anywhere. This means that you will use the window.parent object, which surprisingly enough doesn't have an id. You should use this.parentNode.id instead:
data: "ajax=1&nid=" + this.parentNode.id,
From what you've written it looks as if you're passing the parent.attr("id") replace call as a string rather than extracting the variable:
data: "ajax=1&nid=" + parent.attr('id').replace('record-',''),

Resources