How can I capture a variable inside a while loop, with ajax? - php

I have a loop to answer questions that looks something like this:
<?php
while ($u=mysql_fetch_array($result)){
?>
<table>
<tr>
<td>Question_ID</td>
<td>Question</td>
<td>Answer</td>
</tr>
<tr>
<td><? echo $u['question_id'];?></td>
<td><? echo $u['question'];?></td>
<td>
<form>
<input type="hidden" value="echo $u['question_id'];?>" />
<input type="text"/>
Send Answer
</form>
</td>
</tr>
</table>
<?php
}
?>
If the user answers for example the third question that appears on the page, my question is how do I capture the text written and the question_id so I can send those variables to a php page?
<script>
function ajax_answer(){
$.ajax({
question_id = ??? //how do I capture this variable?
answer = ??? //how do I capture this variable?
url:'answers.php',
type:'POST',
dataType:'text/html',
data:'question_id='+question_id + '&answer='+answer,
success: function(){
};
});
};
</script>
Thanks!

You're not giving them an id. I would give the a tag an id with a prefix so that you can use the same id to get your related input value:
<a href="#" id="q<php echo $u['question_id'];?>" // note that I added a "q" prefix
Then you should be able to get that via jQuery like this:
var theid = $(this).attr('id'); // this being the a tag that was clicked
// then just strip off the leading "q" and you have your id.
var thehiddenid = theid.replace('q', '');

If you want to do it in pure javascript,
then pass this to your ajax_answer function from onclick event like below
<?php
while( $u = mysql_fetch_array( $result ) ) {
?>
<tr>
<td><?php echo $u['question_id'];?></td>
<td><?php echo $u['question'];?></td>
<td>
<input type="hidden" value="<?php echo $u['question_id'];?>" />
<input type="text" />
Send Answer
</td>
</tr>
<?php
}
?>
and your javascript will be...
<script type="text/javascript">
function ajax_answer( elem ) {
var question_id = elem.parentElement.children[0].value;
var answer = elem.parentElement.children[1].value;
/// do your request here
return false;
}
</script>
And the same with jQuery.
Add name attribute to those input elements, and add a classname to anchor element
<?php
while( $u = mysql_fetch_array( $result ) ) {
?>
<tr>
<td><?php echo $u['question_id'];?></td>
<td><?php echo $u['question'];?></td>
<td>
<input type="hidden" name="question_id" value="<?php echo $u['question_id'];?>" />
<input type="text" name="answer" />
Send Answer
</td>
</tr>
<?php
}
?>
Javascript
add the onclick event handler dynamically. Now your function ajax_answer accepts two parameters question_id and answer, we will pass those two parameters through the click event handler
<script type="text/javascript">
$(function() {
$("a.send_answer").on("click", function( event ) {
event.preventDefault();
var td = $(this).parents("td:first");
var qid = $("input[name=question_id]", td).val();
var ans = $("input[name=answer]", td).val();
ajax_answer( qid, ans );
});
});
function ajax_answer( question_id, answer ) {
/// do your request here
}
</script>

You change your form and add id for easier selection:
<form>
<input type="hidden" value="<?php echo $u['question_id'];?>" id="question_id" />
<input type="text"/>
Send Answer
</form>
Then get the values like this:
question_id = $("#question_id").val();
Or if your form has only one hidden field for question_id:
question_id = $("input[type=hidden]").val();
Note: please consider to use <?php tags not short tags <?

Related

how to get the value of clicked input element of array in jquery

