How to grab the required value input on click? - javascript

For example, there is such a JS-code:
function openAlbum() {
$("#tracks").html('Some text...');
var uid = $("#uid").val();
$.ajax({
type: "POST",
url: "s.php",
data: "uid="+uid,
success: function(html) {
$("#results").empty();
$("#results").append(html);
}
}); }
And this html/php-code that is displayed in a cycle:
for ($i = 0; $i < count($searchAlbum); $i++) {
echo '<div id="cover"><form action=""><input type="hidden" id="uid" value="'.str_replace('https://example.com/', '', $searchAlbum[$i]->href).'"/><img src="'.$searchAlbum[$i]->images[1]->url.'"/><br><br><span>'.$searchAlbum[$i]->name.'</span><input type="submit" style="position: absolute;;left: -99999px;" /></form></div>';
}
Problem: currently by clicking grabs only the first input value on the page with id="uid".
How do I put a JS var uid value from the div, which clicked a link?
P.S. Sorry for my bad english.

I'm going to change the way you kinda do this a bit...
<?php
for ($i = 0; $i < count($searchAlbum); $i++) {
?>
<div class="cover">
<form action="">
<input type="hidden" class="uid" value="<?php echo str_replace('https://example.com/', '', $searchAlbum[$i]->href); ?>"/>
<img src="<?php echo $searchAlbum[$i]->images[1]->url; ?>"/>
<span><?php echo $searchAlbum[$i]->name; ?></span>
<input type="submit" style="position: absolute;left: -99999px;" />
</form>
</div>';
<?php
}
?>
Script:
$(document).on('click','.cover img',openAlbum);
function openAlbum() {
$("#tracks").html('Some text...'); var uid = $(this).parent().find('.uid').val();
$.ajax({
type: "POST",
url: "s.php",
data: "uid="+uid,
success: function(html) {
//$("#results").empty();
//$("#results").append(html);
$("#results").html(html);
}
});
}
This should cover everything. I switched all ids to classes and changed how you execute your jQuery.

Thank you all for your help!
As a result, I will be able to solve the problem.
JS-code:
function openAlbum(uid)
{
$("#results").html('Some text...');
$.ajax({
type: "POST",
url: "s.php",
data: "uid="+uid,
success: function(html) {
$("#results").empty();
$("#results").append(html);
}
});
}
HTML-code:
for ($i = 0; $i < count($searchAlbum); $i++) {
?>
<div id="cover"><a href="#" onclick='openAlbum("<? echo $searchAlbum[$i]->id; ?>");'><img src="<? echo $searchAlbum[$i]->images[1]->url; ?>"/></a><br><br><span><? echo $searchAlbum[$i]->name; ?></span></div>
<?
}

Since id in HTML must be unique, it is taking only the first element's value. Make the ids unique or use class attribute as Cayce K has answered.

Related

How to load checked checkbox in ajax edit modal?

can you help me how to load checked checkbox in edit modal? I'm using checkbox to input multiple roles in my system. Everything was fine but I have problem in my edit modal. The checkbox was blank and not checked.
this is my ajax edit function:
function edit_function(task, id) {
$('#editModal').modal();
$.ajax({
method: 'POST',
url: '<?php echo base_url() . 'user/edit/' ?>' + id,
dataType: 'json',
success: function(x) {
if (resp.length > 0) {
for (var i = 0; i < resp.length; i++) {
id= x[i]['id'];
$("#editModalForm input[name=email]").val(x[i]['email']);
$('#editModalForm input[name=role_id]').prop('checked', true);
}
}
}
});
}
this is my checkbox in html form
<?php foreach ($roles as $row) : ?>
<div class="form-check-inline">
<label class="form-check-label">
<input type="checkbox" name="role_id[]" id="role_id[]"
value="<?php echo $row->role_id; ?>"><?php echo $row->role_id; ?>
</label>
</div>
<?php endforeach; ?>
this is my json result:
[{"id":288,"role_id":["2","3"],"email":"me#gmail.com"}]
function edit_function(task, id) {
$('#editModal').modal();
$.ajax({
method: 'POST',
url: '<?php echo base_url() . 'user/edit/' ?>' + id,
dataType: 'json',
success: function(x) {
if (resp.length > 0) {
for (var i = 0; i < resp.length; i++) {
id= x[i]['id'];
$("#editModalForm input[name=email]").val(x[i]['email']);
for (var r = 0; r < x[i]['role_id'].length; r++) {
var role=x[i]['role_id'][r];
$('#role_id_'+role).prop('checked', true);
}
}
}
}
});
}
<?php foreach ($roles as $row) : ?>
<div class="form-check-inline">
<label class="form-check-label">
<input type="checkbox" name="role_id[]" id="role_id_<?php echo $row->role_id ?" />
value="<?php echo $row->role_id; ?>"><?php echo $row->role_id; ?>
</label>
</div>
<?php endforeach; ?>

