working ajax - posting variable into another page that execute - javascript

I have the following script that executes after a form has been clicked
<script type="text/javascript">
// This identifies your website in the createToken call below
Stripe.setPublishableKey('CODE');
var stripeResponseHandler = function(status, response) {
var $form = $('#payment-form');
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
// token contains id, last4, and card type
var token = response.id;
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="text" name="stripeToken" />').val(token));
// and re-submit
}
};
jQuery(function($) {
$('#payment-form').submit(function(e) {
var $form = $(this);
// Disable the submit button to prevent repeated clicks
$form.find('button').prop('disabled', true);
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from submitting with the default action
return false;
});
});
function phpCall() {
$.ajax({
url: 'paymentEmail.php',
success: function (response) {//response is value returned from php (for your example it's "bye bye"
alert(response);
}
});
}
</script>
My problem is that the php paymentEmail.php does not run after the script is done.
My objective is as follow:
once and only this line has been run
$form.append($('<input type="text" name="stripeToken" />').val(token));
The followings happen:
The value of stripeToken gets posted to paymentEmail.php
paymentEmail.php gets executed.
If you're curious, below is how the paymentEmail.php looks like:
<?php
if(isset($_POST['paid'])){
$course_price_final = $_POST['course_price_final'];
$course_token = $_POST['stripeToken'];
$course_provider = $_POST['course_provider'];
$user_email = $_POST['user_email'];
$course_delivery = $_POST['course_delivery'];
$order_date = date("Y-m-d");
$insert_c = "insert into orders (course_title,course_price_final,course_provider,user_email,course_date,course_delivery,order_date,course_token)
values ('$crs_title','$course_price_final','$course_provider','$user_email','$course_date1','$course_delivery','$order_date','$course_token')";
$run_c = mysqli_query($con, $insert_c);
}
Thanks in advance
Update:
<script type="text/javascript">
// This identifies your website in the createToken call below
Stripe.setPublishableKey('');
var stripeResponseHandler = function(status, response) {
var $form = $('#payment-form');
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
// token contains id, last4, and card type
var token = response.id;
var appendedStripeToken = false;
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="text" name="stripeToken" />').val(token);
function handleCall() { if (!appendedStripeToken) { appendedStripeToken = true; phpCall(); } } // and re-submit
}
};
function onSubmit() {
var $form = $('#'+id_from_form);
// Disable the submit button to prevent repeated clicks
$form.find('input').prop('disabled', true);
Stripe.card.createToken($form, stripeResponseHandler);
}
function phpCall() {
$.ajax({
url: 'paymentEmail.php',
success: function (response) {//response is value returned from php (for your example it's "bye bye"
alert(response);
}
});
}
</script>
Update 2:
<script type="text/javascript">
// This identifies your website in the createToken call below
Stripe.setPublishableKey('CODE');
var appendedStripeToken = false;
var stripeResponseHandler = function(status, response) {
var $form = $('#payment-form');
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
// token contains id, last4, and card type
var token = response.id;
handleCall(token);
}
};
function handleCall(token) {
if (!appendedStripeToken) {
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="text" name="stripeToken" />').val(token);
appendedStripeToken = true;
phpCall();
}
}
function onSubmit() {
var $form = $('#payment-form'); // TODO: give your html-form-tag an "id" attribute and type this id in this line. IMPORTANT: Don't replace the '#'!
// Disable the submit button to prevent repeated clicks
$('#paymentSubmit').prop('disabled', true); // TODO: give your html-submit-input-tag an "id" attribute
Stripe.card.createToken($form, stripeResponseHandler);
}
function phpCall() {
$.ajax({
url: 'paymentEmail.php',
success: function (response) { // response is value returned from php (for your example it's "bye bye")
alert(response);
}
});
}
</script>
</head>
<body>
<form action="" method="POST" id="payment-form" class="form-horizontal">
<div class="row row-centered">
<div class="col-md-4 col-md-offset-4">
<div class="alert alert-danger" id="a_x200" style="display: none;"> <strong>Error!</strong> <span class="payment-errors"></span> </div>
<span class="payment-success">
<? $success ?>
<? $error ?>
</span>
<fieldset>
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">Choose Start Date</label>
<div class="col-sm-6">
<select name="course_date" class="address form-control" required>
<option><?php
if(isset($_GET['crs_id'])){
$course_id = $_GET['crs_id'];
$get_crs = "select * from courses where course_id='$course_id'";
$run_crs = mysqli_query($con, $get_crs);
while($row_crs=mysqli_fetch_array($run_crs)){
$course_date1 = $row_crs['course_date1'];
echo $course_date1 ;
}
}
?></option>
<option value=<?php
if(isset($_GET['crs_id'])){
$course_id = $_GET['crs_id'];
$get_crs = "select * from courses where course_id='$course_id'";
$run_crs = mysqli_query($con, $get_crs);
while($row_crs=mysqli_fetch_array($run_crs)){
$course_provider = $row_crs['course_provider'];
$course_date2 = $row_crs['course_date2'];
$course_price = $row_crs['course_price'];
$course_title = $row_crs['course_title'];
$course_priceFinal = $row_crs['course_priceFinal'];
$dig = explode(".", $row_crs['course_tax']);
$course_tax = $dig[1];
echo $course_date2 ;
}
}
?>/>
</select>
</div>
</div>
<input type="hidden" name="course_provider" value="<?php echo $course_provider; ?>" >
<input type="hidden" name="course_title" value="<?php echo $course_title; ?>" >
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">Course Delivery</label>
<div class="col-sm-6">
<select name="course_delivery" class="address form-control" required>
<option value="classroom">Classroom</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">Seats</label>
<div class="col-sm-6">
<select name="course_seats" class="address form-control" required>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
</div>
<!-- Form Name -->
<legend>Billing Details</legend>
<!-- Street -->
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">Billing Street</label>
<div class="col-sm-6">
<input type="text" name="street" placeholder="Street" class="address form-control" required>
</div>
</div>
<!-- City -->
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">Billing City</label>
<div class="col-sm-6">
<input type="text" name="city" placeholder="City" class="city form-control" required>
</div>
</div>
<!-- State -->
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">Billing Province</label>
<div class="col-sm-6">
<input type="text" name="province" maxlength="65" placeholder="Province" class="state form-control" required>
</div>
</div>
<!-- Postcal Code -->
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">Postal Code</label>
<div class="col-sm-6">
<input type="text" name="postal" maxlength="9" placeholder="Postal Code" class="zip form-control" required>
</div>
</div>
<!-- Country -->
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">Country</label>
<div class="col-sm-6">
<input type="text" name="country" placeholder="Country" class="country form-control">
<div class="country bfh-selectbox bfh-countries" name="country" placeholder="Select Country" data-flags="true" data-filter="true"> </div>
</div>
</div>
<!-- Email -->
<?php
$email = $_GET['user_email'];
// Note the (int). This is how you cast a variable.
$coupon = isset($_GET['crs_coupon']) ? (int)$_GET['crs_coupon'] : '';
if(is_int($coupon)){
$course_priceFinalAll = $course_priceFinal - ($course_priceFinal * ($coupon/100));
$coupon_deduction = $course_priceFinal * ($coupon/100);
};
?>
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">Email</label>
<div class="col-sm-6">
<input type="text" name="user_email" value=<?php echo $email; ?> class="email form-control" required>
<input type="hidden" name="course_title" value=<?php echo $course_title; ?> class="email form-control">
<input type="hidden" id="box1" name="course_price" value=<?php echo $course_priceFinal; ?> class="email form-control">
</div>
</div><br>
<legend>Purchase Details</legend>
<div class="form-group">
<label class="col-sm-4 control-label">Coupon Code</label>
<div class="col-sm-6">
<input type="text" style="text-align:left; float:left; border:none; width:100px;" name="name" class="email form-control" placeholder="Coupon Code" value="<?php echo $coupon; ?>%" readonly>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label">Want to replace the current coupon code?</label>
<div class="col-sm-6">
<input type="text" name="name" class="email form-control" placeholder="Please enter another coupon code" value="">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" style="color:#FF6400; font-weight:normal;">Tax</label>
<div class="col-sm-6">
<input type="text" class="email form-control" name="name"style="text-align:left; float:left; border:none; width:100px;" placeholder="Please enter another coupon code" value=" <?php echo $course_tax; ?>%" readonly>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" style="color:#FF6400;font-weight:normal;">Price before Tax</label>
<div class="col-sm-6">
<input type="text" style="text-align:left; float:left; border:none; width:100px;" name="course_price_before_tax" class="email form-control" value=" $<?php echo $course_price; ?>" readonly>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" style="color:#FF6400; font-weight:normal;">Price After Tax</label>
<div class="col-sm-6">
<input type="text" style="text-align:left; float:left; border:none; width:100px;" name="course_price_after_tax" class="email form-control" value=" $<?php echo $course_priceFinal; ?>" readonly>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" style="color:#FF6400; font-weight:normal;">Coupon Deduction</label>
<div class="col-sm-6">
<input type="text" style="text-align:left; float:left; border:none; width:100px;" name="course_deduction" class="email form-control" value=" -$<?php echo $coupon_deduction; ?>" readonly>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" style="color:#FF6400"><b>Final Price</b></label>
<div class="col-sm-6">
<input type="text" style="text-align:left; font-weight:bold; float:left; border:none; width:100px;" name="course_price_final" class="email form-control" placeholder="Course Price Final" value="$<?php echo $course_priceFinalAll; ?>" readonly>
</div>
</div>
<!-- Coupon Code-->
<input type="hidden" name="coupon_code" class="email form-control" placeholder="Coupon Code" value=<?php echo $coupon; ?> readonly>
<!-- Price Final -->
<br>
<fieldset>
<legend>Card Details</legend>
<span class="payment-errors"></span>
<!-- Card Holder Name -->
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">Card Holder's Name</label>
<div class="col-sm-6">
<input type="text" name="cardholdername" maxlength="70" placeholder="Card Holder Name" class="card-holder-name form-control" required>
</div>
</div>
<!-- Card Number -->
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">Card Number</label>
<div class="col-sm-6">
<input type="text" id="cardnumber" maxlength="19" data-stripe="number" placeholder="Card Number" class="card-number form-control" required>
</div>
</div>
<div class="form-row">
<label class="col-sm-4 control-label">CVC</label>
<div class="col-sm-6">
<input type="text" size="4" class="email form-control" data-stripe="cvc" required/>
</div>
</div>
<br>
<div class="form-row"><br><br>
<label class="col-sm-4 control-label">Expiration (MM/YYYY)</label>
<div class="col-sm-6">
<div class="form-inline">
<select name="select2" data-stripe="exp-month" class="card-expiry-month stripe-sensitive required form-control" required>
<option value="01" selected="selected">01</option>
<option value="02">02</option>
<option value="03">03</option>
<option value="04">04</option>
<option value="05">05</option>
<option value="06">06</option>
<option value="07">07</option>
<option value="08">08</option>
<option value="09">09</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
</div>
<input type="text" size="4" class="email form-control" data-stripe="exp-year" required/>
</div>
</div>
<br>
<!-- Submit -->
<div class="control-group">
<div class="controls">
<center><br>
<input id="paymentSubmit" class="btn btn-danger" name="paid" onClick="onSubmit()" type="submit" value="Pay Now" class="btn btn-success"></button>
</center>
</div>
</div>
</fieldset>
</form>
update
two minor issues:
With the button being disabled after a click, it wont allow to click again if for instance an error is returned as shown above. It should only disable it after the input has been released
$form.append($('<input type="text" name="stripeToken" />').val(token));
php code
<?php
$course_price_final = $_POST['course_price_final'];
$course_token = $_POST['stripeToken'];
$course_provider = $_POST['course_provider'];
$user_email = $_POST['user_email'];
$course_delivery = $_POST['course_delivery'];
$order_date = date("Y-m-d");
$insert_c = "insert into orders (course_title,course_price_final,course_provider,user_email,course_date,course_delivery,order_date,course_token)
values ('$crs_title','$course_price_final','$course_provider','$user_email','$course_date1','$course_delivery','$order_date','$course_token')";
$run_c = mysqli_query($con, $insert_c);
$location = "../paymentConfirmed.php";
header( "Location: $location" );
?>

