I am trying to use an ajax form submission for a list of forms generated by a php foreach loop. My issue is I obviously need to mark each generated form as unique and can't seem to figure it out. I thought to use the HTML data- attribute but cant seem to make it work.
Here is the code so
<?php
if (isset($_SESSION['team_mem_id'])) {
$query_team_matches = $conn->prepare($sql_team_matches);
$query_team_matches->bindParam(':tid', $tid, PDO::PARAM_INT);
$query_team_matches->execute();
$matches = $query_team_matches->fetchAll(PDO::FETCH_ASSOC);
if (!empty($matches)) {
foreach($matches as $Matches) {
$tmid = $Matches['tmid'];
$opponent = $Matches['opponent'];
$location = $Matches['location'];
$tm_datetime = $Matches['tm_datetime'];
$match_date = date("F j",strtotime($tm_datetime));
$match_time = date("g:i A",strtotime($tm_datetime));
$match_when = $match_date. " # ".$match_time;
?>
<div class='match_container'>
<div class='match_basic_info'>
<h3><?php echo $match_when.' - <span style="font-size: 16px">'.$location.' vs '.$opponent; ?></span></h3>
<a class='match_details_link' href='http://localhost:1234/tennisexcel/teams/match.php?r=team&tid=<?php echo $tid; ?>&tmid=<?php echo $tmid; ?>'>More info...</a>
</div>
<div id='match_avail_container' class='match_avail_container'>
<h3>My availability:</h3>
<form id='avail_submit_form' data-tmid='<?php echo $tmid; ?>' class="" action='http://localhost:1234/tennisexcel/test_ajax.php' method='POST'>
<input type='hidden' name='uid' value='<?php echo $_SESSION['uid']; ?>'/>
<input type='hidden' name='tid' value='<?php echo $_SESSION['tid']; ?>'/>
<input type='hidden' name='tmid' value='<?php echo $tmid; ?>'/>
<button class='match_avail_yes' type='submit' name='availability' value='1'>✔</button>
<button class='match_avail_no' type='submit' name='availability' value='2'>✖</button>
</form>
<div id="signup" data-tmid='<?php echo $tmid; ?>' class='match_avail_success success_display'>
<p>success!</p>
</div>
</div>
</div>
<?php
}
}
}
?>
I added a data-tmid='$tmid' to the form and the div that need to be marked as unique. The jquery is below:
$(document).ready(function() {
$('#avail_submit_form').submit(function(evt) {
evt.preventDefault();
var url = $(this).attr('action');
var fromData = $(this).serialize();
$.post(url, fromData, function(response) {
$('#avail_submit_form').hide();
$('#signup').removeclass('success_display');
}); //end post
}); //end submit
}); //end ready
I tried adding on [data-tmid='+$(this).attr('data-tmid')+'] to each id but not sure how to make it work properly or if it is even the correct way to do it.
Thank anyone who can lead me in the right direction!
Use a class instead of ID.
<div class='match_container'>
<div class='match_basic_info'>
<h3><?php echo $match_when.' - <span style="font-size: 16px">'.$location.' vs '.$opponent; ?></span></h3>
<a class='match_details_link' href='http://localhost:1234/tennisexcel/teams/match.php?r=team&tid=<?php echo $tid; ?>&tmid=<?php echo $tmid; ?>'>More info...</a>
</div>
<!-- fix #1 -->
<div class='match_avail_container'>
<h3>My availability:</h3>
<!-- fix #2 -->
<form data-tmid='<?php echo $tmid; ?>' class="avail_submit_form" action='http://localhost:1234/tennisexcel/test_ajax.php' method='POST'>
<input type='hidden' name='uid' value='<?php echo $_SESSION['uid']; ?>'/>
<input type='hidden' name='tid' value='<?php echo $_SESSION['tid']; ?>'/>
<input type='hidden' name='tmid' value='<?php echo $tmid; ?>'/>
<button class='match_avail_yes' type='submit' name='availability' value='1'>✔</button>
<button class='match_avail_no' type='submit' name='availability' value='2'>✖</button>
</form>
<!-- fix #3 -->
<div data-tmid='<?php echo $tmid; ?>' class='match_avail_success success_display'>
<p>success!</p>
</div>
</div>
</div>
I am assuming you only want to target the current form in your jQuery
$(document).ready(function() {
// add event handler to your forms
$('.avail_submit_form').submit(function(evt) {
evt.preventDefault();
// cache the current form object
var form = $(this);
var url = form.attr('action');
var fromData = form.serialize();
$.post(url, fromData, function(response) {
// make changes to current form and its related element
form.hide();
form.next('.match_avail_success').removeclass('success_display');
});
});
});
Related
I am trying to build a system where the product-container will display a form or a button depending on if the product is currently in the cart or not. I have an Ajax post system that seems to work fine, but I shall include that too. I have a front Controller which sends the Cart Content and the Products.
The problem is that when I refresh the page my form is supposed to replace the buy button for the given product, but it does not work. Only the Ajax post to Cart system works.
My view (which includes some of the javascript/php):
<?php $countP = 0; ?>
#foreach($products as $product)
<input type="hidden" id="product_id<?php echo $countP; ?>" value="
{{$product->id}}">
<div class="item main-product-container">
<a href="#"<i class="fa fa-exclamation" aria-hidden="true"></i>
</a>
<div class="product-img text-center">
<img src="{{url('img', $product->image)}}">
</div>
<p class="price text-center">{{$product->price}},- kr</p>
<div class="product-title">{{$product->name}}</div>
<script>
<?php foreach($cartContents as $cartContent) { ?>
if(<?php echo $cartContent->id ?> = {{$product->id}})
{
$('.cartBtn{{$product->id}}').hide();
$('.productForm{{$product->id}}').show();
} else {
$('.cartBtn<?php echo $product->id;?>').show();
$('.productForm<?php echo $product->id;?>').hide();
}
<?php } ?>
</script>
<form class="productForm{{$product->id}} productForm"
id="productForm<?php echo $countP;?>">
<input class="qty-input" name="qty" id="qty" type="integer"
value="1">
<input type="hidden" id="id" name="id" value="{{$product->id}}">
<input type="submit" id="ajaxSubmit{{$product->id}}"
class="cart-button" value="Legg til">
</form>
<button class="btn btn-default add-to-cart cartBtn<?php echo
$product->id;?>" id="cartBtn<?php echo $countP;?>">Kjøp</button>
</div>
<?php $countP++?>
#endforeach
</div>
My Ajax:
<script>
$(document).ready(function() {
$('.productForm').hide();
<?php $maxP = count($products);
for($i=0;$i<$maxP; $i++){
?>
$('#cartBtn<?php echo $i;?>').click(function() {
var product_id<?php echo $i;?> = $('#product_id<?php echo $i;?
>').val();
$.ajax({
type: 'get',
url: '<?php echo url('/cart/post');?>/'+ product_id<?php echo $i;?>,
error: function(data) {
var errors = data.responseJSON;
console.log(errors);
},
success:function() {
$('#cartBtn<?php echo $i;?>').hide();
$('#productForm<?php echo $i;?>').show();
},
});
});
<?php } ?>
});
I have the following code with a form inside a list that should submit the element through Ajax. The values in the form is repeated through a do ... while loop, so that the list become a dynamically list, like in this picture:
But when I click a button, the only element that is sent through the Ajax code is the value of the last button, even though I click on Oranges for example.
The code is as follow:
<script>
function submitForm() {
$.ajax({type:'POST', url: 'jQuery-ajax-demo.php', data:$('#MyJobsForm').serialize(), success: function(response) {
$('#myJobs_Right').find('.form_result').html(response);
}});
return false;
}
</script>
</head>
<body>
<ul id="btn_MyJobs" data-role="listview" data-inset="true">
<li id="MyJobs_List" class="push">
<form id="MyJobsForm" onsubmit="return submitForm();">
<?php do { ?>
<input type="hidden" name="name" value="<?php echo $row_Recordset1['cargo']; ?>">
<input type="submit" name="submit" value="<?php echo $row_Recordset1['cargo']; ?>">
<br/>
<br/>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
</form>
</li>
</ul>
<div id="myJobs_Right">
<div class="form_result"> </div>
</div>
</body>
The jQuery-ajax-demo.php page looks like this:
<?php
if(isset($_POST['name'])) {
$name = $_POST['name'];
?>
Your Name Is: <?php echo $name; ?><br />
<?php
die();
}
?>
If you have to do it this way, then you might try creating a new form for each button:
<?php do { ?>
<form onsubmit="return submitForm(this);"> <!--Note I added "this" -->
<input type="hidden" name="name" value="<?php echo $row_Recordset1['cargo']; ?>">
<input type="submit" name="submit" value="<?php echo $row_Recordset1['cargo']; ?>">
<br/>
<br/>
</form>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
Then the only value that will get posted will be the hidden value that is in the form whose button you clicked. I updated the onsubmit call above to include this in the call. So you can do the below in your function:
function submitForm(form) {
var $form = $(form);
$.ajax({
type:'POST',
url: 'jQuery-ajax-demo.php',
data:$form.serialize(),
success: function(response) {
$('#myJobs_Right').find('.form_result').html(response);
}
});
return false;
}
I'm trying to prevent the default action when submitting a form with ajax but I believe I have my code wrong as the page seems to do a 'refresh' and the form clears but nothing is sent to the database. I tried adding the link to the php processing script in the 'action' part of the form and it does submit fine to the database so the problem seems to be with my jQuery code.
<script type="text/javascript">
$(document).ready(function(e){
e.preventDefault();
$("#rpack_add_form").validate({
submitHandler: function(form) {
// do other stuff for a valid form
$.post('<?php echo BASE_URL?>/core/addrpack.php.php', $("#rpack_add_form").serialize(), function(data) {
$('#ajaxResult').html(data);
});
}
});
});
</script>
My form code:
<div id="rpacks_admin" style="display: none;">
<h5>Add A New Recovery Pack</h5>
<form id="rpack_add_form" class='small_form' name='rpack_add_form' action='' method='post'>
Contract:
<select id="contract_select" name="contract" onchange="showContract(this)">
<option value='0'>Select Contract</option>
<?php
$sth = $conn->query("SELECT * FROM `contracts`");
while($row = $sth->fetch(PDO::FETCH_ASSOC))
{
echo '<option value='.$row['contracts_id'].'>'.$row['contracts_name'].'</option>';
}
?>
</select>
<div id="contract1" class="admin_box">
Prefix: <input name='prefix' type='text' id='prefix'><br />
Number: <input name='number' type='text' id='number'><br />
Suffix: <input name='suffix' type='text' id='suffix'><br />
</div>
<div id="contract2" class="admin_box">
<p>Sapce for content</p>
</div>
<div id="contract3" class="admin_box">
<p>Sapce for contentrm</p>
</div>
Received:
<select id="select_receive" name="received" onchange="showLocation(this)">
<option value="0">No</option>
<option value="1">Yes</option>
</select><br />
<div id="location_box" style="display: none; padding-top: 5px;">Location: <input name='location' type='text' id='location'></div>
<input class='button' type=submit value='Add' name='add_rpack'>
</form>
<a class='hide_div' href='javascript:void(0);' onclick='hideRdiscDiv()'>Close</a>
and my PHP if needed
<?php
session_start();
include_once 'config.php';
include_once 'connect.php';
include_once 'bcrypt.php';
$prefix = $_POST['prefix'];
$number = $_POST['number'];
$suffix = $_POST['suffix'];
$contract = $_POST['contract'];
$received = $_POST['received'];
$location = $_POST['location'];
//Check if password and username has been submitted then add to DB
if (empty ($number))
{
echo "You need to enter a recovery pack number";
}else
{
$sth = "INSERT INTO `rpacks` (rpacks_prefix, rpacks_number, rpacks_suffix, rpacks_contract, rpacks_receive, rpacks_location) VALUES (:prefix, :number, :suffix, :contract, :received, :location)";
$q = $conn->prepare($sth);
$q->execute(array(':prefix'=>$prefix,':number'=>$number,':suffix'=>$suffix,':contract'=>$contract, ':received'=>$received, ':location'=>$location));
echo "Added";
}
The .validate() object has a sendForm parameter. It is set to true by default, but you need to set it to false, as in the code below, to prevent the form from being submitted:
$(document).ready(function () {
$('#rpack_add_form').validate({
submitHandler: function (form) {
// do other stuff for a valid form
$.post('<?php echo BASE_URL?>/core/addrpack.php.php', $('#rpack_add_form').serialize(), function (data) {
$('#ajaxResult').html(data);
});
},
sendForm: false
});
});
You can reference the docs for more info.
I have form like this:
<div class="satu">
<input type='text' size='1' maxlength='1' name='score[1][]' id='score[1][]'>
</div>
<div class="dua">
<input type='text' size='1' maxlength='3' name='weight[1][]' id='weight[1][]'> %
</div>
<div class="tiga">
<input type='text' size='5' name='weightscore[1][]' id='weightscore[1][]' disabled>
</div>
<div class="satu">
<input type='text' size='1' maxlength='1' name='score[2][]' id='score[2][]'>
</div>
<div class="dua">
<input type='text' size='1' maxlength='3' name='weight[2][]' id='weight[2][]'> %
</div>
<div class="tiga">
<input type='text' size='5' name='weightscore[2][]' id='weightscore[2][]' disabled>
</div>
this is the jquery script:
$('[id^="score"]').keyup(function()
{
var score=$('[id^="score"]').val();
var weight=$('[id^="weight"]').val();
$.ajax({
url: "cekweightscore.php",
data: "score="+score+"&weight="+weight,
success:
function(data)
{
$('[id^="weightscore"]').val(data);
}//success
});//ajax
});
this is the php code:
<?php
include "connection.php";
$score = $_GET['score'];
$weight = $_GET['weight'];
$totalweightscore=(($weight * $score )/ 100);
echo"$totalweightscore";
?>
When i keyup on score[1][], the value of weight[1][] is not coming out. PLease Help me, How to get value from multiple input fields on different class ??
Your code works for me for the first group of input elements. It would not work for the second set of elements because with .val you get "the current value of the first element in the set of matched elements". So when you keyup on score[2] the JS code actually sends the values of score[1] and weight[1], which may be empty.
To fix that one easy way is to wrap an element around each group of items so that you can easily target the "associated" weight element when keyup is triggered, like this:
<div class="group">
<div class="satu"><input type='text' name='score[1][]' id='score[1][]'></div>
<div class="dua"><input type='text' name='weight[1][]' id='weight[1][]'> %</div>
<div class="tiga"><input type='text' name='weightscore[1][]' id='weightscore[1][]' disabled></div>
</div>
<div class="group">
<div class="satu"><input type='text' name='score[2][]' id='score[2][]'></div>
<div class="dua"><input type='text' name='weight[2][]' id='weight[2][]'> %</div>
<div class="tiga"><input type='text' name='weightscore[2][]' id='weightscore[2][]' disabled></div>
</div>
And the code would look like
<script type="text/javascript">
$('.satu input').keyup(function () {
var $satuInput = $(this);
var score = $satuInput.val();
var weight = $satuInput.closest(".group").find('.dua input').val();
$.ajax({
url: "cekweightscore.php",
data: "score=" + score + "&weight=" + weight,
success: function (data) {
$satuInput.closest(".group").find('.tiga input').val(data);
} //success
}); //ajax
});
</script>
I also changed the jQuery selectors to work with the classes in your HTML rather than the element ids; while the code should work either way, this style feels better to me.
you can get value with this
score.each (function () {
console.log(this.value);
});
I can't submit the form with dynamic id. Below is my code.
<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
var fval;
var cvalue = "<?php echo $_POST['currentval']; ?>";
if(!(cvalue)) cvalue=0;
$(document).ready(function() {
$('#upload'+cvalue).submit(function() {
var options = {
target: '#message',
url:'process.php?sval='+cvalue,
success: function() {
alert("success");
$('#uploader').html('');
}
};
$(this).ajaxSubmit(options);
return false;
});
});
</script>
<div id="message"></div>
<?php
for($i=0;$i<5;$i++) {
echo "<form action='#' method='post' name='upload' id='upload$i' enctype='multipart/form-data'>";
echo "<input type='hidden' name='svalhid' id='svalhid' value='$i'>";
echo "<input type='file' id='fl$i' name='filename".$i."up'>";
echo "<input type='hidden' name='currentval' id='currentval' value='$i'>";
echo "<input type='submit' name='uploads$i' value='Ok'><br>";
echo '</form>';
}
?>
In this line, $('#upload'+cvalue).submit(function() {
I can't get the cvalue. I can't identify what's wrong with this code. Anybody please help me.
Check follow line
echo "<form action='#' method='post' name='upload' id='upload$i' enctype='multipart/form-data'>";
Are you really sure that you printed out a correct value for the id attribute?
I think it exists two better ways:
1st (the best way in my eyes):
<?php
for($i=0;$i<5;$i++) {
?>
<form action='#' method='post' name='upload' id='upload<?php echo $i ?>' enctype='multipart/form-data'>";
<input type='hidden' name='svalhid' id='svalhid' value='<?php echo $i ?>'>"
<input type='file' id='fl<?php echo $i ?>' name='filename<?php echo $i ?>up'>";
<input type='hidden' name='currentval' id='currentval' value='<?php echo$i ?>'>"
<input type='submit' name='uploads<?php echo $i ?>' value='Ok'><br>"
</form>'
<?php
}
?>
2nd: Change the mentioned line to following:
echo "<form action='#' method='post' name='upload".$i."' id='upload".$i."' enctype='multipart/form-data'>";
Note: You defined a couple of forms with the same name. As far as I know, the attribute 'name' is the main attribute for forms, not the 'id' attribute.
I don't see where you assign anything besides "" or 0 to cvalue. Also, those two assignments are outside of $(document).ready(function() { so there could be something weird going on with that code executing before your document has fully loaded. Move them inside of the document.ready call and see what happens.
Try using
var cvalue = "<?php echo $_GET['currentval']; ?>";
or
var cvalue = "<?php echo $_REQUEST['currentval']; ?>";
Also try what #reporter said about the form id: id='upload".$i."
The form id should be the same as the one referenced here:
$('#upload'+cvalue).submit(function() {
Example:
in javascript:
$('#upload').submit(function() {
then form should be:
<form id="#upload" ...
You should definitely see something happen.
Try installing firebug and use console.log(variablehere) instead of alert(variablehere). It's more cleaner.
Hope that helps