Multiple Checkbox Form Issue using Ajax and Jquery - php

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

Related

multiple forms with jquery serialize method not working

I have multiple form and each form is getting submitted but not the first one.
I tried everything like event.preventDefault();
MY CODE :
<?php for($i=0;$i<=5;$i++){ ?>
<form id="form<?php echo $i; ?>>
<td><?php echo $i++ ?><td>
<td><input type="text" name="detention_unloading_charges" value="<?php echo $history[$i]->name; ?>"></td>
<td><input type="text" name="dtn_chrg_per_day" value="<?php echo $history[$i]->dtn_chrg_per_day; ?>"></td>
<td><input type="text" name="dtn_chrg" value="<?php echo $history[$i]->dtn_chrg; ?>"></td>
<td>
<button class="btn btn-secondary" type="button" onclick="save_changes(<?php echo $i ?>);">Save Changes</button></td>
</form>
}
and jquery function:
function save_changes(id)
{
$.ajax({
url: "History/update",
type: "POST",
data: $('#form'+id).serialize(),
success: function(data) {
// Success message
console.log(data);
if(data==1){
$('.success_pop_up').addClass('show').removeClass('d-none');
} else{
$('.failure_pop_up').addClass('show').removeClass('d-none');;
}
}
});
}
You are incrementing $i twice in the beginning itself by echo $i++, which also increments $i apart from for loop , so loop runs only thrice and form id is form0 but corresponding function is save_changes(1) , where that form id does not exist at all , try below code.
<?php for($i=0;$i<=5;$i++){ ?>
<form id="form<?php echo $i; ?>>
<td><?php echo $i?><td>
<td><input type="text" name="detention_unloading_charges" value="<?php echo $history[$i]->name; ?>"></td>
<td><input type="text" name="dtn_chrg_per_day" value="<?php echo $history[$i]->dtn_chrg_per_day; ?>"></td>
<td><input type="text" name="dtn_chrg" value="<?php echo $history[$i]->dtn_chrg; ?>"></td>
<td>
<button class="btn btn-secondary" type="button" onclick="save_changes(<?php echo $i ?>);">Save Changes</button></td>
</form>
<?php } ;?>
Try this code and let me know if it works.
You'll probably want to solve this the following way:
Let the button do a default submit like so:
<button type="submit">Send</button>
Catch the submit event for your form in jQuery:
$('form').on('submit', function(e) {
// Prevent default so the browser doesnt automatically submit it.
e.preventDefault();
var data = $(this).serialize();
// ... send it
});
This way it is much easier to do AJAX form requests.

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;?>" />

Cakephp point php file for ajax and include php file to Cakephp

i'm trying to run ajax script to connect to mysql under cake. I'm having trouble with attaching file and run ajax script also.
<div>
<?php foreach ($tasks as $questions) : ?>
<?php echo $questions['Question']['name'].'<br>'; ?>
<?php $answers = unserialize($questions['Question']['answers']) ?>
1.<?php echo 'A.'.$answers[0]; ?><input type="radio" value="<?php $answers[0] ?>" name="a" ><br>
2.<?php echo 'B.'.$answers[1]; ?><input type="radio" value="<?php $answers[1] ?>" name="a"><br>
3.<?php echo 'C.'.$answers[2]; ?><input type="radio" value="<?php $answers[0] ?>" name="a"><br>
4.<?php echo 'D.'.$answers[3]; ?><input type="radio" value="<?php $answers[0] ?>" name="a"><br>
<?php endforeach; ?>
</div>
<script>
$(':radio').click(function() {
if($(':radio:checked').length === 1) {
var val = $(this).val();
$.ajax({
type: "POST",
url: "question.php",
//data: {"a":val}
});
}
});
</script>
In controller i have
App::uses('questions', 'Vendor');
which indicates on questions.php file in app/Vendor/questions.php
is it correct ? i can't find suitable for me option here Cakebook
Send request to controller/action:
suppose we have QuestionController add an action named getquesetion then import file from Vender folder in getquesetion action like:
`function getquesetion (){
App::uses('questions', 'Vendor');
}`
and js code is below
`$.ajax({
type: "POST",
url: "questions/getquesetion",
});`

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

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 <?

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.

Categories