Try this:
// This identifies your website in the createToken call below
Stripe.setPublishableKey('');
var appendedStripeToken = false;
var stripeResponseHandler = function(status, response) {
var $form = $('#payment-form');
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
// token contains id, last4, and card type
var token = response.id;
handleCall(token);
}
};
function handleCall(token) {
if (!appendedStripeToken) {
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="text" name="stripeToken" />').val(token);
appendedStripeToken = true;
phpCall();
}
}
function onSubmit() {
var $form = $('#[put the form id here]'); // TODO: give your html-form-tag an "id" attribute and type this id in this line. IMPORTANT: Don't replace the '#'!
Stripe.card.createToken($form, stripeResponseHandler);
}
function phpCall() {
$.ajax({
url: 'paymentEmail.php',
success: function (response) { // response is value returned from php (for your example it's "bye bye")
// Disable the submit button to prevent repeated clicks
$('#[put the input id here]').prop('disabled', true); // TODO: give your html-submit-input-tag an "id" attribute
alert(response);
}
});
}
There are two TODO comments!
EDIT: Modified code

The request is asynchronous!
Create a function that executes your script and calls the phpCall() at the end.
Make your html formular call the new method.
-> The request should be started when the script was done.
EDIT: The new function could look like this:
// You don't need jQuery
function onSubmit() {
var $form = $('#'+id_from_form);
// Disable the submit button to prevent repeated clicks
$form.find('input').prop('disabled', true);
Stripe.card.createToken($form, stripeResponseHandler);
phpCall();
}
Call method on the submitButton and change his type from submit to button:
<input type="button" onClick="onSubmit()" value="Submit" name="submit" />
(You can remove the action and method attribute from the form tag)
<form id="my-form">
<!-- stuff -->
<!-- put the input tag here -->
</form>