JS code working in chrome and IE, not in safari and firefox

I have the below js code that is working in chrome and IE but not safari and firefox. In both cases, the beforeSend: function works, but the success function does not work. Is this a problem with the CSS or am I missing something in the javascript?
---JS----
$("#updateBidButton").click(function () {
var bid_amount = document.getElementById("auction_bid_input").value;
var item_id = "<?php echo $this->item['id']?>";
var current_bid = "<?php echo $this->item['current_bid']?>";
var url_view = "<?php echo $this->item['url_view']?>";
$.ajax({
type: 'post',
url: "?module=items&controller=index&action=submitBid",
dataType: "text",
data: 'bid_amount=' + bid_amount + '&item_id=' + item_id + '&current_bid=' + current_bid + '&url_view=' + url_view,
beforeSend: function () {
$('.auction_box').animate({
'backgroundColor': '#ffdead'
}, 400);
},
success: function (result) {
if (result == 'ok') {
$.get(window.location.href, function (data) {
$('.auction_box').animate({
'backgroundColor': '#A3D1A3'
}, 400);
});
} else {
alert(result);
$('.auction_box').animate({
'backgroundColor': '#FFBFBF'
}, 400);
}
}
});
});
Here is the html:
<form action="" method="post">
<div id="<?php echo $this->item['id']; ?>">
<div class="auction_bid_box">
<label for="auction_bid_input">
<!-- Starting bid EXISTS -->
<?php if ($this->item['bid_count'] >= '1') { ?>
You have until <?php echo $this->data['item']['auction_start']; ?> to update the current bid.
<!-- Starting bid is MISSING-->
<?php } else { ?>
You have until <?php echo $this->data['item']['auction_start']; ?> to enter a starting bid.
<?php } ?>
</label>
<span class="auction_bid_container">
<input id="auction_bid_input" type="text" maxlength="12"
class="middle nmr event-clear-focus"
name="bid_amount" value="Enter Bid"/>
<input id="updateBidButton" type="submit"
value="<?php echo $this->translate('Update'); ?>"
class="button grey-button num-items-button"/>
</span>
</div>
</div>
</form>

How to get foreach input value in javascript and pass it to ajax data?

This is my Form
<form method="post" id="BargainForm">
<input type="hidden" name="pro_id" class="pro_id" id="pro_id" value="<?php echo $pro_id; ?>">
<input type="hidden" name="customer_id" class="customer_id" id="customer_id" value="<?php echo $customer_id; ?>">
<input type="text" name="bargain_qty" class="bargain_qty" id="bargain_qty" placeholder="Qty" required/></br></br>
<?php if($productType = 'Configurable'): ?>
<?php foreach($attributes as $attribute): ?>
<input type="text" name="<?php echo strtolower($attribute['store_label']); ?>"
class="<?php echo strtolower($attribute['store_label']); ?>"
id="<?php echo strtolower($attribute['store_label']); ?>"
placeholder="<?php echo $attribute['store_label'] ?>"></br></br>
<?php endforeach; ?>
<?php else: ?>
<?php endif; ?>
<input type="text" name="bargain_price" class="bargain_price" id="bargain_price" placeholder="Total Price" required/></br></br>
<input type="submit" name="bargain_btn" class="bargain_btn">
</form>
Here is my javascript code
<script type="text/javascript">
$(function () {
$('.bargain_btn').click(function(e) {
var qty = $( "#bargain_qty" ).val();
var price = $( "#bargain_price" ).val();
var pro_id = $( "#pro_id" ).val();
var customer_id = $( "#customer_id" ).val();
var att_lable = $( "#<?php echo strtolower($attribute['store_label']); ?>" ).val();
alert(att_lable);
e.preventDefault();
$.ajax({
url: "<?php echo Mage::getUrl('bargain/Ajax/index'); ?>",
type: "POST",
data: {qty,price,pro_id,customer_id},
success: function(data) {
if(data.success) {
}
}
});
});
});
In form i am using foreach. If i have 2 data so it will display 2 input tags, i just don't know how to save values of that 2 input and pass it to data: {qty,price,pro_id,customer_id},
Thank you in advance!
Provide a common class to all textbox that are generated using loop like:
foreach(...)
{
echo '<input class="myTxt" value="" id="" />';
}
Jquery:
var arr = [];
$('.myTxt').each(function(){
arr.push($(this).val());
});
pass this array i.e. arr to ajax call in data{} section using serialize or on an index.
Replace
data: {qty,price,pro_id,customer_id},
By
data: "qty="+qty+"&price="+price+"&pro_id="+pro_id+"&customer_id="+customer_id+"&att_lable="+att_lable,
Do not use:
data: { qty, price, pro_id, customer_id },
Instead use:
data: $("#BargainForm").serialize(),
It will work only if your $attribute['store_label'] name is unique.

