Run function when pressing button and insert into form - php

So I have this form, where I want to add a button which makes a function run.
This is how my form looks like:
<form action="" method="POST">
CVR-nummer:<br>
<input name="cvr" id="cvr" type="text" value="" size="30"/> <button onclick="<?php getinfo(); ?>">Run the function</button><br>
Navn:<br>
<input name="navn" type="text" value="<?php if(isset($navn)) {echo $navn;} ?>" size="30"/><br>
Adresse:<br>
<input name="adresse" type="text" value="<?php if(isset($adresse)) {echo $adresse;} ?>" size="30"/><br>
Postnummer:<br>
<input name="postnr" type="text" value="<?php if(isset($postnr)) {echo $postnr;} ?>" size="30"/><br>
By:<br>
<input name="by" type="text" value="<?php if(isset($by)) {echo $by;} ?>" size="30"/><br>
<input type="submit" value="Registrer"/>
</form>
And this is my function which uses an API
<?php
function getinfo() {
$cvr = "12345678";
$api = json_decode(file_get_contents("http://cvrapi.dk/{$cvr}/"),true);
$navn = $api['navn'];
$adresse = $api['adresse'];
$postnr = $api['postnr'];
$by = $api['by'];
}
?>
When I click the button I want it to:
1. Get value of the cvr-field.
2. Validate cvr-field so it has exactly 8 numbers.
3. If validation OK it must set the variables.
4. The variables must be shown in the form.
Any thoughts on how to do this?
UPDATE
<script type="text/javascript">
function checkCVR()
{
var cvr = document.getElementById("cvr").value;
var reg = new RegExp("^[0-9]{8}$");
if(!reg.test(cvr))
{
document.getElementById("cvr_error").style.display = 'block';
document.getElementById("cvr_error").innerHTML = "CVR Error!";
}
else
{
document.getElementById("cvr_error").style.display = 'none';
// var url = "http://cvrapi.dk/"+cvr+"/";
// var url = "http://haxify.org/result.php";
var url = "json.txt";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var json = JSON.parse(xmlhttp.responseText);
document.getElementById("navn").value = json["navn"];
document.getElementById("adresse").value = json["adresse"];
document.getElementById("postnr").value = json["postnr"];
document.getElementById("by").value = json["by"];
}
};
xmlhttp.send(null);
}
}
</script>
<form action="" method="POST">
CVR-nummer:<br>
<input name="cvr" id="cvr" type="text" value="" size="30"/>
<input type="button" onClick="checkCVR()" value="Run the function" /><br />
<span id="cvr_error" style="color:red;display:none;"></span>
Navn:<br />
<input name="navn" id="navn" type="text" value="" size="30"/><br />
Adresse:<br />
<input name="adresse" id="adresse" type="text" value="" size="30"/><br />
Postnummer:<br />
<input name="postnr" id="postnr" type="text" value="" size="30"/><br />
By:<br />
<input name="by" id="by" type="text" value="" size="30"/><br />
<input type="submit" value="Registrer"/>
</form>
This one actually works on one website but does not work on my own site. Is there any requirements for any software or something, or what can be the reaseon for this to not work on my specific website?
Test:
http://haxify.org/form_v4.php

Related

enable submit button if all fields filled [duplicate]

