How to get input hidden value from multiple forms? - php

I am having unlimited multiple dynamic forms containing only single input hidden field having submit button and trying to get the value of that form whose button is clicked. I don't know why this is not happening.
I've read these How to get the Specific Form Field value using JQuery and Submit a specific form with JQuery Ajax but still no result.
controller
public function order()
{
$data['fruits'] = $this->catering_model->getrecess('Recess Fruits','Category Recess');
$this->load->view('ChoiceLaunch/order',$data);
}
order.php
<?php $i=0;
if(!empty($fruits)){
?>
<div class="col-sm-12"><h3 align="center"><?php echo $fruits[0]->catsubname; ?></h3><br>
<!-- while($res_item=mysqli_fetch_array($cat_item_sql)){ -->
<?php $i=0;
foreach($fruits as $lrd1){
$i++;
?>
<form method="post" action="">
<div class="col-sm-4 col-md-3">
<div class="thumbnail">
<img style="height: 177px;width: 200px;" src="<?php echo 'http://localhost:8080/catering/uploads/'.$lrd1->picturename;?>" alt="...">
<div class="caption protitle">
<p style="height: 12px;width: 200px;margin-top: 9px;margin-bottom:29px;"><?php echo $lrd1->itemname; ?></p><br>
<input type="hidden" name="quantity" id="quantity<?php echo $i;?>" value="<?php echo $lrd1->itemname; ?>" size="2">
<button type="submit" id="send" class="btn btn-info">Add To Order</button><br>
<?php echo '$'.$lrd1->price; ?>
</div>
</div>
</div>
<?php
}}
?>
</form>
</div>
<script>
$('#send').click(function(){
//var selection= $(this).attr('id');
// $( "[id='quantity']" ) .each(function(){
// alert($(this).val());
// }); //running bt showing all at once
$( "form:input[type=hidden]" ) .each(function(){
alert($(this).val());
})
});
</script>
I am using CodeIgniter.

1st: Id must be unique so use class instead
<button type="submit" class="btn btn-info send">Add To Order</button><br>
and in js
<script>
$('form').on('submit',function(e){
e.preventDefault();
var hiddenVal = $(this).find('input[type="hidden"]').val();
alert(hiddenVal);
});
</script>
and in php I think you closed the </form> in a wrong place
<?php $i=0;
foreach($fruits as $lrd1){
$i++;
?>
<form method="post" action="">
<div class="col-sm-4 col-md-3">
<div class="thumbnail">
<img style="height: 177px;width: 200px;" src="<?php echo 'http://localhost:8080/catering/uploads/'.$lrd1->picturename;?>" alt="...">
<div class="caption protitle">
<p style="height: 12px;width: 200px;margin-top: 9px;margin-bottom:29px;"><?php echo $lrd1->itemname; ?></p><br>
<input type="hidden" name="quantity" id="quantity<?php echo $i;?>" value="<?php echo $lrd1->itemname; ?>" size="2">
<button type="submit" class="btn btn-info send">Add To Order</button><br>
<?php echo '$'.$lrd1->price; ?>
</div>
</div>
</div>
</form>
<?php
}
?>
if you have more then one hidden field you need to use .each()
<script>
$('form').on('submit',function(e){
e.preventDefault();
$(this).find('input[type="hidden"]').each(function(){
alert($(this).val());
});
});
</script>

Your id never be quantity because you included a number in the final of each quantity word
Change de hidden input to this:
<input type="hidden" name="quantity" id="quantity<?php echo $i;?>" value="<?php echo $lrd1->itemname; ?>" class="quantity" size="2">
And change the each jquery to this:
$( ".quantity" ).each(function(){
alert($(this).val());
}); //running bt showing all at once

I would personally use a data-* attribute instead of hidden elements. This will allow you to avoid further lookups since they will be on the element you are handling the event for.
<button type="submit" class="btn btn-info send" data-quantity="45">Add To Order</button>
Then the logic would be like
$('.send').on('click', function(){
var $this = $(this);
console.log($this.data('quantity'));
});

Related

Ajax form submission without refresh "not working"

I'm trying to submit the form in the same page without refresh the page.
my form:
<?php
if(isset($_POST['transfer'])){
$amount = $_POST['amount'] ? $_POST['amount'] : '';
$from_c = $_POST['from_c'] ? $_POST['from_c'] :'';
$to_c = $_POST['to_c'] ? $_POST['to_c'] : '';
}
?>
<form class="form-inline" method="post" action="convert.php" onsubmit = 'return false;' id = "frmData">
<div class="md-form form-group col-sm-3">
<div class="input-group col-sm-12">
<input type="number" value="1" min="0" step="0.01" data-number-to-fixed="2" data-number-stepfactor="100" class="form-control" name="amount">
<span class="input-group-addon" id="natCurrency" style="margin-top: 10%;margin-left: -5;margin-right: 15%;"></span>
</div>
</div>
<div class="">
<label for="from_c">from currency</label>
<select id="natSelect" onchange="let csymbol = $(this).find(':selected').data('symbol');$('#natCurrency').text(csymbol) " name="from_c" class="mdb-select colorful-select dropdown-primary" style="width:200px;" placeholder="select currency" >
<?php foreach ($black_a as $name => $black_p) {
?>
<option value="<?php echo $black_p['name'];?>" data-symbol="<?php echo $black_p['symbol_native']; ?>"><?php echo $black_p['name'];?></option>
<?php } ?>
</select>
</div>
<div class="">
<label for="to_c">to currency</label>
<select class="mdb-select colorful-select dropdown-primary" name="to_c" style="width:200px;" >
<?php foreach ($black_a as $name => $black_p) {
?>
<option value="<?php echo $black_p['name'];?>"><?php echo $black_p['name'];?></option>
<?php } ?>
</select>
</div>
<input name="transfer" value="convert" class="btn btn-elegant" style="margin-top:3%;" id = "ha" />
</form>
And I have this PHP code when the form is submitted:
<?php
if(isset($from_c) &&$from_c ==$to_c && isset($to_c) && $to_c == $from_c){
echo "
<div id='less' class='well'>
<div dir='RTL'>
<ul class='text-right'>
<li><strong>resultل</li>
</ul>
<div class='col-md-4'>
<div class='msg msg-success msg-success-text'> <span class='glyphicon glyphicon glyphicon-ok'></span> Error !</div>
</div>
";
}
?>
I tried using AJAX, the page is still refreshing after clicking submit:
$('#ha').on('click', function (e) {
e.preventDefault(); //prevent to reload the page
$.ajax({
type: 'POST', //hide url
url: 'convert.php', //your form validation url
data: $('#frmData').serialize(), //USE THE ID WE SET IN THE FORM
success: function (response) {
$(".mydiv").append(response);
}
});
});
.mydiv:
<div class='mydiv'>
<div dir='RTL'>
<ul class='text-right'>
<li><strong>result</li>
</ul>
<div class='col-md-4'>
<div class='msg msg-success msg-success-text'> <span class='glyphicon glyphicon glyphicon-ok'></span> $amount</div>
</div>
I also tried to using iframe but when clicking the submit button nothing happens.
How can I make this works and displaying the message I have in the if statement in my second PHP code?
This will work If this is your submit button
<input type="submit" name="transfer" value="convert" class="btn btn-elegant" style="margin-top:3%;" />
Change it to
<input name="transfer" value="convert" class="btn btn-elegant" style="margin-top:3%;" id = "ha" /> //ADD AN ID TO SPECIFY THE ON CLICK TRIGGER
Then your form
<form class="form-inline" method="post" action="convert.php" >
Change it to
<form class="form-inline" method="post" action="convert.php" onsubmit = 'return false;' id = "frmData"> // ADD AN ID TO YOUR FORM
Then minor adjustment to your script
$('#ha').on('click', function (e) {
e.preventDefault(); //prevent to reload the page
$.ajax({
type: 'POST', //hide url
url: 'convert.php', //your form validation url
data: $('#frmData').serialize(), //USE THE ID WE SET IN THE FORM
success: function (response) {
$(".yourDiv").append(response);
}
});
});
to achieve this you have to make changes in your code first change your form part like this
<form class="form-inline" method="post" action="convert.php" onsubmit = 'return false;' id = "frmData">
change your submit button like this
<input name="transfer" value="convert" class="btn btn-elegant" style="margin-top:3%;" id = "ha" />
then in your ajax function add e.preventDefault(); in first line .

Div text replace in other div

I want class="hotelname" echo text in class="a" and class="hotelname" is hide. is that possible? I used jQuery code but its not working.
<form id="" class="" method="GET" action="http://localhost/blue_bucket/county/" enctype="multipart/form-data">
<h2 class="a"></h2>
<?php
foreach ($query as $row)
{
?>
<h3 class="hotelname"><?php echo $hotelnames = $row->hotel; ?></h3>
<div class="book-it-btn">
<button type="submit" name="submit" class="btn btn-default">Apply</button>
</div>
</form>
<?php
}
?>
Jquery:
jQuery(".a").append(jQuery(".hotelname").html());
As per my understanding you want .hotelname class value to put in .a class then you want to hide .hotelname class element ?
Check the working snippet below
var hotelName = $(".hotelname").text();
$(".a").text(hotelName);
$(document).ready(function() {
var hotelName = $(".hotelname").text();
$(".a").text(hotelName)
$(".hotelname").hide();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="" class="" method="GET" action="http://localhost/blue_bucket/county/" enctype="multipart/form-data">
<h2 class="a"></h2>
<?php
foreach ($query as $row)
{
?>
<h3 class="hotelname">My hotel</h3>
<div class="book-it-btn">
<button type="submit" name="submit" class="btn btn-default">Apply</button>
</div>
</form>
<?php
}
?>

submit php form with different input type using javascript/ajax

I have to submit a form with some fields, like multiple checkboxes selection and some hidden input fields via ajax and replace html content with response. finally i go with javascript/ajax...but where i was wrong?
<?php include( 'session.php');
$userid=$_SESSION[ 'Userid'];
include( 'connection.php');
?>
<head>
<script>
function myFunction() {
var soi = document.getElementById("sweaterownerid").value;
var osp = document.getElementById("osweaterpic").value;
var osi = document.getElementById("osweaterid").value;
var value = [];
$("input[name*='" + sweater+ "']").each(function () {
// Get all checked checboxes in an array
if (jQuery(this).is(":checked")) {
value.push($(this).val());
}
});
var dataString = 'soi1=' + soi + '&osp1=' + osp + '&osi1=' + osi + '&value1=' + value;
if (soi1 == '' || osp1 == '' || osi1 == '' || value1 == '') {
alert("Please Fill All Fields");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "Usercloset1.php",
data: dataString,
cache: false,
success: function(response) {
$('#mydiv').replaceWith(response);
}
});
}
return false;
}
</script>
</head>
<div id="mydiv">
<div class="padding-top">
<div class="col-lg-3 col-md-3 col-sm-6 col-xs-12 ">
<div class="shop_item" style="width:100%;">
<form id="myForm">
<?php
$sweaterid=$_GET['d'];
$sownerid=$_GET['e'];
$opic=$_GET['f'];
$query1="select * from `usersweater` where `Sweaterid`='$sweaterid'";
$result1=mysql_query($query1);
$row1=mysql_fetch_assoc($result1);
$sweaternikname=$row1['SNickname'];
?>
<div>
<ul class="sweaters">
<li> <h4><?php echo $sweaternikname; ?></h4> <img src="upload/<?php echo $opic; ?>"> </li>
</ul>
<ul class="sweater1">
<?php
$query="select * from `usersweater` where `Userid`='$userid' && `Swap`='0' ";
$result = mysql_query($query);
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)){
$sid = $line[Sweaterid];
$img = $line[Sweaterpic];
$nikname = $line[SNickname];
$size = $line[Size];
?>
<li> <h4><?php echo $nikname; ?><input type="checkbox" name="sweater[]" value="<?php echo $sid; ?>" /></h4> <img src="upload/<?php echo $img; ?>"> </li>
<?php } ?>
</ul>
</div>
<input type="hidden" name="sweaterownerid" value="<?php echo $sownerid; ?>">
<input type="hidden" name="osweaterpic" value="<?php echo $opic; ?>">
<input type="hidden" name="osweaterid" value="<?php echo $sweaterid; ?>">
<input type="submit" name="next" onclick="myFunction()" value="NEXT" class="btn woo_btn btn-primary" style="margin-left: 30px;">
<input type="button" name="cancel" value="CANCEL" class="btn woo_btn btn-primary">
</form>
</div>
</div>
<div class="clearfix"></div>
<hr>
</div>
</div>
I want to pass the selected option to another page, which I do now using form action. But I want it dynamically without reloading page. I am new to ajax/javascript.
Second thing is, how can I handle the response, where submitting this form I want to replace first page content with the reponse that we get using ajax. This means replace all html content with other page's html content. I atteched the file which I want in response after submit.
<div class="padding-top">
<div class="col-lg-3 col-md-3 col-sm-6 col-xs-12 ">
<div class="shop_item" style="width:100%;">
<div style="text-align:center;">
<h4>Are you sure you want to swap?</h4>
</div>
<form action="Usercloset2.php" method="post">
<?php
include('session.php');
include('connection.php');
foreach ($_POST['value1'] as $sid){
$query1="select * from `usersweater` where `Sweaterid`='$sid'";
$result1=mysql_query($query1);
$row1=mysql_fetch_assoc($result1);
$sweaternikname=$row1['SNickname'];
$sweaterpic=$row1['Sweaterpic'];
?>
<div style=" ">
<ul class="sweaters">
<li> <h4><?php echo $sweaternikname; ?></h4> <img src="upload/<?php echo $sweaterpic; ?>"> </li>
</ul>
</div>
<!-------requester's own sweater details--------------->
<input type="hidden" name="sid[]" value="<?php echo $sid;?>">
<input type="hidden" name="snikname[]" value="<?php echo $sweaternikname;?>">
<input type="hidden" name="spic[]" value="<?php echo $sweaterpic;?>">
<?php } ?>
<!-------requester's show intrest that sweater details--------------->
<?php
$sownerid=$_POST['soi1'];
$opic=$_POST['osp1'];
$sweaterid=$_POST['osi1'];
?>
<input type="hidden" name="sweaterownerid" value="<?php echo $sownerid;?>">
<input type="hidden" name="osweaterpic" value="<?php echo $opic;?>">
<input type="hidden" name="osweaterid" value="<?php echo $sweaterid;?>">
<div style="float:right; margin-right:10px;">
<input type="submit" name="next" value="NEXT" class="btn woo_btn btn-primary">
<input type="button" name="cancel" value="CANCEL" class="btn woo_btn btn-primary">
</div>
</form>
</div>
</div>
<div class="clearfix"></div>
<hr>
</div>
you can use in your Ajax like this:
var form = $('#your_form_id');
var formAction = $('#your_form_id').attr('action');
/* Get input values from form */
values = form.serializeArray();
/* Because serializeArray() ignores unset checkboxes and radio buttons: */
values = values.concat(
$('#your_form_id input[type=checkbox]:not(:checked)').map(
function() {
return {
"name": this.name,
"value": this.value
}
}).get()
);
$.ajax({
'ajax code here'
});
or you can check https://api.jquery.com/serialize/
You can achive it though this.
jQuery(document).ready(function($){
$("#your_button_id").on('click', function(e){
e.preventDefault();
$("#your_form_id") .submit();
})
})
Ajax
$("#your_form_id").on('submit', function(e) {
e.preventDefault();
$.post('URL_HERE', $(this).serialize(), function(response) {
console.log(response)
});
});

