jQuery parent usage - php

First time using jQuery parent and got confused, here's my html:
<div id="friends_inveni" class="friends_rec" style="">
<br>
<div style="height: 280px; overflow-y: auto;">
<div style="width:150px;float:left;font-size:11px;color:White;">
<input type="checkbox" name="friends" value="3265" id="friend_3265">
<img style="width:24px;vertical-align:middle;" src="https://graph.facebook.com/661382259/picture">
Test1
</div>
<div style="width:150px;float:left;font-size:11px;color:White;">
<input type="checkbox" name="friends" value="3265" id="friend_3265">
<img style="width:24px;vertical-align:middle;" src="https://graph.facebook.com/599567764/picture">
Test2
</div>
</div>
<br clear="all">
<div class="action_new_comment">
<textarea class="action_comment_input" onkeyup="check_height(this);" style="height:36px;"></textarea>
<br clear="all">
<a class="action_btn" style="font-size:11px;" name="comment" id="A1">Send Recommendation</a>
</div>
</div>
Here's my jQuery code:
jQuery(document).ready(function() {
$(".action_btn").live('click', function() {
var friends = new Array();
$(this).parents('.recommend').find('input:checked').each(function(k) { friends[k] = $(this).val(); });
var comment = $(this).parents('.recommend').find('textarea').val();
if (friends.length == 0) {
alert('Please select at least one friend.');
} else {
$.post("update.php",
{ uid: <?php echo $_SESSION['uid']; ?>, mid: <?php echo $_GET['mid']; ?>, friends: friends, comment: comment },
function() {
var newComment = $('<div class="bubble_confirmation"><h1>Recommendation Sent!</h1><br /><br > Send more</div>');
$(this).parents('.recommend').append(newComment.fadeIn());
$(this).parents('.recommend').find("input:checkbox:checked").attr("checked", "");
$(this).parents('.recommend').find('.action_comment_input').val('');
});
}
});
});
Issue is that:
1. I can't get the content of the textbox
2. I can't get the array of userid
Why is this?

It looks as though your HTML class friends_rec should be recommend, judging from your jQuery code.
Also, since we don't know what $(el) is, that should probably be $(this), instead.

Addition to what Herman said you should do:
var $parent = $(this).parents('.recommend:first')
inside of your ajax callback. The :first prevents jQuery from going up the whole tree to look for more elements of that classname after you've already found the element you're looking for and keeping it as a variable reference allows you to not create a new jQuery object each time you need to use it.

Related

Loading data into the current div

