Call jQuery for each row - php

I want to make a link to call for each row.
Here is the code:
foreach($docs as $row) {
echo "<td><h5><a href='' id='onclick' class='onclickcalldocEdit_".$row->dId."'>".$row->dName."</a></h5></td>";
echo "<div id='response_proj' class='container_proj_".$row->dId."'>
/* container code here */
}
So, basically I create a container for each row and name differs only by id.
I've used this script to try to get it work:
$(document).ready(function(){
var className = $('#onclick').attr('class');
var contName = $('#response_proj').attr('class');
$(className).jqm({trigger:contName, toTop: true});
});
</script> ";
Is it even possible?

Try this:
$(document).ready(function(){
$("#onclick").each(function(){
var className = this.attr('class');
var contName = this.closest('td').next('#response_proj').attr('class');
$(className).jqm({trigger:contName, toTop: true })
})
})
Frankly speaking, I think the better way is to use data-id and class attributes(without id):
<a href='' class='onclick' data-id='".$row->dId."'>".$row->dName."</a>
And access id via
var id = $('.onclick').data('id');

Related

How to generate unique LIKES id in PHP

I have a button in my page:
if($posts = $q->fetchAll()) {
foreach ($posts as $post) {
$username = $post[0];
$post_id = $post[2];
$status = $post[1];
echo $username . " " . $status . "<br/>";
echo "<button value = '$post_id' id = 'like' class='like' type='submit'>Like</button>";
}
}
Let's assume I have ten result from the query, I will definitely have 10 LIKE button with the same ID.
Now my jQuery is coming this way:
$("#like").click(function() {
var menuId = $(this).val();
var request = $.ajax({
url: "likes.php",
type: "POST",
data: { id : menuId },
dataType: "html"
});
request.done(function( msg ) {
$(".likecount").html( msg );
});
});
Every click on a single button applies to all 10 buttons. How do I differentiate them and have the database affected accordingly?
First off, you're adding like elements via ajax, but you're binding the event handler to whichever like element is already part of the dom at any given moment:
$(document).ready(function()
{
//when dom is loaded, #like is selected, and event is bound
$('#like').click(function(){});
});
inside the click handler, you perform an ajax call that may add another like element to the page, but you never bind an event handler to that new element.
You have 2 options: add an event handler for each element that is added to the page dynamically (not so good, bad for performance). OR delegate the event. As an added bonus, you don't need the ID's of the like buttons anymore. You can use the like class to delegate!
$(document).ready(function()
{
$('body').on('click', '.like', function()
{
//handle click on like button here
});
});
This adds an event listener to the body tag, that will call the callback function whenever a click is registered on an element that has the like class.
I'll edit this response, to give you a, purely hypothetical way to ensure unique like id's
Using a closure, you can easily get unique ID's, by exploiting the fact that closure vars can outlive the closure function. But as you can see, just from the verbosity and added complexity of the code below, this approach is not to be recommended. Simply use the class, and leave the ID out. delegation all the way!
$('body').on('click', '.like', (function(count)
{//closure, pass like buttons currently on page
var idNum = 0;
count.each(function()
{
$(this).attr('id', $(this).attr('id') + idNum);
++idNum;//increment
});
return function()
{//this is the actual callback
request.done(function( msg )
{
var chunk = $(msg);//parse HTML response
chunk.find('.like').each(function()
{
$(this).attr('id', ($(this).attr('id') || 'like') + idNum);
++idNum;
});
});
};
}($('.like'))));
Or, if for some reason you don't want to delegate the event:
$('.like').on(function handler()
{//callback should be named, you'll see why
request.done(function( msg )
{
$('.like').off('click', handler);//remove handler
//add msg to DOM
$('.like').on('click', handler);//add handler, now including new DOM elements
});
});
You could (and IMO should) optimize this further, by storing the $.each callback in a closure reference, too:
$('body').on('click', '.like', (function(count)
{//closure, pass like buttons currently on page
var idNum = 0, eachCallback = function()
{
$(this).attr('id', ($(this).attr('id') || 'like') + idNum);
++idNum;//increment
};
count.each(eachCallback);
return function()
{//this is the actual callback
request.done(function( msg )
{
var chunk = $(msg);//parse HTML response
chunk.find('.like').each(eachCallback);
});
};
}($('.like'))));
This way, you avoid creating a callback function object on each click event... but read up on closures to fully understand why this is a better approach, performance wise.
Why not change your PHP to:
if($posts = $q->fetchAll()){
foreach ($posts as $post){
$username = $post[0];
$post_id = $post[2];
$status = $post[1];
echo $username . " " . $status . "<br/>";
echo "<button value = '$post_id' id = 'like_$post_id' class='like' type='submit'>Like</button>";
}
As each item relates to a post with a (I hope) unique ID, why not just append that value to the id property?
ID values MUST BE UNIQUE
Then you'll need to change your jQuery selector, how about:
$("button.like").click(function()
Don't use ID as selectors in your jquery, use class selector if your buttons are going to use the same class.
For example:
if($posts = $q->fetchAll()){
foreach ($posts as $post){
$username = $post[0];
$post_id = $post[2];
$status = $post[1];
echo $username . " " . $status . "<br/>";
// Removing Id like, because Id should be unique in DOM.
echo "<button value = '. $post_id. ' class='like' type='submit'>Like</button>";
}
}
Your jQuery will look like:
// class selector is a dot (.), if you use an id selector (hashtag #) and you
// you have more than 1 element with that Id, jQuery will only select the first one.
$('body').on('click', '.like', function(){
var menuId = $(this).val();
var request = $.ajax({
url: "likes.php",
type: "POST",
data: { id : menuId },
dataType: "html"
});
request.done(function( msg ) {
$(".likecount").html( msg );
});
});

Grabing a data attribute of a clicked element?

I have a link that opens a modal when clicked, however that element also has a data-id="#id here" attribute that I need to grab so I can pass it to my php script for processing. How can I accomplish this?
My JS code:
$(document).ready(function() {
$('#edit_general').click(editModal);
});
function editModal(event)
{
var modal = $('#editModal');
modal.modal({
show: true
});
}
My html:
<li><a id="edit_general" href="#editModal" data-uid="<?php echo $u->id; ?>">Edit General</a></li>
I tried using the this keyword but it didn't work.
How can I accomplish this?
Try this: Demo http://jsfiddle.net/szS2J/1/ or http://jsfiddle.net/ug7ze/
$(this).data('uid')
Hope it fits the cause :)
like this:
$('#edit_general').click(editModal);
$(this).data('uid')
full
$(document).ready(function() {
$('#edit_general').click(editModal);
});
function editModal(event) {
alert($(this).data('uid'));
var modal = $('#editModal');
modal.modal({
show: true
});
}​
You can get the value using the attr method: $(this).attr('data-uid')
Like this stored in data_id.
$(document).ready(function() {
$('#edit_general').click(function() {
var data_id = $(this).data('uid');
var modal = $('#editModal');
modal.modal({
show: true
});
});
});

Passing a PHP variable from a div tag to jquery when clicked

I have a requirement to get a variable from PHP to Javascript when clicked by the user. I have an array of data returned by a query and I need to pass an ID value for the element clicked so that I can populate an additional data set via the .load using another PHP page. I am unsure how todo this?
Javascript Code in Page:
<script type="text/javascript">
$(function () {
$("#pass_userid_div").click(function () {
$("#another_div").load('remote_pages/get_info.php?userid=' + $GET_THE_USERID_AND_PASS_HERE);
});
});
</script>
PHP Code in Page:
$query_str = "SELECT id, username, dateregistered FROM users";
$query = mysql_query($query_string) or die(mysql_error());
while ($results = mysql_fetch_array($query)) {
print "<div id='pass_userid_div'>{$results['username']}</div>";
print "<div>{$results['dateregistered']}</div>";
}
Why must it be a div? Use an interactive element:
PHP:
while ($results = mysql_fetch_array($query)) {
print "<button type='button' name='pass_userid_div' value='{$results['id']}'>{$results['username']}</button>";
print "<div>{$results['dateregistered']}</div>";
}
JavaScript:
<script type="text/javascript">
$(function () {
$("button[name='pass_userid_div']").click(function () {
$("#another_div").load('remote_pages/get_info.php?userid=' + $(this).val());
});
});
</script>
Update: If it really must be a div, use a data- attribute:
<div class="pass_userid_div" data-userid='{$results['id']}'…
…$(this).data("userid")
$("#another_div").load('remote_pages/get_info.php?userid=' + $GET_THE_USERID_AND_PASS_HERE, function(){
$("#another_div #pass_userid_div").each(function(){
var yourvar =$(this).text();
// use your var
})
});
Please not you should not use more then one div whith the same id. Use class instread

mixing php with jquery

I build a table up of cameras using php. So upon entry I have a query that pulls all the data I need (this is Joomla, hence the weird functions):
$query_camera_name = "SELECT camera_name, camera_status, camera_quality, email_notice, camera_hash, camera_type, camera_sensitivity, camera_user, camera_pass, camera_ip, camera_port FROM #__cameras WHERE user_id=".$user->id." AND camera_status!='DELETED'";
$db->setQuery($query_camera_name);
//get number of cameras so we can build the table accordingly
$db->query();
$num_rows = $db->getNumRows();
// We can use array names with loadAssocList.
$result_cameras = $db->loadAssocList();
I then look through to create a table with the data I need (this is abbreviated):
<?php
for($i=0;$i<$num_rows;$i++)
{
?>
...
<tbody>
<tr data-hash="<?php echo $result_cameras[$i]["camera_hash"]; ?>">
<td>
<?php echo $result_cameras[$i]["camera_type"]; ?>
</td>
<td>
<?php echo $result_cameras[$i]["camera_name"]; ?>
</td>
...
<td>
<button id="axis-details" onclick="apikey('<?php echo $result_cameras[$i]["camera_hash"]; ?>');">API Key</button>
</td>
...
<?php
}
?>
I'd like to create a jquery ui dialog with a textarea and a url filled in. The dialog is easy:
$(document).ready(function() {
var $dialog = $('<div></div>');
$dialog.append('Please copy this key for camera setup: ')
.append('<p><textarea id=\"textbox\">'+ENTER URL HERE+'</textarea></p>')
.append('<p>For more information see: setup</p>');
$dialog.dialog({
autoOpen: false,
title: 'API Key'
});
$('#axis-details').click(function(e) {
e.preventDefault();
$dialog.dialog('open');
});
});
The url is this:
"http://myhost.com/notify.php/" +'<?php echo $result_cameras[$i]["camera_hash"]; ?>';
The problem is how can I put that url in the jquery code (where it says "ENTER URL HERE")? I obviously can't use:
<?php echo $result_cameras[$i]["camera_hash"]; ?>
because that is only resolved in the PHP code where I loop to build an html table. Any suggestions are appreciated.
Foolowing will create dialog "on the fly"
First you have to use class instead of ID for your "axis_details" button. ID's must be unique in a page.
You aready have url in your data-has attribute in TR
$('.axis-details').click(function(e) {
e.preventDefault();
var url = $(this).closest('tr').data('hash');
var $dialog = $('<div></div>');
$dialog.append('Please copy this key for camera setup: ').append('<p><textarea id=\"textbox\">' + url + '</textarea></p>').append('<p>For more information see: setup</p>');
$dialog.dialog({
title: 'API Key',
close: function() {
$(this).remove();
}
});
})
....
<button class="axis-details" data-url="<?php echo $result_cameras[$i]["camera_hash"] ?>">API Key</button>
....
....
var $dialog = $('<div id="dialog-container"></div>');
$dialog.append('Please copy this key for camera setup: ')
.append('<p><textarea class="url-container"></textarea></p>')
.append('<p>For more information see: setup</p>');
....
....
$(".axis-details").on("click", function()
{
var url = $(this).data("url");
$("#dialog-container").find(".url-container").val(url);
$dialog.dialog('open');
});
if you didn't, you have to append the dialog div to the document (i'm not sure)
First in your PHP file:
echo '<input type="hidden" value="'.$result_cameras[$i]["camera_hash"].'" class="cameraHash" />';
Then you need to modify your jQuery code so the appends happen the way you intend.
$(document).ready(function() {
var $dialog = $('<div></div>');
$dialog.append('Please copy this key for camera setup: ');
//new code to count each instance found
var eachLink = $(".cameraHash").val();
$.each(eachLink, function(index,value){
$dialog.append('<p><textarea id=\"textbox-'+index+'\">http://myhost.com/notify.php/'+value+'</textarea></p>')
});
//end new code, but change the next .append to $dialog.append
$dialog.append('<p>For more information see: setup</p>');
$dialog.dialog({
autoOpen: false,
title: 'API Key'
});
The above function grabs each value of .cameraHash. It appends the same textarea (which I modified because the ID isn't unique in your post, so I used the 'index' of the links to represent the textbox. so that it's cohesive with the values) and inside of it uses the value of the cameraHash found at that specific index.

Deleting database records using jQuery AJAX is not working

I am trying to delete records from database without reloading the page. In the view file I have the following code. But when I click on the delete link nothing happens. Would you please kindly help me find out where I have done wrong?
Thanks in advance.
My view file:
<script type="text/javascript">
$(function(){ // added
$('a.delete').click(function(){
$.ajax({
var a_href = $('selector').attr('href');
type: "POST",
url: "<?php echo base_url(); ?>student_fee_status/payment_info_delete",
data: "id="+a_href,
success: function(html){
$("#show").html(html);
}
});
return false
});
}); // added
</script>
<?php if(count($records) > 0) { $i = 0; foreach ($records as $row){ $i++; ?>
<span> <?php echo $row['fee_type']; ?> : <?php echo $row['fee_amount']; ?> [<a id='<?php echo "$paymentid" ;?>'
class='delete' href='#'>Delete</a>]</span> <br>
<?php }} ?>
This is my Controller:
function payment_info_delete(){
$id = mysql_real_escape_string($_POST['id']);//Some clean up :)
$query= $this->db->delete('studentpayment2', array('pid' => $id));
echo "$id";
}
You need to put the 'var a_href...' line outside of the ajax function
You need to replace the word selector with this which refers to the currently clicked element.
var a_href = $(this).attr('href');
$.ajax({...
var a_href = $('selector').attr('href');
$.ajax({...
As mgraph pointed out in his answer, the var a_href = $('selector').attr('href'); line is incorrect. You want to replace 'selector' with this so that you're getting the href attribute from the anchor that was clicked on.
That said, I think that's still probably wrong - surely you want to be passing back the id of the entry to delete, which seems to be stored in the id attribute of the anchor tag, rather than always passing back a # symbol?
To pass the id back instead, rather than the href, replace this:
var a_href = $('selector').attr('href');
with this:
var a_href = this.id;

Categories