You have defined the function phpCall() but you are not calling it anywhere within your script. Simply call the function or remove function declaration so that function internals run procedurally.

Related

Having problem submitting a form without reload using jquery ajax

When i submit form it doesnot update value in database mysql.Its a form written in php.
here is my php and html. I want that the form should not reload and it must submit the changes in database without reloading the page and show preloader for 1 sec on submitting form.
HTML,PHP AND ACTION of form: Here action is the current page where this form is avalilable
detail_customer.php
<?php
$server = "localhost";
$username = "root";
$pass = "";
$dbname = "stinkspolitics_pl";
$conn = mysqli_connect($server, $username, $pass, $dbname);
if (isset($_GET['detail_customer'])) {
$quest_id = $_GET['detail_customer'];
$get_quest = "SELECT * FROM questions WHERE quest_id = '$quest_id'";
$getting_quest = mysqli_query($conn, $get_quest);
while ($row = mysqli_fetch_assoc($getting_quest)) {
$quest_title = $row['quest_title'];
$category_id = $row['category_id'];
}
}
if (isset($_POST['submit'])) {
$quest_t = $_POST['quest_t'];
$update = "UPDATE questions SET quest_title = '$quest_t' WHERE quest_id = '$quest_id'";
$run_update = mysqli_query($conn, $update);
if ($run_update) {
echo 'hello';
}
}
?>
<div class="recent-orders cust_det ">
<h2> Customer Detail</h2>
<div class="customer_detail">
<form id="form-submit" action="./inc/detail_customer.php
" method="POST" class="c_form animate__animated animate__fadeIn">
<div class='alert alert-success'>
<strong>Success!</strong> Your question has been submitted.
</div>
<div class='alert alert-danger'>
<strong>Sorry!</strong> Your question has not been submitted.
</div>
<div class="row">
<div class="c_detail">
<label for="" class="form-labels">Name</label>
<input type="text" name="cat_id" value="<?php echo $category_id ?>" id="cat_id">
</div>
<div class="c_detail">
<label for="" class="form-labels">Contact</label>
<input type="text" name="quest_t" value="<?php echo $quest_title ?>" id="quest_t">
</div>
<div class="c_detail">
<label for="" class="form-labels">City</label>
<input type="text" name="" id="">
</div>
</div>
<div class="row">
<div class="c_detail">
<label for="" class="form-labels">Name</label>
<input type="text" name="" id="">
</div>
<div class="c_detail">
<label for="" class="form-labels">Contact</label>
<input type="text" name="" id="">
</div>
<div class="c_detail">
<label for="" class="form-labels">City</label>
<input type="text" name="" id="">
</div>
</div>
<div class="row">
<input name="submit" type="hidden" />
<input class="btn-primary submit-btn" type="submit" name="" value="Submit">
</div>
</form>
</div>
</div>
JS Code
index.js
$("#form-submit").on("submit", function () {
// e.preventDefault();
var form = $(this);
var formData = form.serialize();
$.ajax({
type: "POST",
url: form.attr("action"),
data: formData,
success: function (data) {
$(".alert-success").show();
$(".alert-success").fadeOut(4000);
console.log(data);
},
error: function (data) {
$(".alert-danger").show();
$(".alert-danger").fadeOut(4000);
console.log(data);
},
});
return false;
});
Ajax Success Response But not updating data in mySQL
<div class="recent-orders cust_det ">
<h2> Customer Detail</h2>
<div class="customer_detail">
<form id="form-submit" action="./inc/detail_customer.php" method="POST"
class="c_form animate__animated animate__fadeIn">
<div class='alert alert-success'>
<strong>Success!</strong> Your question has been submitted.
</div>
<div class='alert alert-danger'>
<strong>Sorry!</strong> Your question has not been submitted.
</div>
<div class="row">
<div class="c_detail">
<label for="" class="form-labels">Name</label>
<input type="text" name="cat_id" value="<br />
<b>Warning</b>: Undefined variable $category_id in <b>C:\xampp\htdocs\admin_panel\inc\detail_customer.php</b> on line <b>62</b><br />
" id="cat_id">
</div>
<div class="c_detail">
<label for="" class="form-labels">Contact</label>
<input type="text" name="quest_t" value="<br />
<b>Warning</b>: Undefined variable $quest_title in <b>C:\xampp\htdocs\admin_panel\inc\detail_customer.php</b> on line <b>66</b><br />
" id="quest_t">
</div>
<div class="c_detail">
<label for="" class="form-labels">City</label>
<input type="text" name="" id="">
</div>
</div>
<div class="row">
<div class="c_detail">
<label for="" class="form-labels">Name</label>
<input type="text" name="" id="">
</div>
<div class="c_detail">
<label for="" class="form-labels">Contact</label>
<input type="text" name="" id="">
</div>
<div class="c_detail">
<label for="" class="form-labels">City</label>
<input type="text" name="" id="">
</div>
</div>
<div class="row">
<input name="submit" type="hidden" />
<input class="btn-primary submit-btn" type="submit" name="" value="Submit">
</div>
</form>
</div>
</div>
The condition if (isset($_POST['submit'])) { will never evaluate to true, since there is no input element in the form with name="submit" (the button with name='submit' does not send the attribute by default).
Either change the condition:
if (isset($_POST['quest_t'])) { ...
Or, include an input element with name='submit', for example:
<input name="submit" type="hidden" />
Also, make sure to move the $_POST check at the beginning of the file and ensure that no other code will be evaluated in the PHP file (e.g. the rest of the HTML code) if a POST request has been received.
Just return false after at the end of the method.
jQuery has its own way of ensuring "preventDefault()" and it is just returning false from the submit handler.
Full background on this here:
event.preventDefault() vs. return false
Issue has been solved. By changing path and then putting path of js file again.

How to fill into more than one textbox with data taken from mysql table after dropdown selection

I would like to fill more than one textbox with data taken from mysql table after dropdown selection. I saw this jsfiddle demo and works fine but I need something different. I have the following situation:
<div class="form-group">
<label class="control-label col-sm-2" for="pn_dn">Pn_DN:</label>
<div class="col-sm-4">
<select id="pn_dn" name="pn_dn" required>
<option value="">Seleziona</option>
<?php
$sql = "SELECT codice, cod_forn, descrizione, package, u_m FROM maglab";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$pn_dn = $row['codice'];
$descrizione = $row['descrizione'];
$pn_manufacturer = $row['cod_forn'];
$package = $row['package'];
$u_m = $row['u_m'];
?>
<option><?php echo $pn_dn; ?></option>
<?php } ?>
</select>
</div>
<?php } ?>
<label class="control-label col-sm-2" for="description">Descrizione:</label>
<div class="col-sm-4">
<textarea class="form-control" rows="3" id="description" name="description" style="width: 100%;"> </textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="pn_manufacturer">Pn_Fornitore:</label>
<div class="col-sm-4">
<textarea class="form-control" rows="3" id="pn_manufacturer" name="pn_manufacturer" style="width: 100%;"> </textarea>
</div>
<label class="control-label col-sm-2" for="manufacturer">Fornitore:</label>
<div class="col-sm-4">
<textarea class="form-control" rows="3" id="manufacturer" name="manufacturer" style="width: 100%;"> </textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="package">Package:</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="package" name="package"> </div>
<label class="control-label col-sm-2" for="u_m">Unità di misura:</label>
<div class="col-sm-4">
<input type="u_m" class="form-control" id="u_m" name="u_m" required>
</div>
</div>
<script type="text/javascript">
var pn_dn = document.getElementById('pn_dn');
//var pn_manufacturer = document.getElementById('<?php echo json_encode($pn_manufacturer); ?>');
pn_dn.onchange = function(){
//document.getElementById("pn_manufacturer").innerHTML = '<?php echo json_encode($pn_manufacturer); ?>';
pn_manufacturer.value = this.value;
description.value = this.value;
package.value = this.value;
u_m.value = this.value;
}
</script>
With the above JS all the inputboxes are filled with pn_dn value but as I take $pn_dn, $descrizione, $pn_manufacturer, $package and $u_m from the table maglab, I would like to fill the inputboxes with $descrizione, $pn_manufacturer, $package and $u_m based on $pn_dn selection. How can the JS be mmodified?
You can use custom attribute and in this you can assign your required values for various fields .i.e:
<select id="pn_dn" name="pn_dn" required>
<option value="">Seleziona</option>
<?php
//your othercodes
?>
<!--use data--attr-->
<option descrizione='<?php echo $descrizione; ?>' pn_manufacturer='<?php echo $pn_manufacturer; ?>' package='<?php echo $package; ?>' u_m='<?php echo $package; ?>'>
<?php echo $pn_dn; ?>
</option>
<?php } ?>
</select>
Demo Code :
var pn_dn = document.getElementById('pn_dn');
pn_dn.onchange = function() {
//get select-index
var slected_index = this.options[this.selectedIndex]
//use getAttribute to get custom attribute
document.getElementById("pn_manufacturer").value = slected_index.getAttribute("pn_manufacturer");
document.getElementById("package").value = slected_index.getAttribute("package");
document.getElementById("u_m").value = slected_index.getAttribute("u_m");
document.getElementById("description").value = slected_index.getAttribute("descrizione");
}
<select id="pn_dn" name="pn_dn" required>
<option value="">Seleziona</option>
<!--use attr-->
<option descrizione='A' pn_manufacturer='Ab' package='2' u_m='1'>
Something ..
</option>
<option descrizione='B' pn_manufacturer='Bb' package='5' u_m='5'>
Something2 ..
</option>
</select>
<label class="control-label col-sm-2" for="description">Descrizione:</label>
<div class="col-sm-4">
<textarea class="form-control" rows="3" id="description" name="description" style="width: 100%;"> </textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="pn_manufacturer">Pn_Fornitore:</label>
<div class="col-sm-4">
<textarea class="form-control" rows="3" id="pn_manufacturer" name="pn_manufacturer" style="width: 100%;"> </textarea>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="package">Package:</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="package" name="package"> </div>
<label class="control-label col-sm-2" for="u_m">Unità di misura:</label>
<div class="col-sm-4">
<input type="u_m" class="form-control" id="u_m" name="u_m" required>
</div>
</div>

