Running a php code after script been successfully executed - javascript

I have the following script
<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>
Essentially the phpCall() should only execute after
$form.append($('<input type="text" name="stripeToken" />').val(token);
to be executed again, the user would have to refresh or land on the page, and hit the submit button again.
The problem here is that when a user hit submit, then the php code gets executed, which is great but when the page refresh or user relands on the page the php code gets executed regardless if the submit button was clicked.
Below is the php code, where I would like to store the value of this input and post it on the php page
<input type="text" name="stripeToken" />
php page:
<?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);
Update:
<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 2
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($('').val(token));

Try sending a variable via POST to your PHP:
function phpCall() {
$.ajax({
type: "POST",
data: {run: true},
url: 'paymentEmail.php',
success: function (response) {//response is value returned from php (for your example it's "bye bye"
alert(response);
}
});
}
And then in your php:
if ($_POST['run']) {
$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);
}

It might help you :
function phpCall() {
if( appendedStripeToken === true ){
$.ajax({
type: "POST",
data: {run: true},
url: 'paymentEmail.php',
success: function (response) {//response is value returned from php (for your example it's "bye bye"
alert(response);
}
});
}
}

Related

Multiple two inputs and the inputs generated dynamically by jQuery

I have this form and this is my layout:
I want when the user enters the quantity the total input = qty*price.
My view
<?php $form=array('id'=>'myform');?>
<?php echo form_open('Order/submit',$form);?>
<div class="panel panel-default">
<div class="panel-heading">Customer Details</div>
<div class="panel-body">
<div class="col-xs-3">
<select class="selectpicker" data-show-subtext="true" data-live-search="true" name="customer_name">
<?php foreach ($customerdata as $c):
echo "<option value ='$c->c_id'>" . $c->c_name . "</option>";
endforeach;
?>
</select>
</div>
<div class="col-xs-3">
<input type="text" class="form-control" name="invoice_number" placeholder="Invoice Number"/>
</div>
<div class="col-xs-3">
<input type="text" class="form-control" name="branch" placeholder="Branch"/>
</div>
<div class="col-xs-3">
<select class="selectpicker" data-show-subtext="true" data-live-search="true" name="payment_term"">
<option value="cash">Cash</option>
<option value="bank">Bank</option>
<option value="other">Other</option>
</select>
</div>
</div><!--customer panel-Body-->
<div class="panel-heading">Invoice Details
</div>
<div class="panel-body">
<div id="education_fields">
<div class="col-sm-3 nopadding">
<div class="form-group">
<select class="selectpicker" data-show-subtext="true" data-live-search="true" name="select_product[]">
<option></option>
<?php
foreach($order as $row):
echo"<option data-price='$row->p_price' value ='$row->p_id'>".$row->p_name. "</option>";
endforeach;
?>
</select>
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<input type="text" class="form-control qty" name="qty[]" value="" placeholder="Quantity">
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<input type="text" class="form-control price" name="price[]" value="" placeholder="Price">
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control total" name="total[]" value="" placeholder="Total">
<div class="input-group-btn">
<button class="btn btn-success" type="button" onclick="education_fields();"> <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> </button>
</div>
</div>
</div>
</div>
<div class="clear"></div>
</div>
</div>
<div class="panel-footer"><small>Press <span class="glyphicon glyphicon-plus gs"></span> to add another product field :)</small>, <small>Press <span class="glyphicon glyphicon-minus gs"></span> to remove the last product :)</small></div>
</div>
<button type="submit" class="btn btn-primary center-block">Checkout</button>
<?php echo form_close();?>
This is my first jQuery and that used to generate a new row by + button
<script>
var room = 0;
function education_fields() {
room++;
var objTo = document.getElementById('education_fields');
var divtest = document.createElement("div");
divtest.setAttribute("class", "form-group removeclass"+room);
var rdiv = 'removeclass'+room;
var medo='<div class="col-sm-3 nopadding"><div class="form-group"><select class="selectpicker" data-show-subtext="true" data-live-search="true" name="select_product[]"><option></option><?php foreach($order as $row){ ?><option data-price="<?php echo$row->p_price;?>" value ="<?php echo $row->p_id; ?>"><?php echo $row->p_name; ?></option><?php } ?></select></div></div><div class="col-sm-3 nopadding"><div class="form-group"> <input type="text" class="form-control" name="qty[]" value="" placeholder="Quantity"></div></div><div class="col-sm-3 nopadding"><div class="form-group"> <input type="text" class="form-control price" name="price[]" value="" placeholder="Price"></div></div><div class="col-sm-3 nopadding"><div class="form-group"><div class="input-group"> <input class="form-control" name="total[]" placeholder="Total"/><div class="input-group-btn"> <button class="btn btn-danger" type="button" onclick="remove_education_fields('+ room +');"> <span class="glyphicon glyphicon-minus" aria-hidden="true"></span> </button></div></div></div></div><div class="clear"></div>';
divtest.innerHTML = medo;
objTo.appendChild(divtest);
$('select').selectpicker();
}
function remove_education_fields(rid) {
$('.removeclass'+rid).remove();
}
</script>
and this 2nd jQuery used to get product price from from drop-menu attributes and add that into price input.
<script>
function set_price( slc ) {
var price = slc.find(':selected').attr('data-price');
slc.parent().parent().next().next().find('.price').val(price);
}
$('#education_fields').on('change','select.selectpicker',function(){
set_price( $(this) );
});
</script>
var sample = $('#sample').html();
$('#sample').on('click', '.generate', function() {
$('#sample').append(sample);
});
$('#sample').on('change', 'select.selectpicker', function () {
// keyword this is your current select element
var select = $(this);
// each group of inputs share a common .form element, so use that to
// look up for closest parent .form, then down for input[name="price[]"]
// and set the input's value
select.closest('.form').find('[name^=price]').val(
select.find('option:selected').data('price')
// trigger input's keyup event (*)
).keyup();
});
// (*) note: input[type=text]'s onchange event triggers only after it loses focus; we'll use keyup event instead
// create onkeyup event on the qty and price fields
$('#sample').on('keyup', '[name^=qty], [name^=price]', function() {
// get related form
var form = $(this).closest('.form');
// get its related values
var qty = parseInt(form.find('[name^=qty]').val(), 10),
price = parseInt(form.find('[name^=price]').val(), 10);
// ensure only numbers are given
if (!isNaN(qty) && !isNaN(price)) {
// set the total
form.find('[name^=total]').val(qty * price);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sample">
<!-- group all related blocks into a div .form -->
<!-- it makes it easier to reference in your JS -->
<div class="form">
<div class="col-sm-3 nopadding">
<div class="form-group">
<select class="selectpicker" data-show-subtext="true" data-live-search="true" name="select_product[]">
<option data-price=200 value=1>tes1</option>
<option data-price=218 value=2>tes2</option>
<option data-price=80 value=3>tes3</option>
</select>
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<input type="text" class="form-control" name="qty[]" value="" placeholder="Quantity">
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<input type="text" class="form-control price" name="price[]" value="" placeholder="Price">
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<input type="text" class="form-control " name="total[]" value="" placeholder="total" readonly>
</div>
</div>
</div>
<button class="generate" type="button">Generate New Form</button>
</div>
Note, that I am lazy instead of doing [name="price[]"], I simply did [name^=price].
Edit changed onchange to keyup.

Bootstrap Codeigniter 3 Form Click on edit

<legend data-target="#basic_information" data-toggle="collapse">Basic Information</legend>
<fieldset id="basic_information" class="collapse">
<!-- Text input-->
<div class="form-group">
<label class="col-sm-2 control-label" for="textinput">Screen Name</label>
<div class="col-sm-10">
<input type="text" name="screen_name" placeholder="Screen Name" class="form-control">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-sm-2 control-label" for="textinput">First Name</label>
<div class="col-sm-10">
<input type="text" name="first_name" placeholder="First Name" class="form-control">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-sm-2 control-label" for="textinput">Middle Name</label>
<div class="col-sm-10">
<input type="text" name="middle_name" placeholder="Middle Name" class="form-control">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-sm-2 control-label" for="textinput">Last Name</label>
<div class="col-sm-10">
<input type="text" name="last_name" placeholder="Last Name" class="form-control">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-sm-2 control-label" for="textinput">Birthdate</label>
<div class="col-sm-2">
<select name="birthdate-month" id="birthdate-month">
<option value="">month</option>
<?php foreach($month as $month_number => $month_name) { ?>
<option value="<?php echo $month_number; ?>" <?php echo set_select('birthdate-month', $month_number); ?>><?php echo $month_name; ?></option>
<?php } ?>
</select>
</div>
<div class="col-sm-2">
<select name="birthdate-day" id="birthdate-day">
<option value="">day</option>
<?php for($i=1; $i<=31; $i++){ ?>
<option value="<?php echo $i; ?>" <?php echo set_select('birthdate-day', $i); ?>><?php echo $i; ?></option>
<?php } ?>
</select>
</div>
<div class="col-sm-2">
<select name="birthdate-year" id="birthdate-year">
<option value="">year</option>
<?php for($i=(date("Y")-10); $i>=1930; $i--) { ?>
<option value="<?php echo $i; ?>" <?php echo set_select('birthdate-month', $i); ?>><?php echo $i; ?></option>
<?php } ?>
</select>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-sm-2 control-label" for="textinput">Gender</label>
<div class="col-sm-10">
<select name="gender" id="gender">
<option value=""></option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-sm-2 control-label" for="textinput">Occupation</label>
<div class="col-sm-10">
<input type="text" name="job" placeholder="Occupation" class="form-control">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-sm-2 control-label" for="textinput">Address</label>
<div class="col-sm-10">
<input type="text" name="address" placeholder="Address" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="pull-right">
<button type="submit" class="btn btn-default">Cancel</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</fieldset>
I've added the collapse feature of Bootstrap on the above code. Whenever i click on the BASIC INFORMATION text, it would show the details, as it is hidden by default.
What i want to do is the same as the collapse feature.
I want the above code to be read only, i'm pretty sure i can do that with html.
What i want to do is to make it so that i only have to click on the input and it will be available for me to edit one by one or clicking a button and everything will be editable.
solely using bootstrap, like with what i did with collapse.
Is it possible? or do i need to use jquery.
You can do this using bootstrap and with jquery code like this :-
<script>
$(document).ready(function() {
$('#basic_information').on('hidden.bs.collapse', function () {
$('#basic_information .form-control').attr('readonly', true);/*It will add the readonly attribute in all input on collapse*/
});
$('#basic_information').on('shown.bs.collapse', function () {
$('#basic_information .form-control').attr('readonly', false);/*It will remove as soon as your basic information get expanded*/
});
});
</script>
Put a <span> adjacent to each form control with a common class like currentvalue, each one holding the text of the current value for that field. Add a single button at the top that uses JS/jQuery to toggle visibility between those spans, and the inputs (including the submit button). Then you have one file but its functionality is switchable. If you're using ajax to submit the form, then you'll also have to update the <span>s' contents on successful submit.

JQUERY AJAX POST ERROR 500 any idea? I'm trying to insert records into

CODEIGNITER METHOD
public function agregar_post(){
$nombre = $this->post('nombre');
$mail = $this->post('mail');
$telefono = $this->post('telefono');
$password = $this->post('password');
$nivel_listado = $this->post('nivel_listado');
// Store he whole data into $data
$data = array(
'id' => '',
'nombre' => $nombre,
'mail' => $mail,
'telefono' => $telefono,
'password' => $password,
'api_key' => '',
'nivel_listados' => $nivel_listado
);
$query = $this->db->insert('cliente',$data);
// Check if insert is succes
if ($query)
{
$this->output->set_header("Access-Control-Allow-Origin: http://www.verdulero.com", false); // header allow
$this->response($query,201);
}else
{
$this->response(null,404);
}
}
//JQUERY AJAX
$("#frmAddClient").submit(function (event){
event.preventDefault();
var dataForm = $(this).serialize();
// ajax to insert a new product
$.ajax({
type: $(this).attr('method'), // METHOD FROM FORM
url: $(this).attr('action'), // URL FROM FORM
crossDomain: true,
data: dataForm,
success: function(){
alert();
}
});
// CLEAN THE FORM AFTER INSERT
$("#frmAddClient")[0].reset();
});
// HTML
<form name="frmAddClient" id="frmAddClient" method="post" action="<?= $addClient ?>" class="form-horizontal">
<div class="form-group">
<label for="Email" class="col-sm-4 control-label">Correo electronico:</label>
<div class="col-sm-4">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span></span>
<input type="text" class="form-control" id="Email" name="mail" placeholder="Verdulero#example.com" value="" autofocus required>
</div>
</div>
</div>
<div class="form-group">
<label for="Nombre" class="col-sm-4 control-label">Nombre:</label>
<div class="col-sm-4">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input type="text" class="form-control" id="Nombre" name="nombre" placeholder="Juan Verdura" value="" required>
</div>
</div>
</div>
<div class="form-group">
<label for="Telefono" class="col-sm-4 control-label">Telefono:</label>
<div class="col-sm-4">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-phone-alt"></span></span>
<input type="text" class="form-control" id="Telefono" name="telefono" placeholder=" 555 555 555" value="" required>
</div>
</div>
</div>
<div class="form-group">
<label for="Password" class="col-sm-4 control-label">Password:</label>
<div class="col-sm-4">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
<input type="password" class="form-control" id="Password" name="password" placeholder="Password" value="" required>
</div>
</div>
</div>
<div class="form-group">
<label for="nivel_listado" class="col-sm-4 control-label">Nivel Listado:</label>
<div class="col-sm-4">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
<select class="form-control" name='nivel_listado' id='nivel_listado'>
<option value=''>Elija</option>
<option value='1'>Usuario nivel 1</option>
<option value='2'>Usuario nivel 2</option>
<option value='3'>Usuario nivel 3</option>
<option value='4'>Nivel administrador</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-6">
<input type="submit" class="btn btn-success" name="submit" id="Submit_User" value="Insertar nuevo usuario"/>
</div>
</div>
</form>
Use $this->input->post() instead of $this->post()
$nombre = $this->input->post('nombre');
$mail = $this->input->post('mail');
$telefono = $this->input->post('telefono');
$password = $this->input->post('password');
$nivel_listado = $this->input->post('nivel_listado');

How to display multiple form fields of the same type using jquery and fetch their values in php

I have a table named order_master which stores the order_id column. I also have another table order_details having the columns order_id (FK), vendor, purchase_date, delivery_date, and person_name which stores the details of the order corresponding to the order_id from the order_master table.
I want to display a form wherein a button add new item will be displayed. On clicking this button each time, a new block of fields (like vendor, purchase_date, delivery_date, person_name) will be displayed. The user can click the above button and enter as many items as he wants on the same order_id. And when he submits the form, the items on this form must be entered in the database.
How to achieve this?
actually i am using codeigniter framework (MVC architecture). Here i am attaching the view and js file.
<?php echo form_open(); ?>
<div id="emp"></div>
<div class="box">
<div>
</div>
<div class="col-lg-12" style="padding-top: 2%;margin-bottom: 3%" id="form-box">
<div class="col-lg-6 form-group">
<select name="item[]" id="item" class="form-control">
<option value="">--Select Item--</option>
<?php foreach ($items as $item) { ?>
<option value="<?php echo $item["id"]; ?>"><?php echo $item["name"]; ?></option>
<?php } ?>
</select>
</div>
<div class="col-lg-6 form-group">
<select name="vendor[]" id="vendor" class="form-control">
<option value="">--Select Vendor--</option>
<?php foreach ($vendors as $vendor) { ?>
<option value="<?php echo $vendor["id"]; ?>"><?php echo $vendor["name"]; ?></option>
<?php } ?>
</select>
</div>
<div class="col-lg-4 form-group">
<input type="text" name="po_date[]" id="po_date" class="form-control date" placeholder="Purchase Date">
</div>
<div class="col-lg-4 form-group">
<input type="text" name="quantity[]" id="quantity" class="form-control number" placeholder="Item Quantity Individual">
</div>
<div class="col-lg-4 form-group">
<input type="text" name="unit_price[]" id="unit_price" class="form-control number" placeholder="Unit Price" style="text-align: left;">
</div>
<div class="col-lg-4 form-group">
</div>
<div class="col-lg-12 col-md-12 col-sm-12 form-group">
<textarea name="description[]" id="description" class="form-control"></textarea>
</div>
<div class="col-lg-12 col-md-12 col-sm-12" style="height: 3px;background-color: grey"></div>
<div class="col-lg-12 col-md-12 col-sm-12 form-group" id="messageBox">
</div>
</div>
</div>
<a id="add_item" class="col-lg-12" href="">Add new item</a>
<div class="col-lg-12 col-md-12 col-sm-12 text-center form-group">
<input type="button" value="Add Purchase Order" id="addpurchaseOrderBtn" class="btn btn-primary">
</div>
<?php echo form_close(); ?>
**JS File**
$("#main_content").css('minHeight', '400px');
$(document).ready(function() {
$('#add_item').click(function() {
var def_ht = $("#main_content").height() + 300;
$("#main_content").css('minHeight', def_ht);
$("#form-box").clone(true).appendTo("#form-box");
return false;
});
$("#addpurchaseOrderBtn").click(function() {
focusId = null;
var isvalid = false;
if(validateDropDown('item')){
isvalid = true;
}
if(validateDropDown('vendor')){
isvalid = true;
}
if(validatDate('po_date')){
isvalid = true;
}
if(validateTextbox('quantity')){
isvalid = true;
}
if(validateTextbox('unit_price')){
isvalid = true;
}
if(validateTextbox('description')){
isvalid = true;
}
if(isvalid){
focusId.focus();
$("#messageBox").html('<div class="alert alert-danger">There are some error in your submission. Please try again.</div>');
}else{
$("#addPurchaseFrm").submit();
}
});
});
This code works but i am unable to validate all the elements(items) in the form.
You can try the following structure-
<form name="addItem" method="post" action="addItem.php" class="insertItem">
<div class="itemAdd">
<input type="text" name="vendor" >
<input type="text" name="purchase_date" >
<input type="text" name="delivery_date" >
<input type="text" name="person_name" >
</div>
<input type="submit" name="submit" value="Add Item" class="btn btn-primary additem">
$("document").ready(function(){
$(".additem").click(function(){
$(".insertItem").append($(".itemAdd").html);
});
});
Then on addItem.php, you can execute the insert query to insert this data into your database

Simplify angular controller posting to Firebase using AngularFire

I'm new to angular but picking it up quickly. I have this controller that works, based on demo code ive hacked together, but there has to be an easier cleaner way to get all the fields and post so if i want to add a new field i dont need to keep adding it in the various locations.
Heres the controller:
'use strict';
angular.module('goskirmishApp').controller('addEvent', function ($scope, fbutil, $timeout) {
// synchronize a read-only, synchronized array of messages, limit to most recent 10
$scope.messages = fbutil.syncArray('messages', {limit: 10});
// display any errors
$scope.messages.$loaded().catch(alert);
// provide a method for adding a message
$scope.addMessage = function(newEventName,newEventType,newStartDate,newStartTime,newEndDate,newEndTime,newEventDescription,newAddress,newPostcode,newTicketInformation,newBookLink) {
if( newEventName ) {
// push a message to the end of the array
$scope.messages.$add({
eventName: newEventName,
eventType: newEventType,
startDate: newStartDate,
startTime: newStartTime,
endDate: newEndDate,
endTime: newEndTime,
eventDescription: newEventDescription,
address: newAddress,
postcode: newPostcode,
ticketInformation: newTicketInformation,
bookLink: newBookLink
})
// display any errors
.catch(alert);
}
};
function alert(msg) {
$scope.err = msg;
$timeout(function() {
$scope.err = null;
}, 5000);
}
});
And the view:
<h2>Add Event</h2>
<p class="alert alert-danger" ng-show="err">{{err}}</p>
<form role="form">
<div class="form-group">
<label>Event Name</label>
<input class="form-control" type="text" ng-model="newEventName">
</div>
<div class="form-group">
<label>Event Type</label>
<select class="form-control" ng-model="newEventType">
<option value="" disabled selected>Game type</option>
<option value="milsim">Skirmish</option>
<option value="milsim">Special Event</option>
<option value="milsim">Weekender</option>
<option value="milsim">Milsim</option>
</select>
</div>
<div class="form-group">
<label>Start Date & Time</label>
<div class="row">
<div class="col-sm-6">
<input class="form-control" type="date" placeholder="Date" ng-model="newStartDate"/>
</div>
<div class="col-sm-6">
<input class="form-control" type="time" placeholder="Time" ng-model="newStartTime"/>
</div>
</div>
</div>
<div class="form-group">
<label>End Date & Time</label>
<div class="row">
<div class="col-sm-6">
<input class="form-control" type="date" placeholder="Date" ng-model="newEndDate"/>
</div>
<div class="col-sm-6">
<input class="form-control" type="time" placeholder="Time" ng-model="newEndTime"/>
</div>
</div>
</div>
<div class="form-group">
<label>Event Description</label>
<textarea class="form-control" rows="4" ng-model="newEventDescription"></textarea>
</div>
<div class="form-group">
<label>Address</label>
<input class="form-control" ng-model="newAddress">
</div>
<div class="form-group">
<label>Postcode</label>
<input class="form-control" ng-model="newPostcode">
</div>
<div class="form-group">
<label>Ticket Information</label>
<textarea class="form-control" rows="4" ng-model="newTicketInformation"></textarea>
</div>
<div class="form-group">
<label>Booking Link</label>
<input class="form-control" ng-model="newBookLink">
</div>
<button type="submit" class="btn btn-danger" ng-click="addMessage(newEventName,newEventType,newStartDate,newStartTime,newEndDate,newEndTime,newEventDescription,newAddress,newPostcode,newTicketInformation,newBookLink,newLat,newLong,newApproved);newEventName = null;newEventType = null;newStartDate = null;newStartTime = null;newEndDate = null;newEndTime = null;newEventDescription = null;newAddress = null;newPostcode = null;newTicketInformation = null;newBookLink = null;">Add Event</button>
</form>
Help is greatly appreciated!
Define all your input in a object that you will be directly send send to firebase
For example init in your controller this :
$scope.form = {};
After in your template just define your input as 'form attributes'.
<h2>Add Event</h2>
<p class="alert alert-danger" ng-show="err">{{err}}</p>
<form role="form">
<div class="form-group">
<label>Event Name</label>
<input class="form-control" type="text" ng-model="form.eventName">
</div>
<div class="form-group">
<label>Event Type</label>
<select class="form-control" ng-model="form.eventType">
<option value="" disabled selected>Game type</option>
<option value="milsim">Skirmish</option>
<option value="milsim">Special Event</option>
<option value="milsim">Weekender</option>
<option value="milsim">Milsim</option>
</select>
</div>
<div class="form-group">
<label>Start Date & Time</label>
<div class="row">
<div class="col-sm-6">
<input class="form-control" type="date" placeholder="Date" ng-model="form.startDate"/>
</div>
<div class="col-sm-6">
<input class="form-control" type="time" placeholder="Time" ng-model="form.startTime"/>
</div>
</div>
</div>
<div class="form-group">
<label>End Date & Time</label>
<div class="row">
<div class="col-sm-6">
<input class="form-control" type="date" placeholder="Date" ng-model="form.endDate"/>
</div>
<div class="col-sm-6">
<input class="form-control" type="time" placeholder="Time" ng-model="form.endTime"/>
</div>
</div>
</div>
<div class="form-group">
<label>Event Description</label>
<textarea class="form-control" rows="4" ng-model="form.eventDescription"></textarea>
</div>
<div class="form-group">
<label>Address</label>
<input class="form-control" ng-model="form.address">
</div>
<div class="form-group">
<label>Postcode</label>
<input class="form-control" ng-model="form.postcode">
</div>
<div class="form-group">
<label>Ticket Information</label>
<textarea class="form-control" rows="4" ng-model="form.ticketInformation"></textarea>
</div>
<div class="form-group">
<label>Booking Link</label>
<input class="form-control" ng-model="form.bookLink">
</div>
<button type="submit" class="btn btn-danger" ng-click="addMessage()">Add Event</button>
</form>
and directly in your addMessage function
$scope.addMessage = function() {
if( $scope.form.eventName ) {
// push a message to the end of the array
$scope.messages.$add($scope.form)
// display any errors
.catch(alert);
//Reset your form
$scope.form = {};
}
};

Categories

Resources