This question already has answers here:
Disabling submit button until all fields have values
(11 answers)
Enable submit button only when all fields are filled
(5 answers)
Disable Submit button until Input fields filled in
(7 answers)
Closed 5 years ago.
I have a form
<form>
Username<br />
<input type="text" id="user_input" name="username" /><br />
Password<br />
<input type="password" id="pass_input" name="password" /><br />
Confirm Password<br />
<input type="password" id="v_pass_input" name="v_password" /><br />
Email<br />
<input type="text" id="email" name="email" /><br /> <br/>
<textarea name="adress" id="adress" ></textarea>
<br>
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female<br>
<input type="submit" id="register" value="Register" disabled="disabled" />
</form>
I want to disable my submit button until all the fields have values.Now everything is okay except radio button.
JS:
<script>
(function() {
$('form > input,textarea,radio').keyup(function() {
var empty = false;
$('form > input,textarea,radio').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
})()
</script>
I don't know whether this is good code or not.I am totally new to jquery so please correct me i had make anything wrong.
I want to disable my submit button until all the fields have values including radio button..Please help me.Thanks in advance
You can check if a radio button is checked or not using:
if (!$("input[name='gender']:checked").val()) {
alert('Nothing is checked!');
} else {
alert('One is checked');
}
You need to use prop() and check the type. If the type is radio, you can add validation checks:
required = function(fields) {
var valid = true;
fields.each(function() { // iterate all
var $this = $(this);
if ((($this.is(':text') || $this.is('textarea')) && !$this.val()) || // text and textarea
($this.is(':radio') && !$('input[name=' + $this.attr("name") + ']:checked').length)) { // radio
valid = false;
}
});
return valid;
}
validateRealTime = function() {
var fields = $("form :input");
fields.on('keyup change keypress blur', function() {
if (required(fields)) {
{
$("#register").prop('disabled', false);
}
} else {
{
$("#register").prop('disabled', true);
}
}
});
}
validateRealTime();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Username<br />
<input type="text" id="user_input" name="username" /><br /> Password
<br />
<input type="password" id="pass_input" name="password" /><br /> Confirm Password<br />
<input type="password" id="v_pass_input" name="v_password" /><br /> Email
<br />
<input type="text" id="email" name="email" /><br /> <br/>
<textarea name="adress" id="adress"></textarea>
<br>
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female<br>
<input type="submit" id="register" value="Register" disabled="disabled" />
</form>

javascript form validation using php

checkEmpty validation is not working. functions are not executing in the PHP file. I tried below code please help me to understand where I am wrong.
My Code in my index.php file.
<div class="main_wrapper">
<form name="myform" method="post" action="test1.php">
<div class="head_wrapper">
Rollno : <input type="text" name="id" onblur="checkEmpty('id')" value="<?php echo $id; ?>"/></br></br>
Name : <input type="text" name="name" onblur="checkEmpty('name')" value="
<?php echo $name; ?>"/></br></br>
Email : <input type="text" name="email" onblur="checkEmpty('email')"
value="<?php echo $email; ?>"/></br></br>
Phone : <input type="number" name="phone" onblur="checkEmpty('phone')"
value="<?php echo $phone; ?>"/></br></br>
Address : <input type="text" name="address" onblur="checkEmpty('address')"
value="<?php echo $address; ?>"/></br></br>
Dept_code: <input type="text" name="dept_code"
onblur="checkEmpty('dept_code')" value="<?php echo $dept_code; ?>"/></br>
</br>
</div>
<div class="foot_wrapper">
<input type="submit" name="insert" value="Addinfo"/>
<input type="submit" name="update" value="Modify"/>
<input type="submit" name="delete" value="Delete"/>
<input type="submit" name="search" value="Find"/>
<input type="submit" name="display" value="Display"/>
</div>
</form>
</div>
</body>
<script src="validation.js">
function checkEmpty(field)
{
var fn = document.getElementById(field).value;
if (fn == "" || fn = null)
{
alert("Fill the box");
}
}
function validEmail(email)
{
var fn = document.getElementById(email).value;
var format = /.+#.+/;
if (!fn.match(format))
{
alert("Enter valid mail");
}
}
</script>
First: you need to put id on your input tags if you gonna use the getElementById
<input type="text" name="id" onblur="checkEmpty('id')" value="<?php echo $id; ?>" id="id" /> //it is better to use id the same as the name
Second: inside the checkEmpty function you need to fix the
if(fn==""||fn=null) //change the fn=null to fn == null
{
alert("Fill the box");
}
third: I wouldn't recommend using the alert("Fill the box") because you are using the onblur method, once you try to skip the field for id/Rollno
1. The focus will be on the next input which is for the 'Name'.
2. The alert will be triggered and will say to 'fill the box' for the 'Rollno'
3. Once the alert shows, it will also trigger the onblur method for the 'Name'
4.Then it will loop showing the alert
I would recommend to put a hidden span that will act as an alert to the user, which will show if the user left the field blank
<input type="text" name="id" onblur="checkEmpty('id')" value="" id="id"/><span id="alertForId" hidden="" class="alerts">Fill the this field first.</span></br></br>
and your checkEmpty function will somehow look like:
function checkEmpty(field)
{
console.log(field);
var fn=document.getElementById(field).value;
if(fn==""||fn==null)
{
if(field == "id")
{
$("#alertForId").show();
}
}else $(".alerts").hide();
}
I put a class 'alerts' to the span to hide them in case the field is not empty, but it will hide all the spans. Just try to configure the code an hope it will help you.
Here is the code configured based from your code:
<div class="main_wrapper">
<form name="myform" method="post" action="index.php">
<div class="head_wrapper">
Rollno : <input type="text" name="id" id="id" onblur="checkEmpty('id')" value=""/><span id="alertForId" class="alerts" hidden="">Fill the this field first.</span></br></br>
Name : <input type="text" name="name" id="name" onblur="checkEmpty('name')" value=""/><span id="alertForName" class="alerts" hidden="">Fill the this field first.</span></br></br>
Email : <input type="text" name="email" id="email" onblur="checkEmpty('email')" value=""/><span id="alertForEmail" class="alerts" hidden="">Fill the this field first.</span></br></br>
Phone : <input type="number" name="phone" id="phone" onblur="checkEmpty('phone')" value=""/><span id="alertForPhone" class="alerts" hidden="">Fill the this field first.</span></br></br>
Address : <input type="text" name="address" id="address" onblur="checkEmpty('address')" value=""/><span id="alertForAddress" class="alerts" hidden="">Fill the this field first.</span></br></br>
Dept_code: <input type="text" name="dept_code" id="dept_code" onblur="checkEmpty('dept_code')" value=""/><span id="alertForIdDeptCode" class="alerts" hidden="">Fill the this field first.</span></br>
</br>
</div>
<div class="foot_wrapper">
<input type="submit" name="insert" value="Addinfo"/>
<input type="submit" name="update" value="Modify"/>
<input type="submit" name="delete" value="Delete"/>
<input type="submit" name="search" value="Find"/>
<input type="submit" name="display" value="Display"/>
</div>
</form>
</div>
<script type="text/javascript" src="../jquery.js"></script>
<script type="text/javascript">
// validation.js is here
//validation
function checkEmpty(field)
{
var fn=document.getElementById(field).value;
if(fn==""||fn==null)
{
if(field == "id")
$("#alertForId").show();
if(field == "name")
$("#alertForName").show();
if(field == "email")
$("#alertForEmail").show();
if(field == "phone")
$("#alertForPhone").show();
if(field == "address")
$("#alertForAddress").show();
if(field == "dept_code")
$("#alertForIdDeptCode").show();
} else{
if(field == "id")
$("#alertForId").hide();
if(field == "name")
$("#alertForName").hide();
if(field == "email")
$("#alertForEmail").hide();
if(field == "phone")
$("#alertForPhone").hide();
if(field == "address")
$("#alertForAddress").hide();
if(field == "dept_code")
$("#alertForIdDeptCode").hide();
}
}
function validEmail(email)
{
var fn=document.getElementById(email).value;
var format=/.+#.+/;
if(!fn.match(format))
{
alert("Enter valid mail");
}
}
</script>
</body>'
changes I made:
I just put your javascript inside the same page
Just link a jquery.js

insert multiple rows to database

i have multiple rows insertion, so, i want to insert them into database.
i am trying to use loop function to send them to a table; but not success. Please anyone help with this?
//Adding New Line Item Function
var i = 1;
function AddNew(){
if (i <=3){ //if you don't want limit, you remove IF condition
i++;
var div= document.createElement('div');
div.innerHTML = '<input type="text" value="'+i+'" name="lineitem_'+i+'" maxlength="2" size="2"> <input type="text" name="materialcode_'+i+'" placeholder="Material Code" maxlength="18" size="18"> <input type="text" name="qty_'+i+'" placeholder="Quantity" maxlength="10" size="10"> <input type="text" name="price_'+i+'" placeholder="Price" maxlength="10" size="10"> <input type="button" onclick="removeItem(this)" value="-">';
document.getElementById('addingitem').appendChild(div);
}
}
function removeItem(div){
//document.getElementById('addingitem').removeChild(div.parentNode);
i--;
var addingitem = document.getElementById('addingitem');
addingitem.removeChild(div.parentNode);
var inputs = addingitem.querySelectorAll('[name^="lineitem_"]');
for (var r = 0; r < inputs.length; r++)
{
var item = inputs[r];
item.value = r + 1;
}
inputs = null;
}
//Validate Number Key
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode
return !(charCode > 31 && (charCode < 48 || charCode > 57));
}
<form method="post" action="make_order.php">
<!--Adding item-->
Item Detail:
<br />
<div id="addingitem">
<input type="text" name="lineitem_1" id="item" value="1" maxlength="2" size="2">
<input type="text" name="materialcode_1" placeholder="Material Code" maxlength="18" size="18">
<input type="text" name="qty_1" placeholder="Quantity" maxlength="10" size="10">
<input type="text" name="price_1" placeholder="Price" maxlength="10" size="10">
<input type="button" name="addnew" id="Add_New()" onClick="AddNew()" value="New Item">
</div>
<br />
<input type="submit" name="makeorder" value="Make Order">
</form>

Getting a value from dynamically created textbox through php

I have n number of text box (n may be any number) with same name. And
I want to access the value of all the text box of that name.
Ex-:
<form method="post" id="create">
<input type="text" name="user[]" />
<input type="text" name="user[]" />
<input type="text" name="user[]" />
<input type="button" id="newFieldBtn"/>
<input type="submit" name="save" value="save"/>
</form>
jQuery
<script>
jQuery(document).ready(function($) {
$('#newFieldBtn').click(function(){
var code='<input type="text" name="user[]" />';
jQuery('#create').append(code);
</script>
or is there any other way to access the value of the text box. Either
by class or any other property..
<script>
jQuery(document).ready(function($) {
$('#newFieldBtn').click(function(){
var count = document.getElementById('count').value;
count++;
var code = '<input type="text" name="user'+count+'" />';
jQuery('#create').append(code);
document.getElementById('count').value = count;
</script>
and your html like...
<form method="post" id="create">
<input type="hidden" id="count" value="0" name="count">
<input type="button" id="newFieldBtn"/>
<input type="submit" name="save" value="save"/>
</form>
and in your php code...
<?php
if(isset($_POST))
{
$count = $_POST['count'];
for($i=1;$i<=$count;$i++)
{
$user.$i = $_POST['user'.$i];
}
}
?>
Try this one, it will show you the values :
<form action="#" method="post">
<input type="text" name="user[]" />
<input type="text" name="user[]" />
<input type="text" name="user[]" />
<input type="submit" value="submit" >
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
foreach($_POST['user'] as $key => $value)
{
echo $key." has the value = ". $value."<br>";
}
}
?>
See this in action: http://wistudat.be/try/array.php

Submit several forms with one button and store variables in MySQL

I am currently learning forms and Ajax posting without a page refresh. I have tree forms and one submit button. I have assigned php variables to each input field that will take the value of what’s typed in. The value is echoed for each input box. Is it possible to submit all three forms at the same time? And if yes, how would I submit these values to a MySQL database after the button click?
Ajax:
function() {
$.ajax({
type: "POST",
url: "posting.php",
data: {
"name": $("#name").val(),
"age": $("#age").val(),
"phone": $("#phone").val(),
"email": $("#email").val(),
"job": $("#job").val(),
"hobby": $("#hobby").val(),
},
success: function(data) {
$("#inputResult").html(data);
}
});
}
PHP
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (isset($_POST['name'])) {
$name = $_POST['name'];
echo '<div id="name_input"><h2 class="lastTab">Name:</h2>' . $name . '</div>';
}
if (isset($_POST['age'])) {
$age = $_POST['age'];
echo '<div id="age_input"><h2 class="lastTab">Age:</h2>' . $age . '</div>';
}
if (isset($_POST['phone'])) {
$phone = $_POST['phone'];
echo '<div id="phone_input"><h2 class="lastTab">Phone:</h2>' . $phone . '</div>';
}
if (isset($_POST['email'])) {
$email = $_POST['email'];
echo '<div id="email_input"><h2 class="lastTab">Email:</h2>' . $email . '</div>';
}
if (isset($_POST['job'])) {
$job = $_POST['job'];
echo '<div id="job_input"><h2 class="lastTab">Job:</h2>' . $job . '</div>';
}
if (isset($_POST['hobby'])) {
$hobby = $_POST['hobby'];
echo '<div id="hobby_input"><h2 class="lastTab">Hobby:</h2>' . $hobby . '</div>';
}
}
HTML
<div id="tab-1" class="ui-tabs-panel ui-tabs-hide">
<form autocomplete="off" method="post" enctype="multipart/form-data" id="postForm1" name="postForm1" class="postForm">
Name
<input type="text" id="name" class="detail" name="name" value="" />
Age
<input type="text" id="age" class="detail" name="age" value="" />
</form>
</div>.
<div id="tab-2" class="ui-tabs-panel ui-tabs-hide">
<form autocomplete="off" method="post" enctype="multipart/form-data" id="postForm2" name="postForm2" class="postForm">
Phone Number
<input type="text" id="phone" class="detail" name="phone" value="" />
Email
<input type="text" id="email" class="detail" name="email" value="" />
</form>
</div>
<div id="tab-3" class="ui-tabs-panel ui-tabs-hide">
<form autocomplete="off" method="post" enctype="multipart/form-data" id="postForm3" name="postForm3" class="postForm">
Job
<input type="text" id="job" class="detail" name="job" value="" />
Hobby
<input type="text" id="hobby" class="detail" name="hobby" value="" />
</form>
</div>
You can either use javascript to catch the submit of the form or you can trigger a function that you ve created. It doesn t have to be 3 forms or even a form element for the second case to work
HTML:
<div id="tab-1" class="ui-tabs-panel ui-tabs-hide">
<form autocomplete="off" method="post" enctype="multipart/form-data" id="postForm1" name="postForm1" class="postForm">
Name
<input type="text" id="name" class="detail" name="name" value="" />
Age
<input type="text" id="age" class="detail" name="age" value="" />
</form>
</div>.
<div id="tab-2" class="ui-tabs-panel ui-tabs-hide">
<form autocomplete="off" method="post" enctype="multipart/form-data" id="postForm2" name="postForm2" class="postForm">
Phone Number
<input type="text" id="phone" class="detail" name="phone" value="" />
Email
<input type="text" id="email" class="detail" name="email" value="" />
</form>
</div>
<div id="tab-3" class="ui-tabs-panel ui-tabs-hide">
<form autocomplete="off" method="post" enctype="multipart/form-data" id="postForm3" name="postForm3" class="postForm">
Job
<input type="text" id="job" class="detail" name="job" value="" />
Hobby
<input type="text" id="hobby" class="detail" name="hobby" value="" />
<input type="button" value="SAVE" onclick="saveThem()" />
</form>
</div>
AJAX:
function saveThem() {
var name = $.trim($("#name").val());
var age = $.trim($("#age").val());
var phone = $.trim($("#phone").val());
var email = $.trim($("#email").val());
var job = $.trim($("#job").val());
var hobby = $.trim($("#hobby").val());
var dataString = 'name='+name+'&age='+age+'&phone='+phone+'&email='+email+'&job='+job+'&hobby='+hobby;
$.ajax({
type: "POST",
url: 'http://www.yourdomain.com/something.php',
data: dataString,
dataType: "json",
success: function(data) {
if(data.response){ alert(data.message); }
$("#inputResult").html(data);
}
});
}
something.php
//Get posted variables
$name = (isset($_POST['name'])) ? strip_tags($_POST['name']) : NULL;
$age = (isset($_POST['age'])) ? strip_tags($_POST['age']) : NULL;
$phone = (isset($_POST['phone'])) ? strip_tags($_POST['phone']) : NULL;
$email = (isset($_POST['email'])) ? strip_tags($_POST['email']) : NULL;
$job = (isset($_POST['job'])) ? strip_tags($_POST['job']) : NULL;
$hobby = (isset($_POST['hobby'])) ? strip_tags($_POST['hobby']) : NULL;
//execute your query
$sql = "INSERT INTO ...";
//Return results back to ajax
$result = array(
'response' => 1,
'message' => 'We have a success!'
);
echo json_encode($result);
So in conclusion is pretty much the same as using php but in the middle there is some javascript.
Form: create an id for each element that you want to send to your server(php)
Js: catch values based on element ids and send them to php
Php: get values, clean them, query or anything else and send results back to js
EDIT: Using jQuery serialize()
$('form').submit(function() {
$dataString = $(this).serialize(); //This will produce the same result, based on input names
});

Categories