How to make jquery to post values from a particular span to php, and then get values to a particular div? I'd like to have something like this: click span with class "more", that posts value from this li to php, and then via jquery to get value to div with id "test".
Here I have such a code which php gives me. I can add unique "id" for elements if it needs.
<li>
<span class="word">one word</span>
<span class="numb">1</span>
<span class="more">more</span>
<div id="test"></div>
</li>
<li>
<span class="word">another word</span>
<span class="numb">13</span>
<span class="more">more</span>
<div id="test"></div>
</li>
The problem is using this jquery I post only the first span containing class ".word" but instead of it I'd like to post only that spans where the span is. And get the values not to the first div with id "test" again but in the div where the span was clicked. My jquery-code is:
$('.more').live("click",function() {
var ID = $('.word').test();
var DI = $('.numb').text();
$.ajax({
type:"POST",
data: "value="+ ID + "&numb="+ DI,
cache: false,
url: "more.php",
success: function(msg){
$('#test').html(msg).fadeIn('slow');
}
});
});
By adding var ID = $(this).attr("id"); instead of var ID = $('.word').test(); to jquery and to php <span id="<?php echo $word; ?>" class="more">more</span> I can post the unique value of word. But what about the other values? And the main problem is to post to the next div where the span-button "more" is.
var ID = $('.word').test();
replace it with
var ID = $('.word').text();
Also please use .on jQuery function instead of .live as .live is deprecated.
Complete jQuery Code
$(function()
{
$('.more').on("click",function()
{
var clickedDiv = $(this);
var ID = clickedDiv.parent().find('.word').text();
var DI = clickedDiv.parent().find('.numb').text();
$.ajax(
{
type:"POST",
data: "value="+ ID + "&numb="+ DI,
cache: false,
url: "more.php",
success: function(msg)
{
clickedDiv.find('div[custom_id="test"]').html(msg).fadeIn('slow');
}
});
});
});
One more thing do not repeat same ID for DOM.
ID MUST BE UNIQUE.
For that i used <div custom_id = "test"></div>
Updated HTML
<li>
<span class="word">one word</span>
<span class="numb">1</span>
<span class="more">more</span>
<div custom_id = "test"></div>
</li>
<li>
<span class="word">another word</span>
<span class="numb">13</span>
<span class="more">more</span>
<div custom_id = "test"></div>
</li>
this can work out even without the ajax request if you are not doing any thing on the php side .
Check this code :
in the html make the div with class instead of id .
<li>
<span class="word">one word</span>
<span class="numb">1</span>
<span class="more">more</span>
<div class="test"></div>
</li>
<li>
<span class="word">another word</span>
<span class="numb">13</span>
<span class="more">more</span>
<div class="test"></div>
</li>
then
$('.more').click(function (){
var ID = $('.word').text();
var DI = $('.numb').text();
var Data = "value="+ ID + "&numb="+ DI;
$(this).closest('.test').html(Data); // use anyone of them
or
$(this).sibling('.test').html(Data); // use anyone of them
});
this will work perfectly . This is the updated code
Related
I have one table generated by PHP
<div class="mailbox-list">
<ul>
<?php while ($row=$database->fetch_array($result)){?>
<li id="emal_new" name="<?php echo $row["id"];?>">
<a href="#" >
<div class="mail-checkbox">
<input class="filled-in" id="<?php echo $row["id"];?>" type="checkbox">
<label for="<?php echo $row["id"];?>"></label>
</div>
<h5 class="mail-author">VPN Access Manager</h5>
<h4 class="mail-title"><?php echo $row["naslov"]; ?></h4>
<p class="hide-on-small-and-down mail-text">
<?php $poruka_kratka = clear_mail($row['poruka']);
echo text($poruka_kratka,"75")?></p>
<div class="position-top-right p f-12 mail-date"><?php echo $row["datum"]; ?></div>
</a>
<div id ="user-result" />
</li>
<?php }?>
</ul>
</div>
And my JQCODE is:
<script>
$(document).ready(function() {
var x_timer;
$("#emal_new").bind('click', function (e){
clearTimeout(x_timer);
var email_id = $(this).attr("name");
x_timer = setTimeout(function(){
check_email_id_ajax(email_id);
}, 100);
});
function check_email_id_ajax(email_id){
$("#user-result").html('<img style="width: 24px; height:24px;" src="<?php echo WWW; echo 'includes/themes/'.THEME_NAME.'';?>/img/ajax.gif" />');
$.post('ajax/mailbox.php',{'email_id':email_id}, function(data) {
$("#user-result").html(data);
});
}
});
</script>
And i have about 30 and more data in table and only first at table works with that jquery bind? How can bind work on all objects?
I need when i click on some row in table call ajax for more information about that row called by name.
Thanks!
This is expected behaviors as Identifiers in HTML must be unique, Use a common class to bind event handlers, also I would recommend you to use data-* prefix custom attribute to store arbitary data, which can be accessed using .data()
Change the HTML as
<li class="emal_new" data-name="<?php echo $row["id"];?>">
<div class="user-result"></div>
</li>
Script
$(document).ready(function() {
var x_timer;
$(".emal_new").on('click', function(e) {
var email_id = $(this).data("name");
var userResult = $(this).find('.user-result')
if (x_timer)
clearTimeout(x_timer);
x_timer = setTimeout(function() {
check_email_id_ajax(email_id);
}, 100);
});
function check_email_id_ajax(userResult, email_id) {
userResult.html(TheHTML);
$.post('ajax/mailbox.php', {
'email_id': email_id
}, function(data) {
userResult.html(data);
});
}
});
Also not .bind() has been deprecated. It was superseded by the .on() method for attaching event handlers to a document since jQuery 1.7
I'm currently using JQuery UI Dragabble, Droppable and sortable. I have two div sections at top and bottom of my php file were i'm dragging and dropping contents from bottom to top div sections.
In top div section i'm performing Sortable JQUery opertions my next requirment is when i perform sorting operation in top section its order should be automatically updated in my MYSQL DB i gotta stuck like how to pass the sorted order to my MySQL db via ajax and php file. Can somebody suggest some help in Achieving it!
Thanks!
Html/PHP code
<div class="drop_list">
<ol id="sortable" style="list-style:decimal;"></ol>
</div>
<div class="sort_list">
<ul id="draggable">
<?php
for($i=1;$i<=5;$i++)
{
?>
<li data-id='article_<?php echo $i;?>' class="draggable_li qitem" >
<div class="main_div">
<div class="secondary_div">
<div class="form_div">
<form>
<input style="width:15px;" type="checkbox" class="hello"/>
</form>
</div>
<label class="item_div">
<span class="item">Item = <?php echo $i; ?></span>
</label>
</div>
<button class="hello btn btn-success add_top">
Add to Top Stories
</button>
<span class="AH_section" style="display:none;float:right;">
<input type="checkbox"/>Home Section
<input type="checkbox"/>App Home Section
</span>
</div>
</li>
<?php
}
?>
</ul>
</div>
</div>
</div>
</div>
JQuery code
$(document).ready(function() {
$("#sortable").sortable({
revert: true,
refreshPositions: true ,
helper : 'clone',
cursor: "move",
delay: 1,
tolerance: 'pointer',
revert: 50
/*stop:function(event,ui){
var data = $(this).sortable('serialize');
}*/
}).serialize();
$("ol li").disableSelection();
$(".sort_list li").draggable({
//containment : "#container",
tolerance:"pointer",
helper : 'clone',
refreshPositions: true ,
revert : 'invalid',
opacity:.4,
});
$(".drop_list ol").droppable({
revert:true,
//hoverClass : 'ui-state-highlight',
greedy: true,
refreshPositions: true,
drop : function(ev, ui)
{
$(ui.draggable).clone().appendTo(this);
if($(this)[0].id === "sortable")
{
console.log($(this).closest("button").find('.hello'));
$(this).find('.hello').hide();
$(this).find('.AH_section').show();
//$(ui.draggable).draggable( 'disable' ); //this will not append dragged list at top of the container
ui.draggable.draggable( 'disable' ).closest('li').prependTo(ui.draggable.closest('ul')); //this will append dragged list at top of the container
return true;
}
}
});
});
change data-id='article_<?php echo $i;?>' to id='<?php echo $i;?>'
add this to your sortable(),
update: function (event, ui) {
var serial=$(this).sortable('serialize');
save_sortable(serial);
}
so here on update, you are calling save_sortable() function, from ajax , update your db in the order returned from sortable()
function save_sortable(serial)
{
$.ajax({
url: "path to your file to update in db.",
type: 'POST',
data: serial,
success: function (data) {
//alert(data);
}
});
}
You can add some id attribute to li, in my case will be get_id.
and then call below function onDropSendSort(); when you want, ie after drop.
<li data-id='article_<?php echo $i;?>' get_id="<?php echo $object_id; ?>" class="draggable_li qitem" >
function onDropSendSort() {
var data = [];
$('#draggable li').each(function() {
var id = $(this).attr('get_id');
data.push(id);
});
// data = [id_1, id_3, id_n];
$.ajax({
url: 'some_url',
type: 'POST',
data: {sort: data},
complete: function(res) {
console.info(res);
}
});
}
i am building a mpe player for my production website, using the jplayer. the problem i have is i give my visitors the full song to listen to and for that reason i have to attempt to secure my music so heres the problem. jplayer requires a string that is a file location to the track that is to be played. i would like to make a ajax call and return that location. i tried to return a varible after a ajax call to be placed in the string location,but the code runs threw before the call is finish....
heres my code:
html markup:
<div id="player"></div>
<!-- Using the cssSelectorAncestor option with the default cssSelector class names to enable control association of standard functions using built in features -->
<div id="jp_container" class="demo-container">
<p>
<div class="pro"></div>
<span class="play-state"></span> : <span class="track-name">nothing</span><br />
of <span class="jp-duration"></span>, which is
<span class="jp-current-time"></span><br />
</p>
<ul class="toolbar ui-widget-header ui-corner-all">
<li><button class="jp-Prev" href="#">Prev</button></li>
<li><button class="jp-play" href="#">Play</button></li>
<li><button class="jp-pause" href="#">Pause</button></li>
<li><button class="jp-stop" href="#">Stop</button></li>
<li><button class="jp-Next" href="#">Next</button></li>
<li><button class="jp-mute" href="#">Mute</button></li>
<li><button class="jp-unmute" href="#">Unmute</button></li>
<li><div class="jp-volume-bar"></div></li>
</ul>
<ul class="playlist">
<li><span>Select a track :</span></li>
<? Beats(); ?>
</ul>
</div>
Jquery markup:
$("#jp_container .track").on("click",function(event) {
var x = $(this).attr('id');
var mp3File = // maybe a function can go here
my_jPlayer.jPlayer("setMedia", {
mp3: //this is where the string is expected
});
my_jPlayer.jPlayer("play");
my_trackName.text($(this).text());
$(this).blur();
return false;
});
// here is were i get the location in a function i workout already
function url(x){
var mp3;
$.ajax({
type: "POST",
url: "hosts/beats/beat.php",
data: "<?=md5('url')?>="+x+"&ok=<?=md5(rand(1,20))?>",
dataType: "html",
success:function(data){ var mp3 = data; }
});
return mp3;
}
first "A" in AJAX is for ayshnchronous...you can't return mp3 from your function because the ajax hasn't completed when you try returning it.
You need to do the setMedia within success callback of ajax
$("#jp_container .track").on("click", function(event) {
var x = $(this).attr('id');
$.ajax({
type: "POST",
url: "hosts/beats/beat.php",
data: "<?=md5('url')?>=" + x + "&ok=<?=md5(rand(1,20))?>",
dataType: "html",
success: function(data) {
my_jPlayer.jPlayer("setMedia", {
mp3: data
});
my_jPlayer.jPlayer("play");
my_trackName.text($(this).text());
$(this).blur();
}
});
return false;
});
I have a problem with auto updating a div. I have a script as shown below which refreshes the page content (like facebook) every 1 minute. The problem is that this div is newly added to the page and that it contains some ajax/jQuery elements to add effects.
function loadNewPosts(){
var id = $(".altbgcolor:first").attr("id");
$.get('/update.php', { updateid: id ,catid:'technology' }, function(data){
$(".newslist").prepend(data);
}, 'html');
}
window.setInterval(loadNewPosts, 1000*60)
Below is an example of div its supposed to populate if found via update.php
<li class="altbgcolor" id=755>
<div> <a href=http://mashup2.sunnydsouza.com/technology/755/ target="_blank" rel="nofollow">
<div class="newsthumb" center center no-repeat;"><img src="http://mashup2.sunnydsouza.com/timthumb.php?src=/images/tech/thumb-755.jpg&h=100&w=100&zc=1&a=t" /></div>
</a>
<div class="newstext" style="margin:0px;">
<h1 style="color:#081C28;"><img width="11" height="9" src="/content/icon_topic_newest.gif"> Top 5 Android Apps for Travel </h1>
<!--<i><font color=red size=1.2>Technology</font></i><br>-->
<div style="font-size: 0.4em; color:#666666;">
<!-- AddThis Button BEGIN -->
<!--<span class="st_email" st_url="http://mashup2.sunnydsouza.com/technology/755/" st_title="Top 5 Android Apps for Travel" ></span>
<span class="st_facebook" st_url="http://mashup2.sunnydsouza.com/technology/755/" st_title="Top 5 Android Apps for Travel" ></span>
<span class="st_twitter" st_url="http://mashup2.sunnydsouza.com/technology/755/" st_title="Top 5 Android Apps for Travel" ></span>
<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>
<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=sunnydsouza"></script>-->
<!-- AddThis Button END -->
<span style="text-decoration:none; color:none; "><i> via demo1</i></span>
<span style="text-decoration:none; color:none; ">
<a class="example7" href="comments_3.php?id=755" style="text-decoration:none; color:#666666; "><img src="content/comment/comments.png" width=18 height=18><i>No comments</i></a></span>
<span style="text-decoration:none; color:none; margin:5px;"><img src="content/voting/eye.png" > 17</span>
<!-- Vote Buttons #vote-->
<span class="vote" id="755" name="up" style="text-decoration:none; color:none; margin:5px; ">
<img src="/content/voting/yes-enb.png" width=12 height=12 alt="">
<span style="text-decoration:none; color:none">1 </span></span>
<!-- Vote Buttons ENDS #vote-->
<br>
<i><font color=red size=1.2>Technology</font></i>
</div>
<!--<h1>read...</h1>-->
</div><div class="clear"></div>
</div>
<div class="sharedp">
<span class="st_email" st_url="http://mashup2.sunnydsouza.com/technology/755/" st_title="Top 5 Android Apps for Travel" ></span>
<span class="st_facebook" st_url="http://mashup2.sunnydsouza.com/technology/755/" st_title="Top 5 Android Apps for Travel" ></span>
<span class="st_twitter" st_url="http://mashup2.sunnydsouza.com/technology/755/" st_title="Top 5 Android Apps for Travel" ></span>
</div>
</li>
Though the above code calls the update.php every 1 minute and adds elements to the current page. The current div is devoid on the javascript element
This is the javascript on the main page which attaches itself to every div on every element initially to the span class="vote"
// thumbs up / thumbs down code
$(function() {
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if (name=='up')
{
//$(this).fadeIn(200).html('<img src="/content/voting/yes-enb.JPG" />');
$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
success: function(html)
{
parent.find('span').html(html);
}
});
}
return false;
});
});
However for the new elements added during the auto update, when clicking on the vote button..nothing happens.
Why is this happening. Why is the jQuery mentioned in the page at start not working for the auto newly added divs?
Please help
EDIT:: I have 2 more javascript elements. How do i convert them to .live ?
$(document).ready(function(){
$(".altbgcolor").hover(function() {
$(this)
.addClass('altbgcolor-active')
.find(".sharedp")
.slideDown('slow');
},function () {
$(this)
.removeClass('altbgcolor-active')
.find(".sharedp")
.slideUp('slow');
});
$(".example7").colorbox({
onOpen:function(){ alert('onOpen: colorbox is about to open'); },
onLoad:function(){ alert('onLoad: colorbox has started to load the targeted content'); },
onComplete:function(){ alert('onComplete: colorbox has displayed the loaded content'); },
onCleanup:function(){ alert('onCleanup: colorbox has begun the close process'); },
onClosed:function(){ alert('onClosed: colorbox has completely closed'); }
)};
});
EDIT2: This is what I am trying, Please validate if its correct...
$(".altbgcolor").live('hover',function() {
$(this)
.addClass('altbgcolor-active')
.find(".sharedp")
.slideDown('slow');
},function () {
$(this)
.removeClass('altbgcolor-active')
.find(".sharedp")
.slideUp('slow');
});
$(function() {
$(".vote").live('click', function () {
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if (name=='up')
{
$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
success: function (html) {
parent.find('span').html(html);
}
});
}
return false;
});
});
Have you considered jQuery's live() for this? It will attach the eventhandler to all current and future elements.
i have a problem with this jquery, in the success function call, its mean to remove the `support' button, and fade in the msg, this is my jquery code:
$('.stats').delegate('.against', 'click', function(e) {
//stop event
e.preventDefault();
// cache a reference to the previous <li> element
// since it is used more than once
var $prevLi = $(this).closest('li').prev('li');
//get the id
var the_id = $prevLi.attr('id').split('_').pop();
//the main ajax request
$.ajax({
context:this,
type: "POST",
data: "action=against&id=" + the_id,
url: "ajax/sa.php",
success: function (msg) {
$prevLi.find("h2.score_down").html(msg).fadeIn();
$(this).closest('li').next().next().find('button').remove(); $(this).remove();
}
});
});
the html:
<ul class="stats">
<li id="topic_20" class="score">
<h2 class="score_up" style="color:green;">10</h2>
<span style="text-align:center;">Supporters</span>
</li>
<li>
<button type="submit" value="Actions" class="support" title="support">
<i></i>
<span>Support</span>
</button>
</li>
<li id="down_20"class="score"><h2 class="score_down">20</h2><span style="text-align:center;">Against</span>
</li>
<li>
<button type="submit" value="Actions" class="against" title="against">
<i></i><span>Against</span></button>
</li>
</ul>
<h3 class="success"></h3>
this jquery is meant to remove the support button, when clicked and the new score is meant to fade in! :)) thanks
The button is in the <li> 2 previous to the .against containing one, so your .next() calls should be .prev(), like this:
$(this).closest('li').prev().prev().find('button').remove();
Why not use $("button[type=submit]")? Or just $("button")? If you use the double prev() you're going to have to adjust your code when your markup changes. If you do that often enough, that makes making changes a nightmare later.