I'm creating web page that fetch values from database, there are several values will be display. On each value, it will have textarea and button Tweet below. I want when user click on button tweet, it will catch the value from textarea above that button. For now, it will catch only the value from the first textarea when user click on button Tweet (all buttons).
Here is my code
PHP
while($row=mysql_fetch_array($sql)){
echo "<textarea style='margin-bottom:10px;' id='text_tweet' name='text_tweet'
cols='61' rows='5'></textarea>";
echo "<a style='text-decoration: none; color: #000000;' id='tweet'
href='#'>Tweet</a>";
}
Javascript
$("#tweet").bind('click', function(){
var text_tweet = $("#text_tweet").val();
if(text_tweet==""){
alert("Please fill out something");
}
else{
save_tweet(text_tweet);
}
});
Can anyone help me to solve this problem?
Thank in advance.
You need to distinguish between each row that is being looped out. Here's an alternate approach assuming that $row has an id.
PHP
while ($row = mysql_fetch_array($sql)) {
echo "<textarea style='margin-bottom:10px;' id='text_tweet_" . $row['id'] . "' name='text_tweet_" . $row['id'] . "' cols='61' rows='5'></textarea>";
echo "<a onclick='doSomething(" . $row['id'] . ")' style='text-decoration: none; color: #000000;' id='tweet_" . $row['id'] . "' href='#'>Tweet</a>";
}
JS
function doSomething(id) {
var text_tweet = $("#text_tweet_" + id).val();
if (text_tweet == "") {
alert("Please fill out something");
} else {
save_tweet(text_tweet);
}
}
First off, if you're going to try and grab more than one element on a page, you can't use id as that's reserved for single elements - you should never have more than one element with the same id
First, I would change it so that each element has a class called 'tweet' on it. You will also need to add the jQuery $(function(){}) around it. That function tells the browser not to run that JavaScript until the page and all elements have completely loaded.
I would also make sure to add a container around both the elements, this will make it easier for you to actually grab the textarea that is beside the the link.
Here's how I would handle it:
while($row=mysql_fetch_array($sql)){
echo "<div>";
echo "<textarea style='margin-bottom:10px;' id='text_tweet' name='text_tweet'
cols='61' rows='5'></textarea>";
echo "<a style='text-decoration: none; color: #000000;' class='tweet'
href='#'>Tweet</a>";
echo "</div>";
}
And then the javascript:
$(function() {
$(".tweet").bind('click', function(){
var text_tweet = $(this).parents('div:first').find("textarea").val();
if(text_tweet==""){
alert("Please fill out something");
}
else{
save_tweet(text_tweet);
}
});
});
The reason we do $(this).parents('div:first').find("textarea").val() is because we want to grab the textarea within that containing div only; otherwise, jQuery will grab the first textarea value in the array.
Related
I think I really dug myself a hole here. I have a php file that creates a "notification list" with checkboxes. I want it to work in a way so the user will check the notification he read (in order to clean up his/her list), then the form will submit- by checking, and the 'notification' table in the database will be updated. My problem: it works, but it submits to the notification.php file. I don't want that.
I read several ways to solve it with AJAX but they require the checkboxes id's and as you can see below, The id's are being created by the php...
echo "<form name='noteform' id='noteform' action='notifications.php' method='POST'>";
echo "<ul>";
while($row = mysqli_fetch_array($result)) {
if ($row['type'] == 'group_request') {
echo "<li><input type='checkbox' name='check[]' value='" . $row['id'] . "' onclick='document.noteform.submit()' /><p1>" . $row['text'] . " | Approve? </li>";
}else{
echo "<li><input type='checkbox' name='check[]' value='" . $row['id'] . "' /><p1>" . $row['text'] . "</p1></li>";
}
}
echo "</ul>";
echo "</form>";
$check = isset($_POST['check']) ? $_POST['check'] : array();
foreach($check as $ch) {
$result = mysqli_query($conn, "UPDATE notifications SET `read`=1 WHERE id='$ch'");
}
?>
ps. The if($row['type'] == 'group_request') is just because that's the only notification type i made so far...
You don't have to by any means, but it would make your life a lot easier IMO. Here is a quick solution using jQuery:
$('#noteform').on('submit', function(event){
// Validate or whatever
// Submit
$.ajax({
'type': 'post',
'data': $(this).serialize(),
'url': 'path-to-notification.php',
'timeout': 50000
}).done(function(response) {
// success
}).fail(function(error) {
// error
});
event.preventDefault();
});
EDIT
Let's say you have "index.php", and within that file you have your form:
index.php
<?php
....
<form>
....
</form>
....
?>
Then either in and external .js file, or within index.php inside of a <script> tag, you would have the ajax method(s) above.
Next, you would have notification.php that would handle your form action(s).
notifications.php
if(isset($_POST['check'])
{
// check the value
// handle the form element
}
// sanitize the data
// run your update query
// return success/fail to the javascript
?>
In a nutshell, that's how I would set things up. Hope that helps!
I have a table with many auto generated forms (there could literally be hundreds of forms). The code for that is php based and looks like this:
$cellPosition = 0;
$rowCounter = 1;
$infoCounter = 1;
for ($x=0;$x <= count($assetName);$x++)
{
for ($i=0;$i < count($currentJobs);$i++)
{
$rowCounter= 1;
if ($currentJobs[$i][0] == $table->getCellContents(0,$x))
{
for ($y =0; $y < $currentJobs[$i][10];$y++)
{
$rowCounter++;
}
$table->setCellAttributes ($rowCounter,$cellPosition,"id='jobCell' bgcolor = ". $currentJobs[$i][4]. " rowspan=" . $currentJobs[$i][9]);
$table->setCellContents($rowCounter++,$cellPosition,
"<form id='scheduleForm".$infoCounter++."' method='POST' action='../forms/updateJobForm.php'>".
"<input type='hidden' name='jobInfo' value='" . $currentJobs[$i][1] . "'/>" . " " . "Job# (".$currentJobs[$i][2] . ")<br>" . $currentJobs[$i][3] .
"</form>");
}
else
{
$rowCounter = 1;
}
}
$cellPosition++;
}
echo $table->display();
I have the jobCell (a td element) bound to the following javascript/jquery code:
<script>
$(document).ready(function()
{
$("#jobCell").click(function()
{
$(this).children('form').submit();
//$('#scheduleForm').submit();
});
});
</script>
I each jobcell is click-able and I previously had it to where clicking anyone would submit the form. The problem is that it would only send the information for the hidden information for the last jobcell in the table. Now with my current code, it only allows the user to click the first cell and it does submit. How accomplish submitting the hidden data in the jobcell that is clicked when I have many forms?
There should only ever be one of each ID on the page. You have you have lots of forms all with the same ID it may well only submit the last. Change id to class, there can be any elements on the same page with the same class.
At a guess something like this. But without seeing your actual HTML output this could be wrong.
<script>
$(document).ready(function()
{
$("#jobCell").click(function()
{
$(this).children('form').submit();
//$('.scheduleForm').submit();
});
});
</script>
Check that id='jobCell' is only set once.
I would expect the code to look more like the form id code:
id='scheduleForm".$infoCounter++."'
Basically by clicking the "comment" link the last result of the query should show and by clicking again it should be hidden. I have tried Rocket's code as well but I get an error message in the bottom of the browser and when I click "comments" it just takes me to the top of the page. I would apprieciate some advice on this
$i = 1; // ID Counter
while($row = mysql_fetch_array($result))
{
echo "<h1>$row[title]</h1>";
echo "<p class ='second'>$row[blog_content]</p> ";
echo "<p class='meta'>Posted by .... • $row[date] • Comments<div id='something$i' style='display: none;'>$row[comment]</div>";
$i++; // Increment counter
}
This is a loop, echoing the same thing over and over, thus making all the divs have the same ID, something2.
IDs need to be unique, you gonna have to make unique IDs for each div.
Something like: <div id='something$i' style='display: none;'> (remembering to increment $i).
Also, you're gonna to escape the quotes in your onclick attribute.
<a href='#' onclick=\"toggle_visibility('something$i');\">
The code should look something like this:
$i = 1; // ID Counter
while($row = mysql_fetch_array($result))
{
echo "<h1>$row[title]</h1>";
echo "<p class ='second'>$row[blog_content]</p> ";
echo "<p class='meta'>Posted by .... • $row[date] • Comments<div id='something$i' style='display: none;'>$row[comment]</div>";
$i++; // Increment counter
}
Escape the quotes :
$blah = "onclick='toggle_visibility(\"something2\");'>Comments</a>"
There is an easier way to hiding / showing the next sibling ....
try this
<div style="display:none">some hidden content</div>
function toggle(el,ev) {
ev.preventDefault(); // prevent the link from being followed
el = next(el); // get the next element
if (el.style.display == "none") { // toggle the display
el.style.display = "block";
} else {
el.style.display = "none";
}
}
/*
Credit to John Resig for this function
taken from Pro JavaScript techniques
*/
function next(elem) {
do {
elem = elem.nextSibling;
} while (elem && elem.nodeType != 1);
return elem;
}
Working example
You can throw in a counter into your code as the while loop is executing to dynamically generate unique id's for each comment div. Or, you can pull a unique field out of the query result for the id's, as long as you hook up to it appropriately later if it ends up being used and remain consistent in the rest of the code.
either
$count = count($result);
...
while (...){
$count--;
echo '... id="something'. $count .'" ...'
}
or...
while (...){
echo '... id="something'. $row['ID'] .'" ...'
}
hey guys, im having some trouble...
i'm able to capture the first button on the page, but there are a total of 10 buttons. When I click on any of those 10 buttons, only the first button's value is called and the other ones don't update. is there a way to capture all of the buttons so they each have their own independent value and update their values so jQuery's ajax function gets the new one? the buttons are being created out of a multidimensional array loop.
<?php
$characters = $char->getCharactersListFromAccountId($_SESSION['acctid']);
foreach ($characters as $key) {
if(is_array($key)){
echo "<input class=\"button\" type=\"button\" href=\"javascript:void(0)\" value=\"Show\" style=\"vertical-align: top\" />";
echo $char->getFaction($key['guid']), " ";
echo $char->getClass($key['guid']), " ";
echo "<span class='style'>", $char->getLevel($key['guid']), "</span> ";
echo "<span class='style'>", $key['name'], "</span>";
echo "<input class=\"GUID\" type=\"hidden\" name=\"GUID\" value=\"";
echo $key['name'];
echo "\" />";
echo "<br>";
} else {
echo "<br>";
echo "<b><h1>My Characters: $key</h1></b><br />\n";
}
}
?>
<div id="view" style="display: none;"></div>
<script>
$(".button").livequery('click', function(event) {
var GUID = $('.GUID').val();
$("#view").html('Retrieving...');
$("#view").show("slow");
$.ajax({
type: "POST",
data: "ID=" + GUID,
url: "character.php",
success: function(msg){
$("#view").html(msg);
}
});
});
</script>
From what I can gather, the issue you are facing is that you need to send only the GUID which belongs to the clicked button - i.e. the next one in the document. If I'm correct, you can try this:
$(".button").livequery('click', function(event) {
// get the next GUID value
var GUID = $(this).nextAll('.GUID:first').val();
...
Also, is there any real need to use livequery for that?
a PHP table populates its data from mysql, When a user clicks .button a drop down table row menu appears where user has ability to add item to cart, the name of the item in cart should be the mysql entry $sound['downloadlink'] located in the table row above .mp3buy, It is adding the actual string "$sound['downloadlink']" instead of what the mysql entry for download link should be.
PHP Table
<?php
while($sound=mysql_fetch_assoc($records)){
echo "<tr class='adder'>";
echo "<td width='40' class='player'> <a href='beats/".$sound['downloadlink']."' class='sm2_button'>Play/</a></td>";
echo '<td width="250" class="name">'.$sound['name'].' <span class="red date">'.$sound['date'].'</span></td>';
echo "<td width='88' class='bpm'>".$sound['bpm']." B.P.M.</td>";
echo "<td width='72' class='length'>".$sound['length']."</td>";
echo "<td width='275' class='keywords'>".$sound['keywords']."</td>";
echo "<td width='96' class='buy'><img class='button' src='99cents.png'/></td>";
echo "</tr>";
}
?>
Jquery:
$('#mytable').on('click', ".button", function () {
var thisRow = $(this).parents('tr.adder');
var hasNextRow = thisRow.next('tr.added').length;
if (hasNextRow) {
thisRow.next('tr.added').remove();
} else {
$(this).parents('tr.adder').after('<tr class="added"><td height="100" colspan="6" ><img class="mp3buy" data-product-id=$sound["downloadlink"] src="mp31.png"/></td></tr>');
}
});
$('#mytable').on('click', ".mp3buy", function () {
var flag = $(this).data('flag');
simpleCart.add({
name : $(this).attr("data-product-id"),
price : .99,
quantity : (flag ? -1 : 1)
});
$(this).attr("src", flag ? "mp31.png" : "mp32.png");
$(this).data('flag', !flag);
});
Firstly, your PHP in your jQuery block is not getting parsed as you need to write <?= $sound["downloadlink"] ?> (PHP 5.4 syntax).
However, that's not your solution as you want the correct link for the product, not one fixed value. You could change your button so that it knows the link, as follows:
<img class='button' src='99cents.png' data-link='".$sound["downloadlink"]."'/>
Then you need to make quite a few jQuery changes:
$('.button').on('click', function () {
var thisRow = $(this).parents('tr.adder');
var hasNextRow = thisRow.next('tr.added').length;
if (hasNextRow) {
thisRow.next('tr.added').remove();
} else {
$(this).parents('tr.adder').after(
'<tr class="added"><td height="100" colspan="6" ><img class="mp3buy" data-product-id="'
+ $(this).data('link')
+ '" src="mp31.png"/></td></tr>'
);
}
});
$('#mytable').on('click', ".mp3buy", function () {
var flag = $(this).data('flag');
simpleCart.add({
name : $(this).data("product-id"),
price : .99,
quantity : (flag ? -1 : 1)
});
$(this).attr("src", flag ? "mp31.png" : "mp32.png");
$(this).data('flag', !flag);
});
That's roughly right but I might have missed something. The idea is that you keep your data in your HTML then use your script to manipulate the data. Don't put your data in your script. Also, it doesn't really make sense to transfer the value of the data-downloadlink attribute over to a data-product-id attribute. It would be better to refer to the original value.