I'd like to send the value of clicked item of array in table to header's input element.
In below case, I always got the first line's value. How do I get the exact clicked line's value?
Here is my code of what I am trying to do:
<?php
if(isset($_SESSION['wo_arr'])) {
if(is_array($_SESSION['wo_arr'])) {
foreach($_SESSION['wo_arr'] as $key => $value) {
foreach($value as $k => $v ) {
$wo_arr[$key][$k] = $v ;
}
}
}
$num = count($wo_arr['wo_no']);
} else {
$num = 5 ;
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
function selectWork() {
$(document).ready(function () {
var data = $(this).find('.wono_arr').val() ;
$('#wo_no').val(data);
});
}
</script>
</head>
<body>
<FORM>
<p>
work order # <INPUT size=10 TYPE="text" id=wo_no NAME="wo_no">
</p>
<table>
<?php
for($i = 0 ; $i < $num ; $i++) {
?>
<TR>
<TD><INPUT TYPE="TEXT" class="wono_arr" NAME="wo_arr[wo_no][]"
value="<?php if(isset($wo_arr['wo_no'][$i])) echo $wo_arr['wo_no'][$i]; ?>"
onclick="selectWork()">
</TD>
</TR>
<?php
}
?>
</TABLE>
</FORM>
</body>
</html>
Thanks.
Put this on function call :
HTML
<INPUT TYPE="TEXT" class="wono_arr" NAME="wo_arr[wo_no][]" value="<?php if(isset($wo_arr['wo_no'][$i])) echo $wo_arr['wo_no'][$i]; ?>" onclick="selectWork(this)">
And use it in :
JS
function selectWork(e) {
var data = $(e).val();
$('#wo_no').val(data);
}
Recommended attach click handler to input element instead of using inline javascript like so :
HTML
<INPUT TYPE="TEXT" class="wono_arr" NAME="wo_arr[wo_no][]" value="<?php if(isset($wo_arr['wo_no'][$i])) echo $wo_arr['wo_no'][$i]; ?>">
JS
$('table').on('click','.wono_arr', function () {
var data = $(this).val();
$('#wo_no').val(data);
});
Define your each element with a common class name and for that class define a click function as follows.
//JS
<script>
$(document).ready(function(){
$(".wono_arr").click(function(){
alert("Value"+$(this).val());
alert($(this).attr('id')+"clicked");
});
});
</script>
//In your html
<table>
<?php
for($i = 0 ; $i < $num ; $i++) {
?>
<tr>
<td><input type="text" class="wono_arr" id="<?php echo $wo_arr['wo_no'][$i]; ?>" name="wo_arr[wo_no][]"
value="<?php if(isset($wo_arr['wo_no'][$i])) echo $wo_arr['wo_no'][$i]; ?>"
/>
</td>
</tr>
<?php
}
?>
</table>
For multiple HTML element, you can define same class name and then if you define a method using JQuery and If you use that class then the method will work for all the HTML element. When you call the method, get value of current clicked element using this keyword.

pass specific element of array to ajax in joomla 3 module

I'm sure this is really simple but I have been trying to get this for ages.
I have a foreach loop which iterates over an array of objects and displays them in an html table with a submit button which when clicked makes an ajax call to display some data in the same page.
This all works fine except it only passes the value of the last object from the array in the foreach loop instead of the value as displayed in that table row.
I have tried to use a counter or to set and id for the but unsure how to get that specific value and pass it through.
Here is what is in my code:
<?php
// No direct access
defined('_JEXEC') or die; ?>
<div class="status shelterbuddydog" >
<table class="profile_table">
<?php foreach ($animalDetails as $profile):?>
<tr>
<td><?php echo $profile->photo;?></td>
<td><span class="profile">Name:<?php echo $profile->name;?></span><br/>
<span class="profile">Sex: <?php echo $profile->sex;?></span></<br/>
<span class="profile">Age: <?php echo $profile->age;?></span><br/>
<span class="profile">Breed: <?php echo $profile->breed;?></span><br/>
<span class="profile">Animal Id: <?php echo$profile->animalId;?></span><br/>
<span class="profile">Location: <?php echo $profile->shelter;?></span><br/>
<?php $profile->summary;?>
<input type="submit" id="summary" name="summary" value="VIEW MY PROFILE">
</input></td>
</tr>
<?php endforeach;
</table>
<?php
// Instantiate global document object
$doc = JFactory::getDocument();
$js = <<<JS
(function ($) {
$(document).on('click', '#summary', function () {
var profileSummary = {};
profileSummary['photo'] = '$profile->photo';
profileSummary['name'] = "$profile->name";
profileSummary['sex'] = "$profile->sex";
profileSummary['age'] = "$profile->age";
profileSummary['breed'] = "$profile->breed";
profileSummary['shelter'] = "$profile->shelter";
profileSummary['animalId'] = "$profile->animalId";
profileSummary['summary'] = "$profile->summary";
request = {
'option' : 'com_ajax',
'module' : 'shelterbuddydog',
'data' : profileSummary,
'format' : 'raw'
};
$.ajax({
type : 'GET',
data : request,
success: function (response) {
$('.status').html(response);
}
});
return false;
});
})(jQuery)
JS;
$doc->addScriptDeclaration($js);
?>
</div>
Thanks for any help with this.
add hidden fields like this
<?php foreach ($animalDetails as $profile):?>
<tr>
<td><?php echo $profile->photo;?></td>
<td><span class="profile">Name:<?php echo $profile->name;?></span><br/>
<span class="profile">Sex: <?php echo $profile->sex;?></span></<br/>
<input type="submit" class="summary" name="summary" value="VIEW MY PROFILE">
</input>
<input type="hidden" class="name" value="<?php echo $profile->name;?>" />
<input type="hidden" class="sex" value="<?php echo $profile->sex;?>" />
</td>
</tr>
then
$(document).on('click', '.summary', function () {
var $tr=$(this).parents('tr');
var profileSummary = {};
profileSummary['name'] = $tr.find('.name').val();
profileSummary['sex'] = $tr.find('.sex').val();
request = {
'option' : 'com_ajax',
'module' : 'shelterbuddydog',
'data' : profileSummary,
'format' : 'raw'
};
alternatively you can bind info with button as well with html5 data attribute
<input class="summary" data-name="<?php echo $profile->name;?>" />

Get Ajax variable from the PHP foreach loops

I have a simple ajax (jquery version) script and very short php function and they works fine without problem.
When I submit the value from the form input are, the ajax will work to send and get result from
the php script, in this case to get a total amount of the book order.
The Ajax script and html section are as follows:
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseout( function() {
// get field value
var qtyVal = $('#qty').val();
// use HTTP GET get ajax
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: { qty : qtyVal,
},
success: function(data) {
//get xml value
$('#result').html($(data).find('qty').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
<body>
Total price:<div id="result" class="box" style="height=350px;"></div><div id="result1" class="box" style="height=350px;"></div>
<form>
<p>
<label>quantity: </label>
<input type="text" id="qty" name="qty"/>
<br/>
<input type="submit" value="submit">
total price:</p>
<p> </p>
</form>
And the following php script serving as xml also works fine with above ajax request:
<?php
// XML document
header("Content-Type: text/xml");
header("Content-Type:text/html; charset=utf-8");
// get field values
$qty = (isset($_POST["qty"]) ) ? $_POST["qty"] : $_GET["qty"];
echo "<?xml version=\"1.0\" ?>";
echo "<datetime>";
echo "<qty>" . $qty*100 . "</qty>";
$total=$qty*100;
if ($total==0)
echo "<caution>"."please input number!"."</caution>";
else if ($total<=500)
echo "<caution>"."you shoud buy more!"."</caution>";
echo "";
echo "</datetime>";
?>
However when I combine the above scripts with my shopping cart foreach loops, it doesn't work and the ajax script failed to get variables from the form input area. I don't know if it is a variable scope issue (globals or local)? or anything else?
The following is the total script I would like to fixed with:
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseout( function() {
// get value from the form
var qtyVal = $('#qty').val();
// get
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: { qty : qtyVal,
},
success: function(data) {
// get XML value
$('#result').html($(data).find('qty').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
</head>
<body>
<table border="1" align="center">
<tr>
<th>no</th>
<th>name</th>
<th>price</th>
<th>qty</th>
<th>update</th>
</tr>
<?php
foreach( $_SESSION["psn"] as $i => $data ){
?>
<form action="sessionCartUpdate.php">
<input type="hidden" name="psn" value="<?php echo $_SESSION["psn"][$i];?>">
<tr>
<td><?php echo $_SESSION["psn"][$i];?></td>
<td><?php echo $_SESSION["pname"][$i];?></td>
<td><?php echo $_SESSION["price"][$i];?></td>
<td><input type="text" id="qty" name="qty" value="<?php echo $_SESSION["qty"][$i];?>"></td>
<input type="submit" name="qty"
<td><input type="submit" name="btnUpdate" value="update" />
<input type="submit" name="btnDelete" value="delete" />
</td>
</tr>
</form>
<?php
}
?>
<tr><td colsan="5">total amount:<div id="result" class="box" style="height=350px;"></div><div id="result1" class="box" style="height=350px;"></div></td></td>
</table>
<p>continue to shop
<p>Put your order
</body>
</html>
I would be very grateful if anyone can offer kind or possible suggestion or advice?
My goal is to put different number (variables) in the "input area" (name or id as "qty") throught the using of ajax to get a total amount of price and show the result in the div box (id="result" or "result1").
You should replace the id attribute with class because id is supposed to be unique in the dom and using class you can do a loop to get all quantities of the items in the cart
Another thing i have noticed that you have made the an individual form foreach item in the cart there should be one form having the multiple fields,also remove this line <input type="submit" name="qty" it doesent makes sense
<form action="sessionCartUpdate.php">
<?php
foreach( $_SESSION["psn"] as $i => $data ){
?>
<input type="hidden" name="psn" value="<?php echo $_SESSION["psn"][$i];?>">
<tr>
<td><?php echo $_SESSION["psn"][$i];?></td>
<td><?php echo $_SESSION["pname"][$i];?></td>
<td><?php echo $_SESSION["price"][$i];?></td>
<td><input type="text" class="qty" name="qty[]" value="<?php echo $_SESSION["qty"][$i];?>"></td>
<td><input type="submit" name="btnUpdate" value="update" />
<input type="submit" name="btnDelete" value="delete" />
</td>
</tr>
<?php
}
?>
</form>
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseout( function() {
var qtyVal =0;
$( ".qty" ).each(function() {
qtyVal =qtyVal + parseInt($(this).val());
});
// get
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: { qty : qtyVal,
},
success: function(data) {
// get XML value
$('#result').html($(data).find('qty').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
// get field values
$qty = (isset($_POST["qty"]) ) ? $_POST["qty"] : $_GET["qty"];
Instead of using both $_GET and $_POST, you can use $_REQUEST which will give data from either POST or GET.

Multiple Checkbox Form Issue using Ajax and Jquery

I'm trying to make a form that is in a loop has a unique id.
The issue with this is only the first form is working and all the rest after is not triggering the jquery code.
Form:
<?php foreach( $tasks as $tasks ) : ?>
<tr>
<td><?php echo $tasks->title ?></td>
<td><?php echo $newDate; ?></td>
<td><?php echo $tasks->details ?></td>
<td><?php echo $tasks->category ?></td>
<td>
<form class="noclass">
<input class="hideit id" type="text" name="id" value="<?php echo $tasks->id ?>" />
<input type="checkbox" value="<?php echo $tasks->user ?>" name="value" id="checkbox-2-1" class="regular-checkbox big-checkbox" <?php echo $tasks->user ?> />
</form>
</td>
</tr>
<?php endforeach; ?>
Jquery:
<script>
$(function() {
$('#checkbox-2-1').click(function() {
var id = $(".id").val();
var value = $(".check").val();
var dataString = '?id=' + id + '&value=' + value + '&user=<?php echo $id ?>';
alert(dataString);
$.ajax({
type: "POST",
url: "http://example.com/process.php",
data: dataString,
cache: false,
});
})
})
return false;
</script>
You are using
var id = $(".id").val();
var value = $(".check").val();
and what $(".id") and `$(".check")' will return is object.
So you need to convert it into string of key value pair and then send it.
Also refer Gautam answer for foreach correction.
ONE MORE
You are repeating checkbox-2-1 id for checkbox evert-time loop gets execute and ID for each dom must be unique.
What i suggest
Use code as below.
for checkbox click event use
$('input:ckeckbox[name="value"]').on('change',function(){ });
and inside function(){ } write code for getting value of class id and check as below
$(this).closest('form.noclass').find('.id').val();
$(this).closest('form.noclass').find('.value').val()
Your first form is not closing....close like this
<form class="noclass">
<input class="hideit id" type="text" name="id" value="<?php echo $tasks->id ?>" />
</form>
<form class="noclass">
<input class="hideit id" type="text" name="id" value="<?php echo $tasks->id ?>" />
<input type="checkbox" value="<?php echo $tasks->user ?>" name="value" id="checkbox-2-1" class="regular-checkbox big-checkbox" <?php echo $tasks->user ?> />
</form>
And what is
<?php foreach( $tasks as $tasks ) : ?>
try to give another variable like
<?php foreach( $tasks as $task ) : ?>
and then change the symultanious

Making table cells clickable

I currently have a table of about 30 rows and I would like to make <td> clickable in each case:
<tr height="100px" align="center">
<?php do { ?>
<td style="background-color: <?php echo $row_dd1['colour']; ?>;">
<form action="pay.php?id=<?php echo $row_dd1['dNo']; ?>&user=<?php echo $username; ?>" method="post">
<input type="hidden" id="<?php echo $row_dd1['dNo']; ?>"><input type="hidden" value="<?php echo $username; ?>">
<button type="submit" class="link" id="t<?php echo $row_dd1['dNo']; ?>"><span><?php echo $row_dd1['dNo']; ?></span></button></form>
</td>
<?php } while ($row_dd1 = mysql_fetch_assoc($dd1)); ?>
</tr>
How do you make the table cell clickable? I would like it to have the same link as the form action that I have used which is:
<form action="pay.php?id=<?php echo $row_dd1['dNo']; ?>&user=<?php echo $username; ?>" method="post">
This is a perfect example of where to use .delegate(), like this:
$("#myTableID").delegate("td", "click", function() {
$(this).find("form").submit();
});
.delegate() attaches one handler to the <table>, rather than n handlers, one per cell. If you just want to navigate to the URL, it would look like:
$("#myTableID").delegate("td", "click", function() {
window.location.href = $(this).find("form").attr("action");
});
To actually submit the form:
$('td > form').each(function(i,e){
var form = $(this);
var cell = form.parent();
if(cell.is('td')){
cell.click(function(){
form.submit();
});
}
});
If you jsut want to follow the link instead, jsut modify the form.submit() part to change window.location.href with form.attr('action').
What about jQuery's click-event?
$('td').click(function () {
$('form', this).submit();
return false;
});
This submits the form inside the clicked <td>.

Categories