How to identify which button is pressed and send that to server?

In the while loop I have doctor name, specialist and payment from my database. Each doctor has an <input type="button"> named "did". I want that when I press a button to contact a specific doctor, the value of $row3['did'] will sent to my contact.php page. But I cannot understand where to put it in the <input type="button"> so that I can identify which button is pressed and send its value to contact.php.
while($row3 = mysql_fetch_array($result3))
{
?>
<div class="col_1_of_4 span_1_of_4">
<div class="title-img">
<div class="title"><img src="images/Crystal_Clear_user.gif" alt=""></div>
<!--<div class="title-desc"><p>FACILITY 1</p></div>-->
<div class="clear"></div>
</div>
<h4 class=head>Doctor name: <?php echo $row3['dName'];?></h4>
<p>Specialist: <?php echo $row3['specialist'];?></p>
<p>Payment: <?php echo $row3['payment'];?></p>
<hr>
<div id='contact-form'>
more
<!--<button id="findHelp" class="btn btn-primary"><a href="?did=<?php// echo $row3['did'];?>" >Find help</a></button>-->
<!--<a href="data/contact.php?did=<?php //echo $row3['did'];?>" ></a>-->
<!--<input type='button' name='contact' id='contact' value="Message" class='contact demo btn btn-primary'/>-->
<form method='post' action='contact.php'>
<input type='button' name='did' id='did' value="Message" class='contact demo btn btn-primary'/>
</form>
</div>
<!-- preload the images -->
<div style='display:none'>
<img src='images/loading.gif' alt='' />
</div>
</div>
<?php
}
?>
There is no need to add the form..simply send the id with link when button is clicked and get that id on contact .php page..
OR use as following
<script src="jquery.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$('.contact').click(function(){
var this_rel=$(this).attr('rel');
location.href="contact.php?id="+this_rel;
});
});
</script>
<input type='button' name='did' id='did' value="Message" class='contact demo btn btn-primary' rel="<?php echo $row3['did'];?>"/>
try if(isset($_POST['button_name']) && $_POST['button_name'] === 'button_value')
Use a hidden value inside the form, and assign the doctor details there
<form method="post" action="contact.php">
<input type="hidden" name="thedoctor" value="<?php echo $row3['did'];?>"/>
<input type="button" name="did" id="did" value="Message" class="contact demo btn btn-primary"/>
</form>
And then find the selected button by $button_clicked = $_POST['thedoctor']
This will be your PHP code
<?php
while($row3 = mysql_fetch_array($result3))
{
?>
<div class="col_1_of_4 span_1_of_4">
<div class="title-img">
<div class="title"><img src="images/Crystal_Clear_user.gif" alt=""></div>
<!--<div class="title-desc"><p>FACILITY 1</p></div>-->
<div class="clear"></div>
</div>
<h4 class=head>Doctor name: <?php echo $row3['dName'];?></h4>
<p>Specialist: <?php echo $row3['specialist'];?></p>
<p>Payment: <?php echo $row3['payment'];?></p>
<hr>
<div id='contact-form'>
more
<input type='button' name='did' id='did' value="Message" class='contact demo btn btn-primary' rel="<?php echo $row3['did'];?>"/>
</div>
<!-- preload the images -->
<div style='display:none'>
<img src='images/loading.gif' alt='' />
</div>
</div>
<?php
}
?>
and above that put some jquery code
<script src="jquery.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$('.contact').click(function(){
var this_rel=$(this).attr('rel');
location.href="contact.php?id="+this_rel;
});
});
</script>
Dont forget to write query of database, because that was not in your example, thats why i did not mention that. Also add jquery.js to its appropriate place so jquery code can run. Please do this trick and let me know..
Just use buttons :
HTML
<form method="POST">
<button type="submit" name="btn_action_1" value="abc">Message</button>
<button type="submit" name="btn_action_1" value="def">Message</button>
<button type="submit" name="btn_action_1" value="ghi">Message</button>
<button type="submit" name="btn_action_1" value="jkl">Message</button>
<button type="submit" name="btn_action_2" value="123">Message</button>
<button type="submit" name="btn_action_3" value="456">Message</button>
</form>
PHP
<?php
if(isset($_POST['btn_action_1'])) {
echo 'btn_action_1 was pressed with value: '. $_POST['btn_action_1'];
}
if(isset($_POST['btn_action_2'])) {
echo 'btn_action_2 was pressed with value: '. $_POST['btn_action_2'];
}