backend not adding books to android app sql

i have made an ebook android app everything works fine but the backend code of admin age which is written in php and javascript .the admin has a function to add book known as savebook the "savebook" function is not working please help me guys....every time i try to add a book i it just shows a failed message but when i add the book to the database manually via phpmyadmin it works here is the code to that function
the problem is in last function (what is think) but stil i would appreciate if you guys find some other mistake in the code the whole website is working but this only function is not working the app in on android platform the backend is done using codeigniter and the app is linked to a database which maintains the details of book
<?php
$this->load->view('admin/comman/header');
?>
<div class="clearfix"></div>
<div class="content-wrapper">
<div class="container-fluid">
<!-- Breadcrumb-->
<div class="row pt-2 pb-2">
<div class="col-sm-9">
<h4 class="page-title">Add Book</h4>
<ol class="breadcrumb">
<li class="breadcrumb-item">Dashboard</li>
<li class="breadcrumb-item">Books</li>
<li class="breadcrumb-item active" aria-current="page">Add Book</li>
</ol>
</div>
<div class="col-sm-3">
<div class="btn-group float-sm-right">
Books List
</div>
</div>
</div>
<!-- End Breadcrumb-->
<div class="row">
<div class="col-lg-10 mx-auto">
<div class="card">
<div class="card-body">
<div class="card-title">Add Book
<form id="edit_video_form" enctype="multipart/form-data">
<div class="form-group">
<label for="input-1">Book Name</label>
<input type="text" required value="" class="form-control" name="input_name" id="input-1">
</div>
<input type="hidden" name="id" value="">
<div class="form-group">
<label for="input-3">Book Cost</label>
<select name="select_cost" required class="form-control" id="purpose">
<option value="0">Free</option>
<option value="1">Paid</option>
</select>
</div>
<div class="form-group" id="business" style="display:none">
<label for="input-1">Book price</label>
<input type="text" required value="" class="form-control" name="input_price" id="input-1" placeholder="Enter Book Price">
</div>
<div class="form-group">
<label for="input-2">Book Category</label>
<!-- DropDown -->
<select name="select_category" required class="form-control">
<option value="">Select Category</option>
<?php $i = 1;
foreach($categorylist as $cat) { ?>
<option required value="<?php echo $cat->cat_id; ?>"><?php echo $cat->cat_name; ?></option>
<?php $i++;
} ?>
</select>
</div>
<div class="form-group">
<label for="input-2">Book Author</label>
<!-- DropDown -->
<select name="select_author" required class="form-control">
<option value="">Select Author</option>
<?php $i = 1;
foreach($authorlist as $cat) { ?>
<option value="<?php echo $cat->a_id; ?>"><?php echo $cat->a_title; ?></option>
<?php $i++;
} ?>
</select>
</div>
<div class="form-group">
<label for="input-1"> Book Cover Poster</label>
<input type="file" required class="form-control" name="input_bookcover" id="input-1" placeholder="select Book Cover image"
onchange="readURL(this,'showImage')">
<input type="hidden" name="input_bookcover" value="">
<p class="noteMsg">Note: Image Size must be less than 2MB.Image Height and Width less than 1000px.</p>
<img id="showImage" src="<?php echo base_url() . 'assets/images/placeholder.png'; ?>" height="100" width="100" alt="your image"/>
</div>
<div class="form-group">
<label for="input-1"> Upload Sample Book</label>
<input type="file" required class="form-control" name="input_sample_book" id="input-1" placeholder="select Sample Book">
<input type="hidden" name="input_sample_book" value="">
</div>
<div class="form-group">
<label for="input-1"> Upload Full Book</label>
<input type="file" required class="form-control" name="input_full_book" id="input-1" placeholder="select Full Book">
<input type="hidden" name="input_full_book" value="">
</div>
<div class="form-group">
<label for="input-1">Book Description</label>
<textarea cols="40" rows="5" style="height: 150px" type="text" required value="" class="form-control" name="input_description"
id="input-1"></textarea>
</div>
<div class="form-group">
<button type="button" onclick="savebook()" class="btn btn-primary shadow-primary px-5">Save</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<?php
$this->load->view('admin/comman/footerpage');
?>
<script type="text/javascript">
$('#purpose').on('change', function () {
if (this.value === '1') {
$("#business").show();
} else {
$("#business").hide();
}
});
function savebook() {
var wallpaper_title = jQuery('input[name=wallpaper_title]').val();
if (wallpaper_title == '') {
toastr.error('Please enter Book Name');
return false;
}
$("#dvloader").show();
var formData = new FormData($("#edit_video_form")[0]);
$.ajax({
type: 'POST',
url: '<?php echo base_url(); ?>index.php/admin/savebook',
data: formData,
cache: false,
contentType: false,
processData: false,
dataType: "json",
success: function (resp) {
$("#dvloader").hide();
if (resp.status == '200') {
document.getElementById("edit_video_form").reset();
toastr.success(resp.msg, 'success');
setTimeout(function () {
location.reload();
}, 500);
} else {
toastr.error(resp.msg);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#dvloader").hide();
toastr.error(errorThrown.msg, 'failed');
}
});
}
</script>
here is the database code
enter code here
public function savebook(){
$input_name = $_POST['input_name'];
$input_description = $_POST['input_description'];
$input_price = $_POST['input_price'];
$select_category = $_POST['select_category'];
$select_author = $_POST['select_author'];
$select_cost = $_POST['select_cost'];
$is_feature = "yes";
$b_status = "enable";
$fa_id = $_POST['select_author'];
$input_bookcover=$this->imageupload($_FILES['input_bookcover'],'input_bookcover', FCPATH . 'assets/images/book');
if (isset($_FILES['input_sample_book']) && !empty($_FILES['input_sample_book']['name'])) {
$input_sample_book=$this->fileupload($_FILES['input_sample_book'],'input_sample_book', FCPATH . 'assets/images/book');
}
if (isset($_FILES['input_full_book']) && !empty($_FILES['input_full_book']['name'])) {
$input_full_book=$this->fileupload($_FILES['input_full_book'],'input_full_book', FCPATH . 'assets/images/book');
}
$data = array(
'b_title' => $input_name,
'b_description' => $input_description,
'is_paid' => $select_cost,
'sample_b_url' => $input_sample_book,
'b_url' => $input_full_book,
'b_price' => $input_price,
'fcat_id'=> $select_category,
'b_image' => $input_bookcover,
'is_feature' => $is_feature,
'b_status' => $b_status,
'fa_id' => $fa_id,
'b_date' => date('Y-m-d h:i:s')
);
$res_id=$this->Adminmodel->add_book($data);
if($res_id){
$res=array('status'=>'200','msg'=>'Book added successfully.','id'=>$res_id);
echo json_encode($res);exit;
}else{
$res=array('status'=>'400','msg'=>'fail');
echo json_encode($res);exit;
}
}

my form is not posting values even though i have put method="post" in my form

my form is not posting values even though i have put method="post" and i think there is no error in my form.i have hide some input types by javascript. i am not understanding where the problem is can you rectify that ..my code is
<?php include "header.php" ?>
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<div class="col-md-9" style="padding-top:10px;">
<h3 align="center">Blood Bank Registration </h3>
<form role="form" action="bbinsert.php" method="post" style="color:black">
<div class="form-group">
<input type="text" class="form-control" name="bbname" id="college" placeholder="Blood bank name" required>
</div>
<div class="form-group">
<select class="form-control" id="district" name="district" required>
<option >Select District</option>
<option value="prakasam">Prakasam</option>
<option value="guntur">Guntur</option>
<option value="Nellore">Nellore</option>
</select>
</div>
<div class="form-group">
<select class="form-control" id="mandal" name="mandal" required>
<option >Select Mandal</option>
</select>
</div>
<div class="form-group">
<select class="form-control" id="village" name="village" required>
<option >Select Village</option>
</select>
</div>
<div class="form-group" >
<input type="text" class="form-control" name="phno" placeholder="contact number" >
</div>
<p align="right">create employee<button onclick="return show();"><span class="glyphicon glyphicon-plus" ></span></button></p>
<div id="empform" style="display:none;" >
<div class="form-group">
<input type="text" class="form-control" name="empname1" placeholder="Employee Name" >
</div>
<div class="form-group">
<input type="text" class="form-control" name="empid1" placeholder="Employee Id" >
</div>
<div class="form-group">
<input type="text"class="form-control" name="password1" placeholder="password" >
</div>
<div class="form-group">
<input type="text"class="form-control" name="phno1" placeholder="Contact Number">
</div>
<p align="right"><button onclick="return hide();"><span class="glyphicon glyphicon-minus" ></span></button><button onclick="return show1();"><span class="glyphicon glyphicon-plus" ></span></button></p>
</div>
<div id="empform2" style="display:none;" >
<div class="form-group">
<input type="text" class="form-control" name="empname3" placeholder="Employee Name" >
</div>
<div class="form-group">
<input type="text" class="form-control" name="empid3" placeholder="Employee Id" >
</div>
<div class="form-group">
<input type="text"class="form-control" name="password3" placeholder="password" >
</div>
<div class="form-group">
<input type="text"class="form-control" name="phno3" placeholder="Contact Number">
</div>
<p align="right"><button onclick="return hide2();"><span class="glyphicon glyphicon-minus" ></span></button></p><br>
</div>
<input type="submit" class="btn btn-success" value="create" >
</form>
<script>
function show() {
if(document.getElementById('empform').style.display=='none') {
document.getElementById('empform').style.display='block';
}
return false;
}
function hide() {
if(document.getElementById('empform').style.display=='block') {
document.getElementById('empform').style.display='none';
}
return false;
}
function show1() {
if(document.getElementById('empform1').style.display=='none') {
document.getElementById('empform1').style.display='block';
}
return false;
}
function hide1() {
if(document.getElementById('empform1').style.display=='block') {
document.getElementById('empform1').style.display='none';
}
return false;
}
function show2() {
if(document.getElementById('empform2').style.display=='none') {
document.getElementById('empform2').style.display='block';
}
return false;
}
function hide2() {
if(document.getElementById('empform2').style.display=='block') {
document.getElementById('empform2').style.display='none';
}
return false;
}
</script>
bbinsert.php
<?php
include "connection.php";
if (isset($_POST['submit']))
{
$bbname=$_POST['bbname'];
$district=$_POST['district'];
$mandal=$_POST['mandal'];
$village=$_POST['village'];
$phno=$_POST['phno'];
$insertbb=mysqli_query($conn,"INSERT INTO bloodbanks(bbname,bbdistrict,bbmandal,bbcity,phno)VALUES('$bbname','$district',$mandal','$village','$phno')");
if(!$insertbb)
echo "error in blood bank insertion".mysqli_error($conn);
else
echo "successfully inserted blood banks";
$emp1 = array('empname1', 'empid1', 'password1','phno1');
$emp2 = array('empname2', 'empid2', 'password2','phno2');
$emp3 = array('empname3', 'empid3', 'password3','phno3');
$error = false; //No errors yet
foreach($emp1 AS $fieldname)
{ //Loop trough each field
if(!isset($_POST[$fieldname]) || empty($_POST[$fieldname]))
{
$error = true; //Yup there are errors
}
}
if(!$error) {
$empn1=$_POST['empname1'];
$empid1=$_POST['empid1'];
$password1=$_POST['password1'];
$phno1=$_POST['phno1'];
$insert1=mysqli_query($conn,"INSERT INTO employees(name,empid,password,phno,bbname)VALUES('$empn1','$emmpid1','$password1 ','$phno1','$bbname')");
if(!$insert1)
echo "error in emp1".mysqli_error($conn);
else
echo "success emp1";
}
$error1 = false; //No errors yet
foreach($emp2 AS $fieldname)
{ //Loop trough each field
if(!isset($_POST[$fieldname]) || empty($_POST[$fieldname]))
{
$error1 = true; //Yup there are errors
}
}
if(!$error1) {
$empn2=$_POST['empname2'];
$empid2=$_POST['empid2'];
$password2=$_POST['password2'];
$phno2=$_POST['phno2'];
$insert2=mysqli_query($conn,"INSERT INTO employees(name,empid,password,phno,bbname)VALUES('$empn2','$emmpid2','$password2','$phno2','$bbname')");
if(!$insert2)
echo "error in emp2".mysqli_error($conn);
else
echo "success emp2";
}
$error3 = false; //No errors yet
foreach($emp3 AS $fieldname)
{ //Loop trough each field
if(!isset($_POST[$fieldname]) || empty($_POST[$fieldname]))
{
$error3 = true; //Yup there are errors
}
}
if(!$error3) {
$empn3=$_POST['empname3'];
$empid3=$_POST['empid3'];
$password3=$_POST['password1'];
$phno3=$_POST['phno3'];
$insert3=mysqli_query($conn,"INSERT INTO employees(name,empid,password,phno,bbname)VALUES('$empn3','$emmpid3','$password3','$phno3','$bbname')");
if(!$insert3)
echo "error in emp3".mysqli_error($conn);
else
echo "success emp3";
}
}
else
{
echo "submit method did not post the form";
}
?>
`
Your submit button doesn't have a name attribute. So no post element called "submit" exists. Put a name on your submit button if you want it to post.

How to display the values passing using ajax in another php file?

I have written a code to pass values from a form using ajax but the values passed to another php page is not getting displayed there. I want to display the values passed in email.php file and send it as a mail to a email-id.
My script :
$(function() {
$('#send_message').on('click', function(e) {
var name = $('#exampleInputName1').val();
var email = $('#exampleInputEmail1').val();
var tel = $('#exampleInputTelephone1').val();
var cn = $('#exampleInputCountry1').val();
var message = $('#exampleInputMessage1').val();
e.preventDefault();
$.ajax({
type: 'post',
url: 'php/email.php',
data: {
name: name,
email: email,
tel: tel,
cn: cn,
message: message
},
success: function(data) {
alert(message);
}
});
});
});
html page:
<form name="contactForm1" id='contact_form1' method="post" action='php/email.php'>
<div class="form-inline">
<div class="form-group col-sm-12 padd">
<input type="text" class="form-control" name="name" id="exampleInputName1" placeholder="name">
</div>
<div class="form-group col-sm-12 padd">
<input type="email" class="form-control" name="email" id="exampleInputEmail1" placeholder="email address">
</div>
<div class="form-group col-sm-12 padd">
<input type="text" class="form-control" name="telephone" id="exampleInputTelephone1" placeholder="phone">
</div>
<div class="form-group col-sm-12 padd">
<input type="text" class="form-control" name="Country" id="exampleInputCountry1" placeholder="Country">
</div>
<div class="form-group col-sm-12 padd">
<textarea class="form-control" name="message" rows="3" id="exampleInputMessage1" placeholder="message"></textarea>
</div>
</div>
<div class="form-group col-xs-12 padd">
<div id='mail_success' class='success' style="display:none;">Your message has been sent successfully.
</div>
<!-- success message -->
<div id='mail_fail' class='error' style="display:none;">Sorry, error occured this time sending your message.
</div>
<!-- error message -->
</div>
<div class="form-group col-xs-8 padd" id="recaptcha2"></div>
<div class="form-group col-sm-4 padd" id='submit'>
<input type="submit" id='send_message' name="sendus" class="btn btn-lg costom-btn" value="send">
</div>
</form>
email.php
<?php
$temp = $_POST['name'];
echo $temp;
?>
Can anyone suggest how to do this ?

Categories