insert query with ajax without reloading whole page - javascript

I want to insert data through AJAX (without reload page). I tried but it is not showing data and also reload page.
I have a file first.php (in which, form is present), a AJAX code and a firstcall.php where query will be execute.
My first.php (html form) is:
<form class="reservation-form mb-0" action="" method="post" autocomplete="off">
<input name="name1" id="name1" class="form-control" type="text" placeholder="Enter Name" required aria-required="true">
<input name="age" id="age" class="form-control" required type="number" placeholder="Enter Age" aria-required="true">
<input type="checkbox" id="checkbox" class="checkbox1" name="namec[]" value="<?php echo $value['id']; ?>" >
<input type="submit" class="pull-right btn btn-warning" value="Submit" id="submit">
</form>
Here data should be display:
<div class="col-md-5">
<div class="panel panel-primary" id="showdata">
</div>
</div>
AJAX is:
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var name1 = $("#name1").val();
var age = $("#age").val();
var chkArray=[];
$('.checkbox1:checked').each( function() {
chkArray.push($(this).val());
} );
var selected;
selected = chkArray.join(',') ;
if(selected.length > 1){
$.ajax( {
url:'firstcall.php',
type:'POST',
data:{name1: name1,age: age,namec: chkArray},
}).done(function(data){
$("#showdata").html(data);
});
}
else{
alert("Please at least one of the checkbox");
}
}
}
</script>
firstcall.php is:
<div class="panel panel-primary" id="showdata">
<?php
foreach($_POST['namec'] as $selected){
echo $selected;
$_SESSION['name1']=$_POST["name1"];
$_SESSION['age']=$_POST["age"];
echo $name1=$_SESSION['name1'];
echo $age=$_SESSION['age'];
$query=mysql_query("insert into patient_details (p_name,p_age,g_number) values ('$name1','$age','$selected')") or die(mysql_error());
}
?>

