I have a view of teasers in Drupal. Each teaser has a click() handler which is supposed to send its node id as an argument to load a view via ajax. I've tried 2 different jquery approaches, but am having no luck.
The first example sends the nid for only the last node in the view. So that no matter what teaser I click only the nid for the last teaser gets sent.
Drupal.behaviors.ajaxview = function(context) {
$(".ajaxclick").click(function(){
$(".container").load(Drupal.settings.basePath + "myajax/" + <?php echo $node->nid;?>;);
});
}
In the second approach, a click on a button of class "ajaxview" will send the correct nid but but instead of sending for just the one clicked button to it's corresponding div, it will send a nid for EACH button with a class of "ajaxview" into EACH div with a class of "container". So I end up with the contents of every single view generated from every single teaser into every single div. WAAAAY too much!
$(document).ready(function() {
$(".ajaxclick").click(function(){
$(".container").load(Drupal.settings.basePath + "myajax/" + <?php echo $node->nid; ?>);
});
});
Here is the button;
<button class="ajaxclick">click</button>
And the div:
<div class="container"></div>
Any idea how I can get each click to send the nid of that teaser clicked upon as the argument and load only that view?
Your code is javascript.
You can't use:
<?php echo $node->nid; ?>
You will have to use jQuery approach to get the nid you want.
For example, if you have the nid in a hidden filed like:
<input type="hidden" id="ID" value="100" />
You can use the following jQuery to get the nid:
var nid = $("#ID").val();
Turns out I was able to get it working using a revision of Ionut.A's suggestion;
Drupal.behaviors.ajaxview = function(context) {
$(".ajaxclick").click(function(){
var nid = $(".mynid").eq($('.ajaxclick').index( $(this) )).val();
$('.container').eq($('.ajaxclick').index( $(this) )).load(Drupal.settings.basePath + 'myajax/' + nid);
return false;
});
}
and for the html;
<input type="hidden" class="mynid" value=<?php echo $node->nid;?> />
I had to use class instead of id as the id would only return the id from the first node.
Related
I want to get the value of id so that I can delete the data from mysql based on the id number
This is a project for events, the main idea here is I want to get the id number of the event based on the clicked button, so that I can update/delete the event based on the id number.
Code for displaying details
<?php $sql= "SELECT event_name, event_date, event_id FROM events WHERE event_status=0";
$result= mysqli_query($conn, $sql);?>
while($row = mysqli_fetch_assoc($result))
{
echo '
<div class="pending-card">
<div class="pending-image">
</div>';
echo " <div class='pending-title'>
<h1>{$row["event_name"]}</h1>
</div>";
echo " <div class='pending-des'>
<p>{$row["event_date"]}</p>
<button class='choice-pending'><a href='detail.php'>Read More...</a></button>
<input style='display: none;' type='text' id='test-pend' value='{$row["event_id"]}'>
</div>
</div>
";
}
Jquery code
Here I tried to check if this works by making an alert, but after i press the button, the id number that came out is not correspond with the button i click
$(document).ready(function(){
$('.choice-pending').click(function(){
alert("Value: " + $('#test-pend').val());
});
});
Can anyone tell me where did I go wrong
Example, the event i pressed is suppose to be 34, but the alert shows 26 which is the first event id in the code for displaying details
You can use data-* attribute in your element.
Based on https://www.w3schools.com/tags/att_global_data.asp
The data-* attributes is used to store custom data private to the page
or application.
The data-* attributes gives us the ability to embed custom data
attributes on all HTML elements.
The stored (custom) data can then be used in the page's JavaScript to
create a more engaging user experience (without any Ajax calls or
server-side database queries).
The data-* attributes consist of two parts:
The attribute name should not contain any uppercase letters, and must
be at least one character long after the prefix "data-" The attribute
value can be any string Note: Custom attributes prefixed with "data-"
will be completely ignored by the user agent.
<button class="choice-pending" data-event-id="<?= $row['event_id']; ?>">Read More...</button>
Then in your script you can access the clicked button:
$(".choice-pending").click(function() {
if($(this).attr('data-event-id') !== undefined) {
// You can do ajax call here to your detail.php
// Or you can simply create a hidden field inside your form, assigned the data-event-id value to it, then $("form").submit();
} else {
/** Error message here, maybe? */
}
});
First remove your anchor tag inside button and use only anchor or button and print your html with assign some dynamic class or id into each to make them unique like this.
<div class='pending-des'>
<p>{$row["event_date"]}</p>
<a class='choice-pending-{$row["event_id"]}' href='detail.php'>Read More...</a>
<input style='display: none;' type='text' id='test-pend-{$row["event_id"]}' value='{$row["event_id"]}'>
</div>
Now bind click event on it-
$(document).ready(function(){
$('.pending-des').each(function(){
$(this).on('click', 'a[class^=choice-pending-]', function(){
alert($(this).find('input[id^=test-pend-]').val());
});
});
});
I built a for each loop that pulls back several rows from the database. Each row it pulls has a link, and a hidden input box with a value of posting_id. This link will work similar to a like button on facebook in a way. The hidden input box just stores the posting_id. When you click the "like" link, it sends over the posting_id to a jQuery page and pings back a page called community to tell it the user has "liked" the post.
Here's the problem
I'm pulling several rows, and it seems that only the top row being pulled is actually sending the data to the jQuery page when you click the "like" button. If I click on any other "like" button other than the top one it will not work at all.
Jquery Page
$('.bump_link').click(function(){
var posting_id = $('.posting_id').val();
$.post("community.php", {
posting_id: posting_id
});
alert(posting_id);
$(this).toggleClass("bumped");
});
Foreach Loop
foreach ($result as $value) {
$group_postings .= '
<input type="text" class="posting_id" value="'.$value['posting_id'].'">
<div id="bump_icon" class="bump_link"></div>
<span id="counter"></span>
';
}
I hope I've made the issue clear, it was and is difficult to explain.
The problem is you are using a class to get the posting_id, since all the hidden fields have the same class only the first elements value is passed no matter what button you click.
i recommend using this html, without the hidden input, pass the value as a data attribute
<div id="bump_icon" class="bump_link" data-postid="'.$value['posting_id'].'">
and in this js, get the posting id from the data attribute
$('.bump_link').click(function(){
var posting_id = $(this).data('postid'); // get the posting id from data attribute
$.post("community.php", {
posting_id: posting_id
});
alert(posting_id);
$(this).toggleClass("bumped");
});
You are calling val() on selector you might return more then one elements, but val() will give you the value of one (first) element only. You can use map() to get all values of input having class posting_id
var posting_id_values = $('.posting_id').map(function(){
return this.value;
}).get().join(',');
Your problem is this line:
var posting_id = $('.posting_id').val();
This will return the first posting_id value every time, not the one associated with the bump_link you are clicking on.
There are lots of ways to solve this. One way is to use .prev() to select the previous element:
var posting_id = $(this).prev('.posting_id').val();
this selects the previous posting_id element from the current div. This relies on the fact that the posting_id element is before the associated bump_link div.
If you want to send just the posting_id of the clicked button, you could change your PHP/HTML code like this:
foreach ($result as $value) {
$group_postings .= '
<div id="bump_icon" class="bump_link">
<input type="text" class="posting_id" value="'.$value['posting_id'].'">
</div>
<span id="counter"></span>
';
}
And your JS code like this:
$('.bump_link').click(function(){
var posting_id = $(this).find('.posting_id').val();
$.post("community.php", {
posting_id: posting_id
});
alert(posting_id);
$(this).toggleClass("bumped");
});
use on delegated event since you are adding the content dynamically and
$(this).prev('.posting_id') // to get the posting data value
$(document).on('click','.bump_link',function(){
var posting_id = $(this).prev('.posting_id').val(); //<-- use $(this) reference
$.post("community.php", {
posting_id: posting_id
});
alert(posting_id);
$(this).toggleClass("bumped");
});
I have a web page that lists a number of companies from a MYSQL database, the listing just shows the name of the company. When user clicks on the company name a jquery accordion slider shows the rest of the information about that company.
When company name is clicked it also sends a request to a php script to log that a person has viewed that company's details.
My Problem
I want to send the ID for each record to the php script.
I have achieved this by including the accordion jquery code within the while loop that reads the output of the mysql query, but it generates a lot of unnecessary source code (i.e. for each company listed).
I need to include the jquery accordion code outside of the while statement.
How do I pass the id of each database record (i.e. company name) to the $.post in the jquery code, when it is outside of the while loop?
Accordion Jquery code
$(document).ready(function() { $('div.listing> div').hide(); $('div.listing> h4').click(function() {
$.post("/record.php", { id: "<?php echo $LM_row02[id]; ?>" } )
var $nextDiv = $(this).next();
var $visibleSiblings = $nextDiv.siblings('div:visible');
if ($visibleSiblings.length ) {
$visibleSiblings.slideUp('fast', function() {
$nextDiv.slideToggle('fast');
});
} else {
$nextDiv.slideToggle('fast');
} }); });
Any idea most welcome.
When you create the HTML (I assume you do that in the loop as well), add a data-* attribute with the ID as value to the element and read that value with jQuery when the element is clicked on.
E.g. your resulting HTML will look like:
<h4 data-id="123">Some title</h4>
and your JavaScript:
$('div.listing > h4').click(function() {
$.post("/record.php", { id: $(this).attr('data-id') }, function() {
// ...
});
});
When you create the h4 element in html add a html5 data attribute like
<h4 data-companyid="<?php echo $LM_row02[id]; ?>">Company Name</h4>
Then use that companyid in your ajax call like
$.post("/record.php", { id: $(this).data('companyid') } );
I have been a really big fan of stackoverflow(which led me to ask the question here and not anywhere else), anyway, without further ado...
While creating a shop system, I planned to implement an ajax which buys the item on the fly. Now This is how the loop for retrieving items looks like:
<?php
$shop_query = mysql_query("SELECT * FROM sector0_item WHERE 1");
$numrows = mysql_num_rows($shop_query);
While ($shop_fetch = mysql_fetch_array($shop_query)){
?>
<div id="shop_main">
<div class = 'item_img'>
<a><img src = "http://images.wikia.com/dofus/images/4/4e/Discovery_Potion.png" height = '100px'/></a>
</div>
<div class="item_buy">
<a><center>Price: <?php echo number_format($shop_fetch['item_price']);?></center><br /></a>
<a>Quantity: <input type = 'text' size = '9' id = 'itemquantity'/><br /></a>
<a><p>Point requirement: <?php echo number_format($shop_fetch['item_pt_req']);?></p></a>
<a><input type = 'button' id = 'buy' value = 'buy'/></a><span id = 'buy_status'></span>
</div>
<a><h3><?php echo $shop_fetch['item_name'];?></h3></a>
<a><p><?php echo $shop_fetch['item_desc'];?></p></a>
<a>Item Type: <font color = 'green'><?php echo $shop_fetch['item_class'];?></font></a>
</div>
<br />
<?php
}
?>
However, my ajax seems to act really weird. My implementation was to show a loading gif image.
Script:
<script type = 'text/javascript'>
$('#buy').click (function(){
var quantity = $('#itemquantity').val();
$('#buy_status').html('<img src = "http://www.antibodyresource.com/theme/js/ajax-loader.gif" height = 20px;/>');
});
</script>
The problem is, Only one button shows the circle when clicked. Does the position of the script cause this? Any help is appreciated.
You can only have one item with a given id. When you have multiple elements with the same id, it is indeterminate which one will be returned, but it will usually be the first item only.
If you want multiple buy buttons and want to assign them all the same jQuery event handler, then use a common class name instead of an id.
If you are loading content dynamically and you want event handlers to work for that content, then you need to use delegated event handling.
In jQuery, that is generally done with either .on() or .delegate(). The basic idea is that you pick a static parent object that is not dynamically loaded (perhaps the parent of show_main) and bind the event to that object and then pass the selector of the dynamic element like this (note, I've changed from an id to a class to identify the buy button):
$(staticParentSelector).on('click', '.buyButton', function() {
$(this).closest(".item_buy").find(".buy_status").html('<img src = "http://www.antibodyresource.com/theme/js/ajax-loader.gif" height = 20px;/>');
})
Two things:
It's hard to tell from the sample, but is there an iterator that creates a list of available items? If so, you shouldn't be using IDs which are meant to be unique. If there's really only one #buy then you're fine, though.
When content is updated with Ajax, you're going to lose bindings. Assuming the item related to the #buy button gets replaced with other items, you're better off with a delegated event:
// not in an inline script, but just once, ideally in your main JS file
$(document).ready(function() {
$('#wrapper').on('click', '#buy', (function(){
var quantity = $('#itemquantity').val();
$('#buy_status').html('<img src = "http://www.antibodyresource.com/theme/js/ajax-loader.gif" height = 20px;/>');
});
})
Where #wrapper is some ancestor higher up in the DOM tree that is never destroyed by the Ajax event.
id is unique value - on html page each id must have unique value. Use class instead.
You need to put your code inside $(document).ready(). So its:
$(document).ready( function() {
$('#buy').click( function(){
// do something here
});
});
Also, you may want to list to jfriend00's advice on IDs.
I have a page where ID is generated dynamically and be fetch from database and I put the result inside <a> tag :
<?php while($row = mysql_fetch_array($result))
{ ?>
ID Number 1<br />
ID Number 2
<?php } ?>
and when user click the link, the javascript myfunc() function will be trigger.
function myFunc(){
$("#div").load("get_id.php?","id="+"SHOW THE $row['id'] HERE"); }
But I don't know how to retrieve href value and put it inside the load() method. Can someone show me the correct way?
Thank you
-mike
Make sure that you generate a complete href attribute:
ID Number 1
and then attach a click handler unobtrusively (don't mix markup and javascript):
$(function() {
$('a').click(function() {
$('#div').load(this.href);
return false;
});
});