I have two divs, and when one is clicked it empties the div. I want to be able to load data into that div once it's been emptied. I've got it so it loads in both, but I only want to load data into the div that's been emptied.
HTML (I have two of these)
<div class="fl person">
<div class="maintain_size">
<input type="hidden" name="userSaved" value="<?php echo $user_one['id']; ?>" />
<img src="<?php echo "http://graph.facebook.com/".$user_one['id']."/picture?type=large"; ?>" class="circle-mask" />
<img class="hoverimage" src="images/fire_extinguisher.png" />
<div class="meta_data">
<h2><?php echo $user_one['name']; ?></h2>
</div>
</div>
</div>
Javascript
<script>
$("div.person img").click(function () {
$(this).parent("div").fadeOut(1000, function () {
var saved_id_user_who_voted_val = "<?php echo $_SESSION['id']; ?>";
var saved_id_user_voted_on_val = $(this).parent('div').find('input:hidden');
var saved_id_user_voted_on_val = saved_id_user_voted_on_val.val();
$(this).parent("div").empty();
// Load in new data
var current_div = $(this).parent("div");
$.get('loadNewUser.php', function(data) {
current_div.html(data);
});
});
});
</script>
The data seems to come through fine if I select a div that's not the current one, or I just use an alert to see if the data is there--which it is, but if I try load the data into the current div it just doesn't work. Any ideas? Thanks.
The code that I think is wrong:
$.get('loadNewUser.php', function(data) {
current_div.html(data);
});
Edit: The div I'm trying to get the data into is: div.person - although, there are 2 of these.
Once you empty the div your 'this' is no longer there. Try just declaring var current_div before you empty.
var current_div = $(this).parent("div");
current_div.empty();
$.get('loadNewUser.php', function(data) {
current_div.html(data);
});
See fiddle
You need to delegate the event as you are replacing old content with new one
$(document.body).on('click',"div.person img",function () {
Use live() function
Example
$("div.person img").live("click",function () {
//Your code goes here
});

Better PHP with Json

Hi currently i have an app on Zend php framework, and i heavily using json to fetch data from controller. Now i am not sure whether the way i parse json data into hmtl within javascript are good or not. Below are my sample code.
controller:
public function searchAction()
{
$search = $this->getRequest()->getParam('search');
$user = new Application_Model_User();
$userMapper = new Application_Model_Mapper_UserMapper();
$usersearch = $userMapper->findByString($search);
for($i=0; $i<count($usersearch); $i++)
{
$usersearch[$i]['pic'] = $this->view->getLoginUserImage($usersearch[$i]['social_id'],$usersearch[$i]['login_type'],null,null,square);
}
$this->_helper->json($usersearch);
}
View: member.phtml
<div class="container">
<div class="clearfix page-header">
<h1 class="heading">Member Search</h1>
</div>
<div class="clearfix layout-block layout-a">
<div class="column column-alpha member-search-container">
<div class="search-input-container clearfix">
<form action="/member_search?query=" class="member-search-form" id="member-search-form" method="get" name="member_search_form" data-component-bound="true">
<fieldset>
<legend>Member Search</legend>
<label for="name_field">
<strong> Name</strong>
</label>
<span class="formNote">
(e.g. Bob Smith, Bob S.)
</span><br>
<input type="hidden" name="action_search" value="Search">
<input class="name-field" id="story-title" name="query" size="90" type="text" placeholder="search" autocomplete="off" style="width:220px;">
<div id="search-box"></div>
<div class="auto-name" style="display: none;"></div>
</fieldset>
</form>
</div>
<div class="member-search-results">
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
});
$('#story-title').keyup(function(e){
var searchbox = $(this).val();
if(searchbox == '')
{
$(".similar_story_block").hide();
}else {
$.ajax({
url:"<?= $this->baseUrl('index/search')?>",
data:{'search':$('#story-title').val()},
dataType:"json",
type:"POST",
cache:false,
success:function(data){
if(data.length > 0)
{
var divHtml = '<div class="similar_story_block" style="display: block;">'+
'<div class="head">'+
'<p>People</p>'+
''+
'</div>'+
'<ul>';
for(var count=0; count<data.length;count++)
{
if(data[count]['reviews_num'] != null )
{
data[count]['reviews_num']
}
else
{
data[count]['reviews_num'] = 0
}
divHtml+='<li>'+
'<a class="pushstate no-confirm" href="' + baseUrl + 'user/' + data[count]['user_unique_name'] + '">'+
'<div class="image">'+
'<img alt="" src="'+data[count]['pic']+'">'+
'</div>'+
'<div class="fleft col-400">'+
'<p>'+ data[count]['name'] +'</p>'+
'<span>'+data[count]['reviews_num']+' Reviews</span>'+
'</div>'+
'</a>'+
'</li>';
}
divHtml += '</ul></div>';
$("#search-box").html(divHtml);
$(".search-box").show();
}
else {
$("#search-box").html('');
$(".search-box").hide();
}
}
}) }
});
function closeSearchBox(event)
{
disabledEventPreventDefault(event);
$(".similar_story_block").hide();
}
</script>
Currently the above code will do a live query of members who already signup to the site. The code work very well, but i am not sure if this is right way of doing. Below is how it looks on chrome debug console
it seems i am exposing too much of details. It would be appreciated if anyone can suggest a better way of fetch a data from controller, or how it can be done by using partial template.
Thanks for your help !!!
You can either render your template via PHP and send HTML down the wire, or you can send JSON and render your template using JavaScript.
I would suggest the latter using something like HandlebarsJS.
Define the HTML template:
<script id="member-template" type="text/x-handlebars-template">
<p>Name: {{ name }}</p>
<p>Role: {{ role }}</p>
</script>
Our example JSON data:
var data = {"name": "Bob", "role": "Manager"};
Render our template with our JSON data:
var template = Handlebars.compile($("#member-template").html());
var html = template(data);
The html variable will be your compiled HTML that you can insert witin your <div class="member-search-results"> div.
I think if your project has a lot of visitors and this operation uses often you can relay this function to them. It's could reduce little load on the server. But it could work only if you have very many visitors (pageview). But if your project not so big you can't feel the difference and "PHP way" could be easier on my mind.