Problen with my ajax code to display comment

The code below is a attempt to create a comment system using ajax and php here php part works well comment is inserted into table but seems I didn't get my hands on ajax yet. Ajax does not work comment is not shown unless I reload page. On reloading page comment appears perfectly where it should be so help me on fixing my ajax code.
<?php
if(isset($_POST['content'])) {
$comment=strip_tags($_POST['content']);
$com = $db->prepare("INSERT INTO comments (comment,userto, userfrom, blog) VALUES (:comment, :userto, :userfrom, :blog)");
$com->execute(array(':comment'=>$comment,':userto'=>$userid,':userfrom'=>$uid,':blog'=>$blogId));
}
?>
<div class='db'>
<table>
<tr>
<td>
<img src='<?php echo $tar['profile_pic']; ?>' style='width:40px;height:40px;'/>
</td>
<td>
<a href='<?php echo $tar['username']; ?>'><?php echo $tar['first_name'].' '.$tar['last_name']; ?></a>
<p><?php echo $tar['comment']; ?></p>
</td>
<td>
<a href='#' id='<?php echo $tar['id']; ?>' class='delcomment' style='color:#555555;text-decoration:none;' title='Delete'>X</a>
</td>
</tr>
</table>
</div>
<script type="text/javascript" >
$(function() {
$(".comment_button").click(function() {
var test = $("#content").val();
var dataString = 'content=' + test;
if (test == '') {
alert("Please Enter Some Text");
} else {
$.ajax({
type: "POST",
url: "",
data: dataString,
cache: false,
success: function(html) {
$(".db").show(html);
}
});
}
return false;
});
});
</script>
<form method='post' name='form' action='' class='commentbox'>
<textarea cols='30' rows='2' name='content' id='content'></textarea><br />
<input type='submit' value='Comment' name='submit'class='comment_button'/>
</form>
You dont need to use the variable dataString and you need to change the $.ajax() function for this:
var test = $("#content").val();
$.ajax({
type: "POST",
url: "",
data: {
content: test;
},
success: function(response) {
$(".db").append(response);
}
});
change the following line to avoid page refreshes:
$(".comment_button").click(function(event) {
event.preventDefault();
or change the attrubute type="submit" of your button for type="button", like this:
<button type='button' name='submit' class='comment_button'>Comment</button>
I hope it helps you...
Try this.
And make sure jQuery library is also included in your page.
HTML PAGE
<script type="text/javascript" >
$(function() {
$(".comment_button").click(function() {
var test = $("#content").val();
var comment = test;
if (test == '') {
alert("Please Enter Some Text");
} else {
$.ajax({
type: "POST",
url: "process.php",
data: {content : comment},
cache: false,
success: function(html) {
$("#db").append(html);
}
});
}
return false;
});
});
</script>
<div id="db">
<!--Returned comment will appear here -->
</div>
<form method='post' name='form' action='process.php' class='commentbox'>
<textarea cols='30' rows='2' name='content' id='content'></textarea><br />
<input type='submit' value='Comment' name='submit'class='comment_button'/>
</form>
PHP PAGE
process.php
<?php
if(isset($_POST['content'])) {
$comment=strip_tags($_POST['content']);
$com = $db->prepare("INSERT INTO comments (comment,userto, userfrom, blog) VALUES (:comment, :userto, :userfrom, :blog)");
$com->execute(array(':comment'=>$comment,':userto'=>$userid,':userfrom'=>$uid,':blog'=>$blogId));
}
?>
<table>
<tr>
<td>
<img src='<?php echo $tar['profile_pic']; ?>' style='width:40px;height:40px;'/>
</td>
<td>
<a href='<?php echo $tar['username']; ?>'><?php echo $tar['first_name'].' '.$tar['last_name']; ?></a>
<p><?php echo $tar['comment']; ?></p>
</td>
<td>
<a href='#' id='<?php echo $tar['id']; ?>' class='delcomment' style='color:#555555;text-decoration:none;' title='Delete'>X</a>
</td>
</tr>
</table>
Use
$(".db").append(html);
if you already have existing comments like:
<div class = "db">
Comment 1
Comment 2
...
</div>
.append will add more HTML to existing tag.

how to change the html tag element when onclick to a input text, so the user can edit comment

I am actually trying to make comments and also edit option when the comment enters it will show in a 'div'through ajax.
<?php
$q="select * from discuss where rownum=1 order by id desc";
$s=oci_parse($conn, $q);
$r=oci_execute($s) or die(oci_error());
echo "<table border=1>";
while($m=oci_fetch_assoc($s))
{
echo "<tr style='background-color:red'><th style='float:left;color:white'>Name : ".$m['NAME']."</th><th style='float:right;color:white'>Date: "."".$m['DATE_TIME']."</th></tr>";
echo "<tr class='edit_option' style='width:1000px;height:10px;background- color:white'><div><td id='input_text' style='width:1000px;height:10px;background- color:white'>".$m['COMMENTS']."</div><div class='anchor_edit' id='anchor_id_edit'><span onclick=\"edit_text('".$m['COMMENTS']."')\">edit</span></div></td></tr>";
}
echo "</table>";
?>
<script>
function edit_text(edit_option){
alert(edit_option);
}
</script>
onclick the function value is coming to edit_text() function getting alert, here i am not getting how can iput logic for this comment.
when edit option is clicked the user has to get his/her comment in a input text 'value' so the user can edit comment.
onclick how can i do the edit comment, please anyone can help!!
This may be help to you
Here I take a sample array input data
PHP SCRIPT
<?php
$r=array(
array('COMMENT-ID'=>'1','NAME'=>'Comment1','COMMENTS'=>'Comment1Comment1Comment1Comment1','DATE_TIME'=>'12547896321'),
array('COMMENT-ID'=>'2','NAME'=>'Comment2','COMMENTS'=>'Comment2Comment2Comment2Comment2','DATE_TIME'=>'12547896321'),
array('COMMENT-ID'=>'3','NAME'=>'Comment3','COMMENTS'=>'Comment3Comment3Comment3Comment3','DATE_TIME'=>'12547896321'),
array('COMMENT-ID'=>'4','NAME'=>'Comment4','COMMENTS'=>'Comment4Comment4Comment4Comment4','DATE_TIME'=>'12547896321')
);
echo "<div>";
foreach($r as $m)
{ ?>
<div>
<div>
Name : <?php echo $m['NAME']; ?>
</div>
<div>
Date: <?php echo $m['DATE_TIME']; ?>
</div>
</div>
<div class="comment">
<div class="comment-text" id="comment<?php echo $m['COMMENT-ID']; ?>">
<?php echo $m['COMMENTS']; ?>
</div>
<div class="commentEditBtn">
Edit
</div>
<div class="editedText"></div>
<div class="commentInput" data-id="<?php echo $m['COMMENT-ID'] ?>">
<input type="text" name="comment" /><br/>
<button class="commentSubmit">Submit</button>
</div>
</div><br/>
<?php }
echo "</div>";
?>
jQuery
$(".commentEditBtn").on('click',function(){
$('.commentinput').hide();
var parentDiv = $(this).parent();
var commentText = parentDiv.find('.comment-text').html();
parentDiv.find('.commentInput input').val(commentText.trim());
parentDiv.find('.commentInput').show();
});
$(".commentInput > input").keypress(function(){
var commentData = $(this).val();
$(this).parent().parent().find('.editedText').html(commentData.trim()).show();
});
$(".commentInput .commentSubmit").on('click',function(){
var commentId = $(this).parent().attr('data-id');
var commentText = $(this).parent().find('input').val().trim();
$(this).parent().parent().find('.editedText').html('').hide();
$.ajax({
url: "AJAX_POST_URL",
type: "POST",
data: {
commentId: commentId,
commentText: commentText
},
dataType: 'json',
success: function (data) {
if (data.error == 'false') {
$('#comment' + commentId).html(commentText);
}
}
});
});
CSS
.commentInput{display: none;}
.editedText{display: none;}
Check out this jquery plugin: http://jsfiddle.net/2u89gnn8/1/
You can make, for example, an h1 editable when a user clicks a button:
$('h1').editable({
"enable": true,
"trigger": $('button')
});

Categories