Ajax form submission without refresh "not working" - php

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 .

Related

ajax code not work for 2nd list

my code works fine for the first list. But not work even other list if has more list. Could you please find out what happened with my code.
if I click on signOut it will be add to database and remove form the page with signOut value only. First Div list work,But other will not response anything.
Thank You
Here is my code:
Java Script Code:
$(function() {
$("#add").click(function(){
//Save the link in a variable called element
var element = $(this);
//Find the id of the link that was clicked
var del_id = element.attr("dataid");
var outime = $(this).parents("#list").find("#outtime").val();
//Built a url to send
var info = 'id=' + del_id+ '&singout=' + outime;
$.ajax({
type: "POST",
url: "signOut.php",
data: info,
success: function(){
}
});
// After success
$(this).parents("#list").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
});
});
HTML COde:
<?php
$comments = runQuery($conn, "SELECT * FROM `civ_in_out` WHERE `out_time` = 'null'");
//print_r($comments) ;
if(!empty($comments)) {
foreach($comments as $k=>$v) {
?>
<div id="list">
<div class="form-group">
<div class="form-row">
<div class="col-md-3">
<input class="form-control" type="text" name="name" value="<?php echo $comments[$k]['name']; ?>" disabled>
</div>
<div class="col-md-3">
<input class="form-control" type="time" name="signIn" value="<?php echo $comments[$k]['in_time']; ?>" disabled>
</div>
<div class="col-md-3">
<input class="form-control" id="outtime" type="time" name="singOut">
<input class="form-control" id="id" type="hidden" name="id" value="<?php echo $comments[$k]['id']; ?>">
</div>
<div class="col-md-3">
<a class="btn btn-primary btn-block" dataid="<?php echo $comments[$k]['id']; ?>" id="add" >Sign Out</a>
</div>
</div>
</div>
</div>
<?php
} }
?>
signOut.php
include 'connect.php';
$data=$_POST['serialize'];
echo $id = $data['id'];
echo $outtime = $data['singout'];
$sql = "UPDATE `civ_in_out` SET `out_time`='$outtime' WHERE id = '$id'";
mysqli_query($conn, $sql);
The problem is that you are repeating the list id and all the other element ids, so the jQuery call and event binding will always refer to the first id found on the HTML.
Id’s must be unique on you html.
You can change your code to use a class name for example:
$(function() {
$(".add").click(function(){
//Save the link in a variable called element
var element = $(this);
//Find the id of the link that was clicked
var del_id = element.attr("dataid");
var outime = $(this).parents(".list").find(".outtime").val();
//Built a url to send
var info = 'id=' + del_id+ '&singout=' + outime;
$.ajax({
type: "POST",
url: "signOut.php",
data: info,
success: function(){}
});
// After success
$(this).parents(".list").animate({ backgroundColor: "#fbc7c7" }, "fast").animate({ opacity: "hide" }, "slow");
});
});
HTML/PHP:
<?php
$comments = runQuery($conn, "SELECT * FROM `civ_in_out` WHERE `out_time` = 'null'");
//print_r($comments) ;
if(!empty($comments)) {
foreach($comments as $k=>$v) {
?>
<div class="list">
<div class="form-group">
<div class="form-row">
<div class="col-md-3">
<input class="form-control" type="text" name="name[]" value="<?php echo $comments[$k]['name']; ?>" disabled>
</div>
<div class="col-md-3">
<input class="form-control" type="time" name="signIn[]" value="<?php echo $comments[$k]['in_time']; ?>" disabled>
</div>
<div class="col-md-3">
<input class="form-control outtime" id="outtime-<?=$k?>" type="time" name="singOut[]">
<input class="form-control" id="id-<?=$k?>" type="hidden" name="id[]" value="<?php echo $comments[$k]['id']; ?>">
</div>
<div class="col-md-3">
<a class="btn btn-primary btn-block add" dataid="<?php echo $comments[$k]['id']; ?>>Sign Out</a>
</div>
</div>
</div>
</div>
<?php
} }
?>
You can change $("#add").click(function() to $(document).on('click', '#add', function()

make sure at least one radio button is checked before submission

heres something that has bothered me for a while,i have several dynamically generated forms each with two radio buttons and a submit button,now the problem is that each time i submit a radio button selection,on click event is not fully consumed until another on change event happens,meaning that if the next form doesnt detect an onchange event on the radio buttons it uses the previous event
and produces a value(of the previous submitted radio button) even if no selection is made..
Check the code below,thanks
$(function(){
var pName;
var selectedValue;
var checked;
$(".sel1").on('change',function(){
$checked=$(this);
alert($checked.val());
});
$(".submit_btn").on('click',function(event){
event.preventDefault();
var $this=$(this);
var $cat_id=$this.data('uid');
alert($selectedValue);
$.ajax({
url:"vote.php",
method:"get",
data:"cat_id="+$cat_id+"&hisId="+$selectedValue,
success:function(result){
alert(result);
}
})
});
});
php code
<?php
}else{
?>
<div class="col-md-4 col-lg-4 col-sm-4 col-xsm-4 col-xxl-4 mt-4">
<div class="cat_holder">
<form action="" class="ml-4">
<div class="form-group">
<label for=".sel1" class="cat_name"><?php echo $catNames; ?></label><br>
<?php
foreach($player_id as $real_player_id){
$player_name=$caller->getPlayerNames($real_player_id);
?>
<input class="text_style sel1" type="radio" name="id" value="<?php echo $real_player_id;?>"> <?php echo $player_name;?><br>
<?php
}
?>
</select>
</div>
<div class="form-row">
<div class="col-md-6 col-lg-6 col-sm-6 col-xsm-6 col-xxl-6">
<input type="submit" value="Vote" class="btn btn-primary btn-block submit_btn" data-uid="<?php echo $realcatIds;?>">
</div>
</div>
</form>
</div>
</div>

How to get input hidden value from multiple forms?

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'));
});