Reading checkboxes values with jQuery

I have a little bit problem with reading datas from checkboxes.
{foreach value=artist2 from=$artist}
<br />
<input type="checkbox" name="artist[]" value="{$artist2.MOVIE_ID}-{$artist2.PERSON_ID}" { in_array array=$item match=$artist2.NAME_SURNAME returnvalue="CHECKED" }>{$artist2.NAME_SURNAME}<br />
<hr />
{/foreach}
<p align="right"> <a style="float: right" href='javascript:void(null);' onclick="deleteData();" ><input type="submit" name="removeArtistFromMovie" onclick="showMessage('Seçilen oyuncu(lar) başarıyla silindi')" value="Seçilenleri Sil" id="value"</p></a>
<br >
</form>
I produce checkboxes like that and in my js file:
I try this
function deleteData(){
var artistIds = new Array();
$("input[#type=artist[]][#checked]").each(function(){
artistIds.push($(this).attr('id'));
});
alert(artistIds);
$.post('/management/deleteDataAjax2',
{ json: JSON.stringify({'artistIds': artistIds}) },
function(response){
alert("Başarıyla silindi");
window.location.replace(window.location.pathname);
});
}
However, above code does not take the values of checkboxes which is checked. Why ?
Finally
I think problem is here because the page does not go to js.
<form name=form1 method=post action=# onsubmit='return validate(this)'>
<br />
<input type="checkbox" name="artist[]" value="{$artist2.MOVIE_ID}-{$artist2.PERSON_ID}" />{$artist2.NAME_SURNAME}<br />
<hr />
{/foreach}
<p align="right">
<a style="float: right" href='javascript:void(null);' onclick="deleteData();" ><br />
<input type="button" name="checkArtistButton" value="Seçilenleri Sil" id="ajaxCheckbox" /></a></p>
<br >
</form>
and this is my js
function deleteData(){
var artistIds = [];
$('#ajaxCheckbox').click(function() {
$("input[name='artist[]']:checked").each(function() {
artistIds.push($(this).attr('value'));
});
alert(artistIds);
});​
​
$.post('/management/deleteDataAjax2',
{ json: JSON.stringify({'artistIds': artistIds}) },
function(response){
alert("Başarıyla silindi");
window.location.replace(window.location.pathname);
});
}
instead of
$("input[#type=artist[]][#checked]").each(function(){
try
$("input[name='artist[]']:checked").each(function(){
Working example here
note
I think you mean to get the value of the checkboxes - as looking at your markup they do not have id attributes - use .val() instead of attr('id') to get the value
Update
You are now setting up an event handler on the click of an anchor ... change this
function deleteData() {
var artistIds = [];
$('#ajaxCheckbox').click(function () {
$("input[name='artist[]']:checked").each(function () {
artistIds.push($(this).attr('value'));
});
alert(artistIds);
});​​
to this
function deleteData() {
var artistIds = [];
$("input[name='artist[]']:checked").each(function () {
artistIds.push($(this).val());
});
alert(artistIds);
the deleteData function is already called onclick
Use the :checked selector instead of [#checked] (btw, you do not use # in CSS property selectors). You also used the wrong property selector for the name. I've also simplified your code a bit; your use-case is perfect to use .map(..).get()
var artistIDs = $("input[name='artist[]']:checked").map(function(){
return this.id;
}).get();
Demo: http://jsfiddle.net/ThiefMaster/sBmdC/
Try below line of code:
var artistIds = Array();
$("input[name=artist[]]:checked").each(function(index){
artistIds[index] = $(this).val();
});
This may work for you..

Jquery not considering new div that is added by Jquery + php + jquery

I have a php page where I add and delete items from database using Jquery + PHP + AJAX.
Now I am able to delete and add when that page loads for the first time.
Now if I first add an element; which in turn adds record to the DB and then updates the div that contains all the listing of divs.
Example:
<div id="all_items">
<div id= "item_1">
<a id="delete_link">...</a>
</div>
<div id= "item_2">
<a id="delete_link">...</a>
</div>
.... Upto Item n
</div>
Now I replace the div with id all_items.
Now I have jQuery at the bottom of the page which calls ajax on a tag of delete_link.
Situtation is:
When page is loaded I can delete any item from the list.
But if I page load i add new item first. (which will update all_items div) after that if I try to click on delete link. Jquery on click selector event is not fired and which in turn doesn't do delete ajax operation.
I couldn't figure out why this is happening.
Looking for some help here.
EDITED:
Sorry for not writing code earliar.
Following is the jQuery I am talking about.
<script type="text/javascript" >
var jQ = jQuery.noConflict();
jQ(function() {
jQ("#submit_store").click(function() {
var store_name = jQ("#store_name").val();
var dataString = 'store_name='+ store_name;
dataString += '&mode=insert';
if(store_name =='')
{
alert("Please Enter store Name");
}
else {
jQ.ajax({
type: "POST",
url: "<?php echo $mycom_url; ?>/store_insert.php",
data: dataString,
cache: false,
success: function(html){
jQ("#dvstoreslists").html(html);
document.getElementById('store_name').value='';
document.getElementById('store_name').focus();
}
});
}
return false;
});
jQ(".store_delete").click(function() {
var store_id = jQ(this).attr('id');
var id = store_id.split("_");
var dataString = 'store_id='+ id[2];
dataString += '&mode=delete';
var to_delete = "#store_list_" + id[2]
jQ.ajax({
type: "POST",
url: "<?php echo $mycom_url; ?>/store_insert.php",
data: dataString,
cache: false,
success: function(html){
jQ(to_delete).hide("slow");
}
});
return false;
});
});
</script>
So If on page load, I delete then delete on click jquery event is fired. But after adding new store and replacing div of stores with new div. then jQuery on click event is not fired.
My HTML is as below.
<div class="sbBox stores">
<form id="add_storefrm" name="add_storefrm" method="post" action="" >
<div class="dvAddStore">
<div class="dvName" id="store_list">
<input type="text" id="store_name" name="store_name">
<input type="hidden" value="addstore" id="mode" name="mode">
</div>
<div class="btnAddStore">
<input type="submit" name="submit_store" value="Add Store" id="submit_store">
</div>
</div>
<div id="dvstoreslists">
<?php
$query = "SELECT * FROM #__shoppingstore order by store_id desc;";
$db->setQuery($query);
$rows = $db->loadObjectList();
foreach($rows as $row)
{
echo "<div class=dvlist id=store_list_".$row->store_id ."><div class=dvStoreListLeft>";
echo "<div class='slname'><h3>" . $row->store_name . "</h3></div>";
?>
<div class="slDelBtn">
<p id = "p_store_<?php echo $row->store_id ; ?>">
<a id="store_delete_<?php echo $row->store_id ; ?>" class="store_delete" alt="Delete" onclick="DeleteStore(<?php echo $row->store_id ; ?>);" >
</a>
</p>
</div>
</div>
</div>
<?php } ?>
</div>
</form>
</div>
Sorry folks for not posting the code earliar.
the ID should always be unique so use class instead
in your case : <a id="delete_link">...</a> to <a class="delete_link">...</a>
When you replace the contents of #all_items any event handlers that were bound to any descendants will no longer exist. You can use event delegation, using the on method, to solve this:
$("#all_items").on("click", ".delete_link", function() {
//Do stuff
});
Notice that I'm using a class selector (.delete_link) instead of an ID selector for the links. It's invalid to have duplicate IDs in the same document.
Also note that the above will only work if you are using jQuery 1.7 or above. For older versions, use delegate instead:
$("#all_items").on(".delete_link", "click", function() {
//Do stuff
});
This works because DOM events bubble up the tree from their target. So a click on a link which is a descendant of #all_items will bubble up through all of its ancestors and can be captured when it reached #all_items.
use live() instead of .bind()
It seems you are trying to delete dynamically added delete_link so i think you should use
$('id or class').on(click,function(){});

Finding id of elements

i have this bit of html.
(Link at bottom)
Its output of php code for status updates, it has view comments and post comment link, the post comment link uses jquery to add a textarea and submit button below that status update. and the view comments shows the comments to that status update below that status update.
So i use php looping so there will be obviously more than 1 status updates at most times(depends on how much friends users have) so i cant have an element like 'textelement', i will need to have elements like 'textelement1' and 'textelement2'
So i used php to add the id of the status update in the end of the links like _id so the element id becomes view_comments_1.
So i want to use jquery to find out which element has been clicked so that i can add a text box and show comments below the right status update instead of showing it below all status updates.
HTML
<div class="wrapbg">
<span class="corners-top"><span></span></span>
<div id="content"><br/>
Whats new?
<hr class='hr1'>
<div class='stbody' id='stbody'>
<div class='stimg'>
<img src='uploads/profile_pics_small/Anonymous_Blueprint_Wallpaper_by_co.jpg' /></img>
</div>
<div class='sttext'>
Welcome yoall!!
<div class='sttime'>By LUcase</div>
<br><br>
<a href=''>0 Likes</a> <a href=''>1 Dislikes</a>
</div>
<a href=''>unDislike</a> <a id='comment_now_1' href=''>Comment</a> <a id='view_comments1' data-id-1 = '1' href=''>View comments</a> <div id='emptydiv1'> </div></div>
<div class='stbody' id='stbody'>
<div class='stimg'>
<img src='uploads/profile_pics_small/wood_texture_by_pabloalvin-d1igijr.jpg' /></img>
</div>
<div class='sttext'>
hi
<div class='sttime'>By nicknick</div>
<br><br>
<a href=''>0 Likes</a> <a href=''>0 Dislikes</a>
</div>
<a href=''>Like</a> <a href=''>DisLike</a> <a id='comment_now_4' href=''>Comment</a> <a id='view_comments4' data-id-4 = '4' href=''>View comments</a> <div id='emptydiv4'> </div></div></div>
<span class="corners-bottom"><span></span></span>
</div>
JavaScript
//Gotta find out which status update we are dealing with!
jQuery("document").ready(function(){
jQuery(".likebtn").click(function(e) {
var id=jQuery(this).attr("data-id");
jQuery.post('like.php', {'id': id}, function(data) {
alert("Your like.php has been called");
}, "json");
e.preventDefault();
});
jQuery(".dislikebtn").click(function(e) {
});
//gotta figure out which status update we are dealing with!
//attache the click event to the anchor tag
$("#comment_now").live("click",function(e){
//prevent the default behaviour of following the link
e.preventDefault();
$("#comment_now").remove();
//find the textarea element, and after it, put an input tag
$(".sttext").after('<textarea id="comment_text" name="comment"></textarea> <br> <button id = "post_button" class="action greenbtn"><span class="label">Comment</span></button> <a id="cancel_comment" href="">Cancel</a> <br id="com_spacing">');
});
//gotta figure out which status update we are dealing with!
$("#cancel_comment").live("click",function(event){
event.preventDefault();
$("#comment_text").remove();
$("#cancel_comment").remove();
$("#post_button").remove();
$("#com_spacing").remove();
$("#view_comments").before('Comment ');
});
$("#view_comments").live("click", function(e){
e.preventDefault();
var id=jQuery(this).attr("data-id");
$.ajax({
url: 'query_comments.php?status_id='+id,
beforeSend: function( xhr ) {
xhr.overrideMimeType( 'text/plain; charset=UTF-8' );
},
success: function( data ) {
$('#emptydiv').html(data);
}
});
});
});
Please help me out :)
You know that html forms can send arrays, right?
<input type="text" name="textelement[]" value="First Element" /><br/>
<input type="text" name="textelement[]" value="Second Element" /><br/>
PHP Code:
foreach($_POST['textelement'] as $somethingSomething){
echo $somethingSomething, "\n";
}
Prints out:
First Element
Second Element
add a class to to action buttons and pass the comment id as data attribute like so:
<a class="commentBtn" href='' data-commentid="1">Comment</a>
and than you can read out the id easily with jquery:
$(".commentBtn").live("click",function(e){
var id = $(this).data('commentid');
e.preventDefault();
// do something with id…
});

Categories