After $("#submit").click(function(event){ add command
event.preventDefault();
And your page will not be reloaded

The submit button will automatically reload the page on click so the solution is either change the button type to button or add preventDefault to the click event
$("#submit1,#submit2").click(function() {
alert('form submited')
})
$("#submit3").click(function(e) {
e.preventDefault();
alert('form submited')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
this will reload the page
<input type="submit" class="pull-right btn btn-warning" value="Submit" id="submit1">
</form>
<form>
this will not reload the page
<input type="button" value="Submit" id="submit2">
</form>
<form>
this will not reload the page
<input type="submit" value="Submit" id="submit3">
</form>

Related

storing ID in hidden field

I have a script here right now that will display(alert) me the ID from the reaction and the First Name and Last Name. Now I need it that when I press this button it will store the ID in a hidden form input so it will send it to the database.
Script that alerts the data:
<script type="text/javascript">
function printIt(id){
alert(document.getElementById(id).value);
alert(document.getElementById('naam'+id).value);
}
</script>
<form name="formName">
<input type=hidden id="'.$reactie['id'].'" name="abcName" value="'.$reactie['id'] .'"/>
<input type=hidden id="naam'.$reactie['id'].'" name="abcName" value="Reactie op bericht van '.$reactie['voornaam'].' ' .$reactie['achternaam'] .'"/>
<input class="btn btn-primary btn-xs" type=button value="Reageer" onclick="printIt(\''.$reactie['id'] .'\')" />
</form>
Script that sends the form (where the ID needs to be added) to the database:
<?php if(isset($_POST['react_btn'])){ unset($q1); $q1['reactie'] = $app->check_string($_POST['reactie']);
$q1['topic_id'] = $app->check_string($_POST['topicid']);
$q1['klant_id'] = $app->check_string($_POST['klantid']);
$q1['ledenpagina_id'] = $app->check_string($_POST['ledenpaginaid']);
$app->insert_query('reacties', $q1, 'id');
}
?>
<form action="" method="post"> <div class="form-group">
<label for="comment">Reactie:</label>
<textarea class="form-control" name="reactie" rows="3" id="comment"></textarea>
<input type="hidden" name="klantid" value="<?php echo $_SESSION["klant_id"] ?>"> <input type="hidden" name="topicid" value="<?php echo $actieftopicid ?>">
<input type="hidden" name="ledenpaginaid" value="<?php echo $_SESSION["ledenpagina_id"]; ?>">
<input type="hidden" name="onderreactieID" value="<?php echo $reactie; ?>">
<button type="submit" name="react_btn" class="btn btn-primary">Plaats reactie</button>
</div>
</form>
Summary:
I need the data from the first script ($reactie['id']) when you press the button to fill that in some hidden field. That field needs to go to the database.
So it needs to set that javascript in a hidden field somehow. And when you didnt press anybuttons it needs to be a default 0.
Set <input type="hidden" value="0"/> and when no button pressed you get 0 from hidden input(click on Check Value button to see it)
And 'when a button is pressed'(SetID ! button) will set the given id.
it follows:
function setID(iD){
var hidden_input = document.getElementById('my_hidden_input');
hidden_input.value = iD;
alert('The ID given from button is "' + iD + '".');
alert('The new value of my_hidden_input is "' + hidden_input.value + '".');
}
function check(){
alert('The value of my_hidden_input is "' + document.getElementById('my_hidden_input').value + '".');
}
<form>
<input type="hidden" id="my_hidden_input" value="0"/>
<input type="button" value="SetID !" onclick="setID('MyID')" />
<input type="button" value="Check Value" onclick="check()" />
</form>
You should already have a hidden input ready if you otherwise want to set reactieID to 0. You can set the value with javaScript on click event.
console.log("Value of hidden input reactieID = " + document.getElementById('reactieHier').value);
<form name="formName">
<input class="btn btn-primary btn-xs" type=button value="Reageer" onclick="document.getElementById(
'reactieHier').value = '5'; console.log('Value of hidden input reactieID = ' + document.getElementById('reactieHier').value)" />
</form>
<form>
<div class="form-group">
<label for="comment">Reactie:</label>
<textarea class="form-control" name="reactie" rows="3" id="comment"></textarea>
<input type="hidden" name="klantid" value="99">
<input type="hidden" name="topicid" value="99">
<input type="hidden" name="ledenpaginaid" value="99">
<input type="hidden" name="onderreactieID" value="99">
<input type="hidden" name="reactieID" id="reactieHier" value="0">
<button type="submit" name="react_btn" class="btn btn-primary">Plaats reactie</button>
</div>
</form>

How to submit a bootstrap form with 'required' elements with onClick button

The reasons are:
The submit button is outside the </form>
I need to use bootstrap as a form validation with required fields
But, when I submit the form with onClick. It's just submit the form without checking - even it's blank.
$('#submit').on('click',function(){
$('#billing-form').submit();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="clearfix" id="billing-form" method="post">
<!-- NAME -->
<div class="col-md-6">
<input class="form-control" type="text" name="name" required/>
</div>
.
.
.
</form>
//coupon
<input type="text" name="coupon" />
<button type="button" id="submit">Buy now!</button>
I've got it.
$("#submit").on("click", function(){
if($("#billing-form")[0].checkValidity()) {
//do ajax submit
}
else {
$("#billing-form")[0].reportValidity();
}
});
You can use checkValidity method. It will return true/false depending on whether the form is valid or not
$('#submit').on('click', function(e) {
var x = document.getElementById('billing-form').checkValidity();
if (x) {
$('#billing-form').submit();
} else {
console.log('Not Valid')
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="clearfix" id="billing-form" method="post">
<!-- NAME -->
<div class="col-md-6">
<input class="form-control" type="text" name="name" required/>
</div>
</form>
<input type="text" name="coupon" />
<button type="button" id="submit">Buy now!</button>

Show/hide forms based on button id

I am trying to build a button for each form; when the users click on it, the specific form with the specific id will show or hide again.
I already tried the below JavaScript code, but it doesn't work.
Is this code wrong or do I miss something? Does someone have another idea?
Thanks in advance.
$(function(){
$('.btn').on('click', function(e){
e.preventDefault();
$(this).next('.form2').show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
$result_posts = $conn -> prepare("SELECT * FROM posts WHERE post_topic=:post_topic ORDER BY DATE(post_date) ASC");
$result_posts -> bindParam(':post_topic',$topic_id);
$result_posts -> execute();
while ($row2 = $result_posts ->fetch(PDO::FETCH_ASSOC))
{
?>
<a class="btn" id="<?php echo $row2['post_id']; ?>"><i class="fa fa-commenting" aria-hidden="true"></i>Comment</a>
<form name="form2" class="form2" id=" <?php echo $row2['post_id']; ?>" style="display:none">
<textarea class="commenting" id="commenting" placeholder="Comment here..." cols="30" rows="5"></textarea>
<input type="submit" class="comment_submit2" value="Submit" >
</form>
<?php } ?>
need to use toggle():-
Working example:-
$(function(){
$(document).on('click', '.btn',function(e) {
e.preventDefault();
$(this).next('.form2').toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="btn"><i class="fa fa-commenting" aria-hidden="true"></i>Comment</a>
<form name="form2" class="form2" style="display:none">
<textarea class="commenting" id="commenting" placeholder="Comment here..." cols="30" rows="5"></textarea>
<input type="submit" class="comment_submit2" value="Submit" >
</form>
<br>
<br>
<a class="btn"><i class="fa fa-commenting" aria-hidden="true"></i>Comment</a>
<form name="form2" class="form2" style="display:none">
<textarea class="commenting" id="commenting" placeholder="Comment here..." cols="30" rows="5"></textarea>
<input type="submit" class="comment_submit2" value="Submit" >
</form>
Note:- take care that no id will repeat in any case(in your code it's happening for button id and it's corresponding form id).
I had removed id's from button as well as from forms in my code . (if needed then try to make them different for each one )
Here is an example with jQuery, showing more than one form. The first form content shows by default.
$(function(){
$('.btn').on('click', function(e){
e.preventDefault();
$("form").css("display","none");
var TargetDiv = $(this).attr("data-target");
$("#" + TargetDiv).show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn" data-target="form1">Form 1</button>
<button class="btn" data-target="form2">Form 2</button>
<button class="btn" data-target="form3">Form 3</button>
<form id="form1" style="display: block;">
<label>show form one content by default</label>
</form>
<form id="form2" style="display: none;">
<label>form two content</label>
</form>
<form id="form3" style="display: none;">
<label>form three content</label>
</form>
first of all, you should not repeate the ID in same document. I can notice you will have button and form id same.
So what you can do concat some string with post_id like for button
"btn_" + post_id
and for post something like -
"form_" + post_id
use the toggel so it will inverse the state of form on each click. If hidden it will be visible, and if visible on click it will be hidden.
Check my fiddle.
https://jsfiddle.net/stdeepak22/crrwa7Ls/

validation not working when i am trying to prevent multiple click on submit

i have used class='required' for required validation which is working fine when i remove onClick="this.form.submit(); this.disabled=true;
from submit button.
i want to disable multi click with validation
<form action="<?php echo $this->url('weeklyplan', array('action' => 'add')); ?>" method="post" id='myform'>
<div class="mainformdiv">
<div class= "formelementblock">
<div class="formelement">
<select name="txtdefined_week_id" id="txtdefined_week_id" class="select-block required" onchange="showdateranges()">
<option value="">Select Defined Week</option>
<?php foreach ($definedweeks as $obj) { ?>
<option value="<?php echo $obj->defined_week_id; ?>"><?php echo $obj->start_day . "-" . $obj->end_day; ?></option>
<?php } ?>
</select>
</div>
</div>
<div class= "formelementblock">
<div class="formelement">
<input type="text" readonly="readonly" name="txtstart_date" class="input-text datepickerwidth required" id="txtstart_date" placeholder="Start Date*"/>
</div>
</div>
<div class= "formelementblock last">
<div class="formelement">
<input type="text" readonly="readonly" name="txtend_date" class="input-text datepickerwidth required" id="txtend_date" placeholder="End Date*"/>
</div>
</div>
</div>
<div class="clear"></div>
<div class="form-button">
<div class="button-block">
<input onClick="this.form.submit(); this.disabled=true;" class="button" type="submit" name="button" id="button" value="Save" />
<input class="button" type="button" name="button" id="button" value="Cancel" onclick="window.location = '<?php echo $this->url('weeklyplan', array('action' => 'index')); ?>'" />
</div>
</div>
</form>
$(document).ready(function() {
$("#button").click(function(){
$('#button').attr('disabled',true);
$('#myform').submit();
var no=$("#myform").validate().toShow.length;
if(no!=0){
$('#button').attr('disabled',false);
}
});
});
You are using html5 form validation. If you want to check if the inputs are valid before submit you have to change the:
<input onClick="this.form.submit(); this.disabled=true;" class="button" type="submit" name="button" id="button" value="Save" />
To something like:
<input onClick="checkform(); this.disabled=true;" class="button" type="button" name="button" id="button" value="Save" />
Notice that the button is not a 'submit' type but rather a normal button. With this you can create a javascript function ("checkform()") that checks if the inputs are valid. There is a function in javascript that returns whether an input with the 'required' html5 attribute is valid. This function is:
inputElement.checkValidity()
After you checked if all inputs are valid you can submit the form.

how to make text area and img tags read only after clicking submit button

<form method="post" enctype="multipart/form-data" action="">
<div class="prp_div">
<div id="img_div1">
<?php
include_once('config.php');
$disp=mysql_query("select * from pop") ;
$out = mysql_fetch_array($disp);
?>
<img src="<?php echo $out[3];?>" style="width:100%; height:100%" />
</div>
<div id="comment_left">
<b>Graphic Text:</b><br/>
<textarea rows="4" cols="50" id="gtext" name="gtext" placeholder="Enter Graphic Text..." class="input" >
<?php echo $out['gtext']; ?>
</textarea><br/>
<b>Caption:</b><br/>
<textarea rows="4" cols="50" id="caption" name="caption" placeholder="Enter Caption..." class="input">
<?php echo $out['caption']; ?>
</textarea>
<input type="file" name="file">
<input type="submit" name="submit" value="save">
I have a form that contains one image tag in a div and two text areas.Once i enter the data and press the submit button i want these fields to be read only..can anyone help me on this task.
use a php variable.
<?php
$isSubmitted = false;
if (!empty($_POST))//checks request
$isSubmitted = true;
?>
<!--on your textarea-->
<textarea rows="4" cols="50" id="caption" name="caption" placeholder="Enter Caption..." class="input"
<?php
echo $isSubmitted== true? 'disabled' : '' //add 'disabled' tag in element if isSubmitted is true
?>
><?php echo $out['caption']; ?></textarea>
sorry if my code is a bit dirty.
EDIT
this alone might work.
<!--on your textarea-->
<textarea rows="4" cols="50" id="caption" name="caption" placeholder="Enter Caption..." class="input"
<?php
echo !empty($out['caption'])? 'disabled' : '' //add 'disabled' tag in element if $out['caption'] is not empty
?>
><?php echo $out['caption']; ?></textarea>
This will the button:
<button onclick = "disableFields()" type="submit" name="submit" value="SAVE"> </button>
This will be your javascript:
function disableFields(){
document.getElementById('gtext').disable;
document.getElementById('caption').disable;
}
Try this....
<input type="button" class="buttonclass" name="submit" value="save">
$(".buttonclass").click(function(){
$(".input").attr('readonly', true);
});
A more user-friendly way :
$(".buttonclass").click(function(){
$(".input").attr('disabled', true);
});
You can do it by following way
<form method="post" enctype="multipart/form-data" action="" onSubmit="makeReadOnly();">
......
......
......
</form>
<script>
function makeReadOnly()
{
$('#gtext').attr('readOnly', true);
$('#caption').attr('readOnly', true);
}
</script>
Use disable function on the elements you wanted.
My suggestion is to give a class name like "toReadOnly" to those particular elements and then getElementsByClassName and disable those elements.
<script>
function onyourRequirement()
{
var elements = document.getElementsByClassName("toReadOnly")
for(element : elements)
element.disable
}
</script>
<form method="post" enctype="multipart/form-data" action="" onSubmit="dsiableAllInputs();">
Call following code on submission of form
function dsiableAllInputs(){
jQuery(":input").prop('disabled', true);
jQuery(":textarea").prop('disabled', true);
}
My Bad, Use this
<form action="demo_form.asp" onsubmit="myFunction()">
<textarea rows="4" cols="50" id="gtext" name="gtext"
placeholder="Enter Graphic Text..." class="input" >
aaass
</textarea><br/>
<textarea rows="4" cols="50" id="caption" name="caption"
placeholder="Enter Caption..." class="input"> </textarea>
<input type="submit" value="Submit">
</form>
<script>
function myFunction() {
alert("The form was submitted");
document.getElementById('gtext').disabled = true;
document.getElementById('caption').disabled = true;
}
</script>

Categories

Resources