ajax return data using bootstrap modal can't get parameter inside modal

I want to submit a data parameter using PHP Codeigniter that comes from ajax return data, but when I submit the form, I can't get this parameter.
HTML :
<a href="#myModalBiaya" class="trash" role="button" data-toggle="modal">
<button class="btn btn-success btn-sm" name="pdetailbiaya" value="Detail Biaya" >Detail Biaya</button>
</a>
JS :
$('#myModalBiaya').on('shown.bs.modal', function(e) {
po_id = $('#po_id').val();
$.ajax({
type: 'post',
url: '<?php echo base_url();?>admin/po_trans_receive_po/getBiaya',
data:'po_id='+po_id,
success: function(data){
$("#myModalBiaya .tdata").html(data);
}
});
});
Modal :
...
<div class="modal-body">
<div class="panel panel-default" >
<div class="panel-heading">
<div class="form-horizontal tdata" >
<div class="form-group" >
<label class='col-md-3 control-label' for='menu_name'>Biaya PPN </label>
<div class='col-md-8'>
<input type="text" name="po_biaya_ppn" id="po_biaya_ppn" readonly onkeyup="getTotalBiaya()"class="form-control text-right" value="0">
</div>
</div>
...
PHP :
function getBiaya()
{
$po_id = $this->input->post('po_id');
$resultPO = $this->md_po_trans_po->getID($po_id);
if ($resultPO) {
$resultotal = $resultPO->po_biaya_ppn+$resultPO->po_ongkos_angkut+$resultPO->po_biaya_asuransi+$resultPO->po_biaya_materai;
echo ' <div class="form-group" > ';
echo ' <label class="col-md-3 control-label">Biaya PPN </label> ';
echo ' <div class="col-md-8"> ';
echo ' <input type="text" name="po_biaya_ppn" id="po_biaya_ppn" readonly onkeyup="getTotalBiaya()" class="form-control text-right" value="'.$resultPO->po_biaya_ppn.'"> ';
echo ' </div> ';
echo ' </div> ';
}
Everything works unless the input parameter po_biaya_ppn is blank when I submit this form. When I print_r($this->input->post('po_biaya_ppn'));die(); this is returned blank.
Regards,
Thank You
Replace
data:'po_id='+po_id,
with
var form_data = {
po_id : po_id,
};
data:form_data,

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)
});
});

Categories