Passing Jquery value to PHP form

I have that simple form in a php page:
<form role="form" method="post" action="send-message.php">
<input type="text" id="SendTo" name="SendTo" value="">
<textarea class="form-control text-input" name="Message"></textarea>
<button type="submit" class="btn btn-primary">Send</button>
</form>
The value of SendTo input is set by a JQuery script from the same page:
$("button").click(function() {
$("#SendTo").val($(this).siblings('.username').val());
});
Then I have PHP script in send-message.php:
<?php
$message = $_POST["Message"];
$sendTo = $_POST["SendTo"];
echo $sendTo; //nothing here!
Now, why the value of SendTo is not passing from the form to send-message.php?
It's weird because in the form, I can clearly see the value of the input but it's not passed to send-message.php.
I tried with GET method and it's the same thing...
Thank you for your help!
The missing code:
<?php foreach($mostCompatibleUsers as $otherUser => $score): ?>
<?php $compatibilityScore = getCompatibilityScore($score, $maxScore); ?>
<div class='col-sm-4 col-xs-6'>
<div class='box-info full'>
<div class='img-wrap'>
<img src='images/default-profile-pic.png' alt='Image small'>
</div>
<div class='des-thumbnail'>
<h4><b><?php echo $otherUser; ?></b> <small>Niveau de compatibilité: <b><?php echo $compatibilityScore; ?>%</b></small></h4>
<div class='progress progress-striped active'>
<div class='progress-bar progress-bar-success' role='progressbar' aria-valuenow='<?php echo $compatibilityScore; ?>' aria-valuemin='0' aria-valuemax='100' style='width: <?php echo $compatibilityScore; ?>%'></div>
</div>
<div class='row'>
<div class='col-md-6'>
<input type="hidden" class='username' value="<?php echo $otherUser;?>">
<button type='button' class='btn btn-success btn-sm btn-block' data-toggle='modal' data-target='#myModal'><i class='fa fa-envelope'></i> Send a message</button>
</div>
</div>
</div>
</div>
</div>
<?php endforeach; ?>
More details
As you can see with the last added code, there is a foreach loop that display some users information and a button allow to send a message to that particular user.
When we press a button to send a message, it pops out a modal window containing a form where we can write and send the message. It's not a regular architecture! I think this is not simplifying the situation..
There is no .username class in your code.
By calling $(this).siblings('.username') you are basically just getting the other elements of the form as $(this) is actually the submit button.
Providing more code would be useful. Especially where the .username class is.
$("button").click(function() {
$("#SendTo").val($(this).siblings('.username').val());
$.post( "send-message.php", $( "form" ).serialize() );
});
If you do in fact have an input with a username class, your code would not work anyway because the form will have already submitted by the time you try to read the inputs with javascript.
give your form an id
<form role="form" id="form" method="post" action="send-message.php">
and instead attach to its submit event
$("#form").submit(function(e) {
e.preventDefault(); //prevent the form from submitting
$("#SendTo").val($(this).siblings('.username').val()); //process the inputs
$(this).submit(); // then submit the form
});
First of all, in this case, You have to cancel the default submit of the form when clicking the submit button, the easiest way is to set its type to be button.
Second perform submitting manually using the Jquery as follows:
<form id="myForm" role="form" method="post" action="send-message.php">
<input type="text" id="SendTo" name="SendTo" value="">
<textarea class="form-control text-input" name="Message"></textarea>
<input type="button" id="myButton" value="send">
</form>
<script>
$("#myButton").click(function() {
$("#SendTo").val($(this).siblings('.username').val());
$("#myForm").submit();
});
</script>

Categories