I was trying to change the Image inside the loop for example If I click the button that is also inside the loop it is perfectly changing the image but other data's that are in the loop was also changing to zero(0). I also add an id to a clickable button to change the image only that I clicked..
This is what iv'e tried:
HTML
<div class="ult_tabitemname current">
<div id="dashboard">
<ul class="slider-20" style="width: 5215%; position: relative; transition-duration: 0.2s; transform: translate3d(0px, 0px, 0px);">
<li aria-hidden="false" style="float: left; list-style: none; position: relative; width: 779px;"><img src="http://myurl.com/temp/wp-content/uploads/SAVED.png"><img src="http://myurl.com/temp/wp-content/uploads/1234-1.jpg" class="image-gallery"><input class="mytravel-img-id" img-cat="20" type="hidden" value="1058"></li>
<li aria-hidden="true" style="float: left; list-style: none; position: relative; width: 779px;"><img src="http://myurl.com/temp/wp-content/uploads/SAVE.png"><img src="http://myurl.com/temp/wp-content/uploads/Travel-Personality-FAQ-image-5_09-1.jpg" class="image-gallery"><input class="mytravel-img-id" img-cat="20" type="hidden" value="1059"></li>
<li aria-hidden="true" style="float: left; list-style: none; position: relative; width: 779px;">\<img src="http://myurl.com/temp/wp-content/uploads/SAVED.png"><img src="http://myurl.com/temp/wp-content/uploads/Travel-Personality-FAQ-image-3_03-1.jpg" class="image-gallery"><input class="mytravel-img-id" img-cat="20" type="hidden" value="1060"></li>
</ul>
</div>
</div>
Ajax
$('#dashboard').on("click", 'li a.save', function(){
var img_id = $('.ult_tabitemname.current li[aria-hidden=false] .mytravel-img-id').val();
var img_cat = $('.ult_tabitemname.current li[aria-hidden=false] .mytravel-img-id').attr('img-cat');
var curr_data = $('.ult_tabitemname.current li[aria-hidden=false] a.save').attr('current-data');
$.ajax({
type : "POST",
url : stats_area_load.ajax_url,
dataType : 'json',
data : {
action : 'update_save_ajax',
img_id : img_id,
img_cat : img_cat,
curr_data : curr_data
},
beforeSend: function( response ) {
//$('.ult_tabitemname.current div#dashboard').html('<div class="loading-wrap"><img src="/wp-includes/images/spinner-2x.gif"><p class="stat-loading">Loading, Please Wait...</p></div>');
},
success: function( response ) {
$('a#img-'+img_id).html('<img src="'+response.get_img_url+'" />');
}
});
});
}
PHP
add_action( 'wp_ajax_nopriv_update_save_ajax', 'update_save_ajax', 20 );
add_action( 'wp_ajax_update_save_ajax', 'update_save_ajax', 20 );
function update_save_ajax(){
$img_id = $_REQUEST['img_id'];
$img_cat = $_REQUEST['img_cat'];
$curr_data = $_REQUEST['curr_data'];
$get_curr_uid = get_current_user_id();
$url = get_bloginfo( 'url' );
$uploads = $url . '/wp-content/uploads';
$save = $uploads. '/SAVE.png';
$saved = $uploads. '/SAVED.png';
if($curr_data == 'save'){
$get_save_url = $saved;
$curr_data_save = 'saved';
}else{
$get_save_url = $save;
$curr_data_save = 'save';
}
$param = array(
'get_img_url' => $get_save_url,
'change_curr_data' => $curr_data_save,
'get_curr_img_cat' => $img_cat
);
echo json_encode($param);
die();
}
Just to make it more clear this is the sample output.. The first Image if I clicked that violet button it works perfectly and changing the Image.. In the second photo that is the other image also changing to zero.. They are on the loop..
Are you sure there is only one li[aria-hidden=false] within the entire html?
The correct approach should be like finding the unique element in order to retrieve the properties you want, by specifying the immediate parent() of the element, for e.g.
$('#dashboard').on("click", 'li > a.save', function(){
// $( this ).parent() is the immediate parent of 'a.save' which is 'li'
var img_id = $( this ).parent().find('.mytravel-img-id').val();
var img_cat = $( this ).parent().find('.mytravel-img-id').attr('img-cat');
var curr_data = $( this ).attr('current-data');
...
See also:
.val() Returns: String or Number or Array
Description: Get the current value of the first element in the set of matched elements.
.attr( attributeName ) Returns: String
Description: Get the value of an attribute for the first element in the set of matched elements.
Related
I am using AJAX to receive data from my database on to my main PHP page.
I have a piece of code that worked, but on with PHP.
When I have just tried to put it in to AJAX (receiving format), the code that I return is not being shown.
I know my AJAX method works as I'm using it to get some other database values.
It's just the Get online users individually won't work.
When I load the page, the code shows what's inside my div id - Loading Info... and then goes blank, so I know it's trying to update it but it's not getting it correctly.
Picture showing that nothing is displayed
My PHP request code is :
//Get online users individually and echo if they're online or not in a div class
$user_grab = mysqli_query($con, "SELECT * FROM users");
while($users_ = mysqli_fetch_array($user_grab)) {
$last_online = strtotime($users_['lastonline']);
if(time() - $last_online < 30) {
$client_is_online = '
<div class="chat-list-item -available" style="background: rgba(255,255,255,0.1); padding: 5px;">
<img class="chat-list-avatar" src="'.$users_['profile_picture'].'" style="width: 40px; height: 40px; padding: 7px; border-radius: 20px;" /><i class="fa fa-circle chat-list-status"> </i>
<div class="chat-list-user">'.$users_['username'].' (<font size="2">'.get_users_level_all($users_['userLevel']).'</font>)</div>
<div class="chat-list-excerpt">Online</div>
</div>
';
} else {
$client_is_online = '
<div class="chat-list-item -offline" style="background: rgba(255,255,255,0.1); padding: 5px;">
<img class="chat-list-avatar" src="'.$users_['profile_picture'].'" style="width: 40px; height: 40px; padding: 7px; border-radius: 20px;" /><i class="fa fa-circle chat-list-status"> </i>
<div class="chat-list-user">'.$users_['username'].' (<font size="2">'.get_users_level_all($users_['userLevel']).'</font>)</div>
<div class="chat-list-excerpt">Offline</div>
</div>
';
}
}
//I then echo it back to my home PHP page so it can read the values
//Ignore my other code definitions below as I know they work
//$client_is_online is the only one which doesn't
echo $totalUsers.",".$totalOnline.",".$freemode.",".$bypasses.",".$client_is_online;
My AJAX recieve code is :
<script>
function fetchOnline() {
$.ajax({
url: "includes/get_dash_settings.php",
context: document.body,
success: function(value){
var data = value.split(",");
$('#totalUsers').html(data[0]);
$('#totalOnline').html(data[1]);
$('#freeModeStatus').html(data[2]);
$('#bypassesStatus').html(data[3]);
$('#isOnline').html(data[4]);
},
complete:function(){
setTimeout(fetchOnline,5000);
}
})
}
$(document).ready(function() { setInterval(fetchOnline,5000); });
</script>
I then try storing the returned data in-side my div id :
<div class="sidebar-tab-content" id="staff">
<div class="chat-list sidebar-content-section" id="isOnline">
Loading Info...
</div>
</div>
Return the json data like this
1st : your overwriting the variable . you need to concatenate all user like this
$client_is_online=""; //declare empty string before while loop start
//while loop start here
$client_is_online .= 'html here';
// while end here
2nd : Return the json data like this
$response = array ('totalUsers'=> $totalUsers, 'totalOnline'=> $totalOnline,'freemode'=>$freemode,'bypasses'=>$bypasses,'client_is_online'=>$client_is_online);
header('Content-Type: application/json');
echo json_encode($response);
3rd : Don't forgot to add dataType in ajax
dataType: "json",
4rd : success function should be changed like this
ajax :
success: function(value){
var data = JSON.parse(value);
$('#totalUsers').html(data['totalUsers']);
$('#totalOnline').html(data['totalOnline']);
$('#freeModeStatus').html(data['freemode']);
$('#bypassesStatus').html(data['bypasses']);
$('#isOnline').html(data['client_is_online']);
},
Click http://jsfiddle.net/4y1b1j8g/25/ to see the result. I want to move the cross sign to the right side which will not appear over the text. I want it to be like Stackoverflow tag. And then click the image and remove it. I've try to use $(removePic).click.(function() { $(removePic).remove()}):, but it is not working.
var removePic = $('.test').css({'background-image' : 'url(https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/16x16/DeleteRed.png)',
'background-repeat' : 'no-repeat',
'background-position' : 'right'})
.test {
display: inline-block;
margin: 0 3px 0 0;
border:solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="test" id="test0">dog</div>
<div class="test" id="test1">lion</div>
<div class="test" id="test2">cat</div>
$(document).ready(function(){
$(".test").append('<img src="https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/16x16/DeleteRed.png">');
$(document).on("click", ".test img", function() {
$(this).parent().remove();
});
});
Working Fiddle
There are a lot of solutions out there as to how to save the position of draggable DIVs but I haven't found any that will help with using a While loop in php.
I have a database of "needs" and I want to display all the "needs" that match the persons username and status=inprogress. This could be 1 need or 1,000,000 needs depending on if the criteria is met.
I want to save the position of the need (DIV) automatically when it's moved. Is this possible? I wanted to store the values in a database using SQL if I can.
Here the code I currently have that displays the "needs" (divs)
Header
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<style>
#set div { width: 90px; height: 90px; padding: 0.5em; float: left; margin: 0 10px 10px 0; }
#set { clear:both; float:left; width: 368px; height: 120px; }
p { clear:both; margin:0; padding:1em 0; }
</style>
<script>
$(function() {
$( "#set div" ).draggable({
stack: "#set div"
});
});
</script>
Body
<div id="set">
<?
$query = mysql_query("SELECT * FROM needs WHERE (needsusername='$username' OR workerusername='$username') AND status='inprogress'");
while ($rows = mysql_fetch_assoc($query)) {
$title = $rows['titleofneed'];
$status = $rows['status'];
echo "
<div class='ui-widget-content'>
$title<br>Status: $status<br>
</div>
";
}
?>
</div>
Insert Query
$x_coord=$_POST["x"];
$y_coord=$_POST["y"];
$needid=$_POST["need_id"];
//Setup our Query
$sql = "UPDATE coords SET x_pos=$x_coord, y_pos=$y_coord WHERE needid = '$needid'";
//Execute our Query
if (mysql_query($sql)) {
echo "success $x_coord $y_coord $needid";
}
else {
die("Error updating Coords :".mysql_error());
}
You can use the stop event of draggable to get noticed when an element has reached a new position. Then you just have to get the offset as described in the docs.
Assuming you have a setup like that:
<div id="set">
<div data-need="1"></div>
<div data-need="2"></div>
<div data-need="3"></div>
<div data-need="4"></div>
<div data-need="5"></div>
</div>
I've used a data attribute to store the id of the "need", you can later on use that id to store the position of the "need" in the database.
Now as mentioned before, use the stop event to send an ajax call to the server with the id of the need and the x and y postion of it. Be aware hat this is the position of the screen so if you have different screen sizes you should probably use positions relative to a parent container with a desired position.
$(function() {
$( "#set div" ).draggable({
stack: "#set div",
stop: function(event, ui) {
var pos_x = ui.offset.left;
var pos_y = ui.offset.top;
var need = ui.helper.data("need");
//Do the ajax call to the server
$.ajax({
type: "POST",
url: "your_php_script.php",
data: { x: pos_x, y: pos_y, need_id: need}
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
});
});
This way every time a draggable element reaches a new positions e request will be sent to your_php_script.php. In that script you then only have to grab the post parameters and store them in the database.
There is a working fiddle, of course the ajax request is not working but you can see whats going on in the console.
I am attempting to update some sortable divs that are connected with connectwith. I have done a single table before and the update query works, but when mutiple divs are involved it gets tricky. The problem is I have a field in the database called div that needs to update as well with whatever div the sortable object is getting dropped into AS WELL AS put it in a specific order within that div.
EDIT: SOOO, how can I create a sortable update query for multiple div.id locations?
The results I am getting from the code work for just updating the order inside one div, but across multiple divs there is no update. Plus, I'm not exactly sure of the easiest way to find the div I moved the content to and save that to the database.
Okay, so here's the code I have so far for just updating the order within one div:
$(".heriyah").sortable({
handle : '.handle',
connectWith: ".heriyah",
revert: "invalid",
update : function () {
var order = $('.heriyah').sortable('serialize');
$("#info").load("admin/sortable.php?"+order);
}
});
And the PHP:
foreach ($_GET['listItem'] as $position => $item) :
$sql[] = "UPDATE `temp` SET `order` = $position WHERE `id` = $item";
endforeach;
print_r ($sql);
And the HTML/PHP to produce the content (using alot of PHP and JQuery):
<script type="text/javascript">
(function() {
$('div.heriyah').each(function() {
$(this).html('<div class="add"><div id="add_button_container"><div id="add_button" class="edit_links">+ ADD NEW CONTENT</div></div></div><div class="clear"></div><div class="placeable" style="height:20px;background-color:#fff;"></div></div>');
var curID = $(this).attr('id');//get the id before you go into fallr
$('.add').click(function() {
$.fallr('show', {
content : '<iframe width="620" height="600" src="<? echo $URL ?>/manage_content.php?pageID=<? echo $pageID; ?>&div='+ curID +'"></iframe>',
width : 620 + 5, // 100 = for width padding
height : 600,
closeKey : true,
closeOverlay : true,
buttons : {}
});
});
});
})();
<?
include_once('system/js/dbc.php');
$pageID = $_REQUEST['pageID'];
$getdiv2 = mysql_query("SELECT * FROM temp WHERE pageID = '$pageID' ORDER BY `order` ASC");
while ($row = mysql_fetch_assoc($getdiv2))
{
echo "$('#{$row['div']}.heriyah').append('<div class=sortable id=listItem_{$row['id']}><div id=heriyah_content class=sortable_header>{$row['title']}<br>{$row['maintext']}<div id=heriyah_handle class=handle></div><a onClick=edit_{$row['id']}();return false><div id=heriyah_content_hover></div></a></div></div>');\n";
}
?>
</script>
<script>
$(".heriyah").sortable({
handle : '.handle',
connectWith: ".heriyah",
revert: "invalid",
update : function () {
var order = $('.heriyah').sortable('serialize');
$("#info").load("admin/sortable.php?"+order);
}
});
</script>
<div id="info"></div>
I have produced something based on the jQuery UI connect-lists example.
I have not implemented the backend calling or database side components but I'm sure you can work that out. I am only interested in capturing what has moved and to where.
The receive event is triggered when you drag items between lists so we can use that.
We also need to catch the update event but are not interested in items that are already being dealt with by the receive event. To do this we need to check to see if ui.sender is undefined (as it will be for all non-connected list transfers). However it seems that the update event calls all the sortable containers when the update has completed. We only want to capture the data when the updated item's parent is the same as the list receiving the update event trigger. (I hope that makes sense!)
In summary the receive event will be used to capture all the inter connect-list transfers and the update event will capture any sorting that happens within an element list.
<!DOCTYPE html>
<html lang="en">
<head>
<base href="http://jqueryui.com/demos/sortable/"/>
<meta charset="utf-8">
<title>jQuery UI Sortable - Connect lists</title>
<link rel="stylesheet" href="../../themes/base/jquery.ui.all.css">
<script src="../../jquery-1.6.2.js"></script>
<script src="../../ui/jquery.ui.core.js"></script>
<script src="../../ui/jquery.ui.widget.js"></script>
<script src="../../ui/jquery.ui.mouse.js"></script>
<script src="../../ui/jquery.ui.sortable.js"></script>
<link rel="stylesheet" href="../demos.css">
<style>
#sortable1, #sortable2, #sortable3 { list-style-type: none; margin: 0; padding: 0; float: left; margin-right: 10px; }
#sortable1 li, #sortable2 li, #sortable3 li { margin: 0 5px 5px 5px; padding: 5px; font-size: 1.2em; width: 120px; }
</style>
<script>
$(function() {
$( "#sortable1, #sortable2, #sortable3" ).sortable({
connectWith: ".connectedSortable",
update: function(event, ui){
if(($(ui.sender).attr('id') == undefined)&&($(this).attr('id') == ui.item.parent().attr('id'))){
alert('UPDATE ' + $(this).attr('id') + ' ' + (ui.item.index()+1) + ' ' + $(ui.item).text());
}
},
receive: function(event, ui){
alert('RECEIVE: ' + $(ui.sender).attr('id') + '=>' + $(this).attr('id') + ' ' + (ui.item.index()+1) + ' ' + $(ui.item).text());
}
}).disableSelection();
});
</script>
</head>
<body>
<div class="demo">
<ul id="sortable1" class="connectedSortable">
<li class="ui-state-default">A</li>
<li class="ui-state-default">B</li>
<li class="ui-state-default">C</li>
<li class="ui-state-default">D</li>
<li class="ui-state-default">E</li>
</ul>
<ul id="sortable2" class="connectedSortable">
<li class="ui-state-highlight">F</li>
<li class="ui-state-highlight">G</li>
<li class="ui-state-highlight">H</li>
<li class="ui-state-highlight">I</li>
<li class="ui-state-highlight">J</li>
</ul>
<ul id="sortable3" class="connectedSortable">
<li class="ui-state-default">K</li>
<li class="ui-state-default">L</li>
<li class="ui-state-default">M</li>
<li class="ui-state-default">N</li>
<li class="ui-state-default">O</li>
</ul>
</div>
</body>
</html>
function showComments(wallID){
$.ajax({
url: "misc/showComments.php",
type: "POST",
data: { mode: 'ajax', wallID: wallID },
success: function(msg){
var $msg = $('#showWallCommentsFor'+wallID).find('.userWallComment');
// if it already has a comment, fade it out, add the text, then toggle it back in
if ( $msg.text().length ) {
$msg.fadeOut('fast', function(){
$msg.text( msg ).slideToggle(300);
});
} else {
// otherwise just hide it, add the text, and then toggle it in
$msg.hide().text( msg ).slideToggle(300);
}
}
});
}
msg, the response i get: ( firebug )
<span class='userWallComment'>
<span style='float: left;'>
<img style='border: 1px solid #ccc; width: 44px; height: 48px; margin-right: 8px;' src='images/profilePhoto/thumbs/noPhoto_thumb.jpg'>
</span></span>
<span style='font-size: 10px; margin-bottom: 2px;'>
<a href='profil.php?id=1'>Navn navn</a> - igår kl. 01:55
</span>
<br>
DETTE ER EN TEST
<br>
<div class="clearfloat"></div>
</span>
It sends and execute the ajax call properly, and it have something in response, but it doesnt toggle it?
This is the div:
<div id="showWallCommentsFor<?php echo $displayWall["id"]; ?>" style="display: none;">
</div>
The Problem
Your if - else statement has a flaw:
if ( $msg.text().length ) {
// ...
} else {
// $msg has a length of ZERO by definition here!!!
$msg.hide().text( msg ).slideToggle(300);
}
The very first time the AJAX call is fired #showWallCommentsFor is empty, so it doesn't have .userWallComment inside it so, $msg will not be defined.
The Solution
You should add text directly to the original div in your else, using:
if ( $msg.text().length ) {
// ...
} else {
// otherwise just hide it, add the text, and then toggle it in
// You cannot use $msg here, since it has a length of 0.
// Add text directly to the original div instead.
// You do not need to hide the DIV first since it is already
// invisible.
$('#showWallCommentsFor'+wallID).text( msg ).slideToggle(300);
}
Finally, in your else, there's no need to .hide() the #showWall... div, since the div is orginally invisible due to style="display: none;".