insert data from dynamic inputs to database in codeigniter - codeigniter

everyone.
I'm beginner in CodeIgniter, I trying to insert data from dynamic input to database, I searched too much but I got nothing so far
my model is empty till now because I don't know how to insert data from dynamic inputs
This is my view
<form id="bookForm" method="post" class="form-horizontal"action="order/insert">
<div class="form-group">
<div class="col-xs-3">
<label for="customer_name">Customer :
<br>
<select class="selectpicker" data-show-subtext="true" data-live-search="true" name="customer_name" id="customer_name">
<?php foreach ($customerdata as $c):
echo "<option value ='$c->c_id'>" . $c->c_name . "</option>";
endforeach;
?>
</select>
</label>
</div>
<div class="col-xs-3">
<label for="invoice_number">Invoice Number :
<input type="text" class="form-control" name="invoice_number" id="invoice_number" placeholder="Invoice Number"/>
</label>
</div>
<div class="col-xs-3">
<label for="branch">Branch :
<input type="text" class="form-control" name="branch" id="branch" placeholder="Branch"/>
</label>
</div>
<div class="col-xs-3">
<label for="payment_term">Payment Term :
<br>
<select class="selectpicker" data-show-subtext="true" data-live-search="true" name="payment_term" id="payment_term">
<option id-="cash">Cash</option>
<option id-="bank">Bank</option>
<option id-="other">Other</option>
</select>
</label>
</div>
<br>
<br><br><br><hr>
<label class="col-xs-1 control-label">Product</label>
<div class="col-xs-4">
<select class="selectpicker" data-show-subtext="true" data-live-search="true" name="product[0].title">
<?php
foreach($order as $row):
echo"<option value ='$row->p_id'>".$row->p_name. "</option>";
endforeach;
?>
</select>
</div>
<div class="col-xs-4">
<input type="text" class="form-control" name="product[0].qty" placeholder="Quantity" />
</div>
<div class="col-xs-2">
<input type="text" class="form-control" name="product[0].price" placeholder="Price" />
</div>
<div class="col-xs-1">
<button type="button" class="btn btn-default addButton"><i class="fa fa-plus"></i></button>
</div>
</div>
<!-- The template for adding new field -->
<div class="form-group hide" id="bookTemplate">
<div class="col-xs-4 col-xs-offset-1">
<select class="selectpicker" data-show-subtext="true" data-live-search="true" name="title">
<?php
foreach($order as $row):
echo"<option value ='$row->p_id'>".$row->p_name. "</option>";
endforeach;
?>
</select>
</div>
<div class="col-xs-4">
<input type="text" class="form-control" name="qty" placeholder="Quantity" />
</div>
<div class="col-xs-2">
<input type="text" class="form-control" name="price" placeholder="Price" />
</div>
<div class="col-xs-1">
<button type="button" class="btn btn-default removeButton"><i class="fa fa-minus"></i></button>
</div>
</div>
<div class="form-group">
<div class="col-xs-5 col-xs-offset-1">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
This Jquery
<script>
$(document).ready(function() {
var titleValidators = {
row: '.col-xs-4', // The title is placed inside a <div class="col-xs-4"> element
validators: {
notEmpty: {
message: 'Product is required'
}
}
},
isbnValidators = {
row: '.col-xs-4',
validators: {
notEmpty: {
message: 'Quantity is required'
}
}
},
priceValidators = {
row: '.col-xs-2',
validators: {
notEmpty: {
message: 'Invoice Number is required'
},
numeric: {
message: 'The invoice number must be a numeric number'
}
}
},
bookIndex = 0;
$('#bookForm')
.formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
'product[0].title': titleValidators,
'product[0].qty': isbnValidators,
'product[0].price': priceValidators
}
})
// Add button click handler
.on('click', '.addButton', function() {
bookIndex++;
var $template = $('#bookTemplate'),
$clone = $template
.clone()
.removeClass('hide')
.removeAttr('id')
.attr('data-book-index', bookIndex)
.insertBefore($template);
// Update the name attributes
$clone
.find('[name="title"]').attr('name', 'product[' + bookIndex + '].title').end()
.find('[name="qty"]').attr('name', 'product[' + bookIndex + '].isbn').end()
.find('[name="price"]').attr('name', 'product[' + bookIndex + '].price').end();
// Add new fields
// Note that we also pass the validator rules for new field as the third parameter
$('#bookForm')
.formValidation('addField', 'product[' + bookIndex + '].title', titleValidators)
.formValidation('addField', 'product[' + bookIndex + '].qty', isbnValidators)
.formValidation('addField', 'product[' + bookIndex + '].price', priceValidators);
})
// Remove button click handler
.on('click', '.removeButton', function() {
var $row = $(this).parents('.form-group'),
index = $row.attr('data-book-index');
// Remove fields
$('#bookForm')
.formValidation('removeField', $row.find('[name="product[' + index + '].title"]'))
.formValidation('removeField', $row.find('[name="product[' + index + '].qty"]'))
.formValidation('removeField', $row.find('[name="product[' + index + '].price"]'));
// Remove element containing the fields
$row.remove();
});
});
This is my controller
function OrderNow(){
$this->load->model('Out_m');
$this->Out_m->outs();
$this->session->set_flashdata('done','Your Order Submitted Successfully');
redirect('Order', 'refresh');
}

Just validate your form input however you see necessary:
$this->load->library('form_validation');
$this->form_validation->set_rules('branch', 'Branch', 'required|trim');
Make sure your form validation doesn't fail.
if ($this->form_validation->run() === FALSE) {
// Throw some error or whatever
} else {
$form_data = array('branch'=>set_value('branch');
}
Then chuck that over to the model:
$this->Out_m->handling_function($form_data);
Once you get it over there, you can do whatever you want with it.

Related

Laravel Batch Update Data Based on Checked Checkboxes Error

I have a table that has checkboxes on the left column that looks like this :
Table
What I want to try to do is assign a surveyor name using the select option in a modal to the surveyor column for all of the checked rows.
Modal
If I checked the first 4 rows of the table and then click the "Try Assign", it will only fill the last checked row (4th row), not all of the checked rows.
I think I've already used Foreach in my Controller so I don't know yet what is wrong with my code.
Result
This is my modal code :
<div class="modal fade" id="city-modal" aria-hidden="true">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="CityModal"></h4>
</div>
<div class="modal-body">
<form action="javascript:void(0)" id="CityForm" name="CityForm" class="form-horizontal" method="POST" enctype="multipart/form-data">
<input type="hidden" name="id" id="id">
<div class="form-group">
<label for="name" id="labelname" class="col-sm-2 control-label">Name</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="name" name="name" placeholder="Enter City Name" maxlength="50">
</div>
</div>
<div class="form-group">
<label for="name" id="labelpopulation" class="col-sm-2 control-label">Population</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="population" name="population" placeholder="Enter City Population" maxlength="50">
</div>
</div>
<div class="form-group">
<label id="labelsurveyor" class="col-sm-2 control-label">Surveyor</label>
<div class="col-sm-12">
<select class="form-control select2" id="surveyor_id" name="surveyor_id" ">
<option value="">--Select Surveyor--</option>
#foreach($users as $surveyor)
<option value="{{ $surveyor->id }}">
{{$surveyor->name}}
</option>
#endforeach
</select>
</div>
</div>
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary" id="btn-save">Save changes</button>
</div>
</form>
</div>
<div class="modal-footer">
</div>
</div>
</div>
This is my JavaScript code for assigning the surveyor:
$(document).on('click', '.try-assign', function(e) {
var cityId = [];
var svrid;
$('.checkbox:checked').each(function() {
cityId.push($(this).val());
console.log(cityId);
});
if (cityId.length > 0) {
$.ajax({
type: "PUT",
url: "{{ url('try-assign') }}",
data: {
cityId,
svrid
},
dataType: "json",
success: function(res) {
$('#CityModal').html("Assign Surveyor");
$('#city-modal').modal('show');
$('#labelname').attr('hidden', true);
$('#labelpopulation').attr('hidden', true);
$('#labelsurveyor').attr('hidden', false);
$('#id').val(res.id);
$('#name').val(res.name).attr('hidden', true);
$('#population').val(res.population).attr('hidden', true);
$('#surveyor_id').val(res.surveyor_id).attr('disabled', false);
$('#surveyor_id').trigger('change');
svrid = res.surveyor_id;
}
});
} else {
alert('Please select atleast one row');
}
});
This is my tryAssign() function on the Controller :
public function tryAssign(Request $request)
{
$cityId = $request->cityId;
$svrid = $request->svrid;
foreach ($cityId as $key => $value) {
$city = City::find($value);
$city->surveyor_id = $svrid;
$city->update();
}
return Response()->json($city);
}
And, this is my route :
Route::put('try-assign', [CityController::class, 'tryAssign']);

I'm new in ASP.NET CORE, and I'm trying to send data from dynamically created input fields to Controller

$("#addRow").click(function ()
{
#{
new VLSM_Model().LansValues.Add(new Lans());
}
var rowCount = parseInt($("#totalLans").val());
rowCount++;
$("#totalLans").val(rowCount);
var html = '';
html += '<div id="inputFormRow" style="width: 35%">';
html += '<div class="input-group mb-3">';
html += '<input type="number" id="[' + (rowCount - 1) + '].InitialLanValues" class="form-control m-input" placeholder="Enter number of Hosts" autocomplete="off" style="width: 30%" required>';
html += '<div class="input-group-append">';
html += '<button id="removeRow" type="button" class="btn btn-danger" style="margin-right: 5px">Remove Network</button>';
html += '</div>';
html += '</div>';
$('#newRow').append(html);
});
$(document).on('click', '#removeRow', function ()
{
var rowCount = parseInt($("#totalLans").val());
rowCount--;
$("#totalLans").val(rowCount);
$(this).closest('#inputFormRow').remove();
});
$(document).ready(function () {
$("#createButton").click(function ()
{
var inputData = $(this).serializeArray();
$.ajax(
{
type: "POST", //HTTP POST Method
url: "VLSM_Controller/Create", // Controller/View
data: inputData,
success : function(response) {
console.log(response)
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>VLSM CALCULATE</h1>
<hr />
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group" style="width: 35%">
<label asp-for="IP_Address" class="control-label"></label>
<input asp-for="IP_Address" class="form-control" />
<span asp-validation-for="IP_Address" class="text-danger"></span>
</div>
<br/>
<div class="form-group">
<div id="inputFormRow" style="width: 35%">
<div class="input-group mb-3">
<br/>
<div class="input-group-append"></div>
</div>
</div>
<div id="newRow">
<input type="hidden" id="totalLans" value="0" />
</div>
<button id="addRow" type="button" class="btn btn-info">Add Network</button>
</div>
<span asp-validation-for="LansValues" class="text-danger"></span>
<br/>
<div class="form-group" style="width: 35%">
<label asp-for="cidrValue" class="control-label"></label>
<input asp-for="cidrValue" class="form-control" />
<span asp-validation-for="cidrValue" class="text-danger"></span>
</div>
<br/>
<div class="form-group">
<input type="submit" value="Calculate VLSM" class="btn btn-info" id="createButton"/>
</div>
</form>
<div>
<a asp-action="VlsmResult">Back to List</a>
</div>
I created dynamically input fields as you can see from code, but I have difficulties to pass the data to controller, and to use the data for calculations inside the controller.
My question is how to pass data from dynamically created input fields with ajax to controller and how to use passed data for any kind of calculations.
Model binding system will look through the property by name. So you need match the name attribute in html with model property name. That is to say, your dynamic added input fields should have name attribute:name="LansValues[index].InitialLanValues".
Here is a whole working demo:
Model:
public class VLSM_Model
{
public string IP_Address { get; set; }
public List<Lans> LansValues { get; set; }
public int cidrValue { get; set; }
}
public class Lans
{
public int InitialLanValues { get; set; }
}
View:
Modify type="submit" to type="button", otherwise the ajax will not hit.
#model VLSM_Model
<h1>VLSM CALCULATE</h1>
<hr />
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group" style="width: 35%">
<label asp-for="IP_Address" class="control-label"></label>
<input asp-for="IP_Address" class="form-control" />
<span asp-validation-for="IP_Address" class="text-danger"></span>
</div>
<br />
<div class="form-group">
<div id="inputFormRow" style="width: 35%">
<div class="input-group mb-3">
<br />
<div class="input-group-append"></div>
</div>
</div>
<div id="newRow">
<input type="hidden" id="totalLans" value="0" />
</div>
<button id="addRow" type="button" class="btn btn-info">Add Network</button>
</div>
<span asp-validation-for="LansValues" class="text-danger"></span>
<br />
<div class="form-group" style="width: 35%">
<label asp-for="cidrValue" class="control-label"></label>
<input asp-for="cidrValue" class="form-control" />
<span asp-validation-for="cidrValue" class="text-danger"></span>
</div>
<br />
<div class="form-group">
#*change here*#
<input type="button" value="Calculate VLSM" class="btn btn-info" id="createButton" />
</div>
</form>
<div>
<a asp-action="VlsmResult">Back to List</a>
</div>
JS:
Change the dynamic html to name="LansValues[' + (rowCount - 1) + '].InitialLanValues" and change var inputData = $(this).serializeArray(); to var inputData = $('form').serializeArray();.
#section Scripts
{
<script>
$("#addRow").click(function ()
{
#*#{new VLSM_Model().LansValues.Add(new Lans());}*#
var rowCount = parseInt($("#totalLans").val());
rowCount++;
$("#totalLans").val(rowCount);
var html = '';
html += '<div id="inputFormRow" style="width: 35%">';
html += '<div class="input-group mb-3">';
//change id attribute to name attribute and modify the name
html += '<input type="number" name="LansValues[' + (rowCount - 1) + '].InitialLanValues" class="form-control m-input" placeholder="Enter number of Hosts" autocomplete="off" style="width: 30%" required>';
html += '<div class="input-group-append">';
html += '<button id="removeRow" type="button" class="btn btn-danger" style="margin-right: 5px">Remove Network</button>';
html += '</div>';
html += '</div>';
$('#newRow').append(html);
});
$(document).on('click', '#removeRow', function ()
{
var rowCount = parseInt($("#totalLans").val());
rowCount--;
$("#totalLans").val(rowCount);
$(this).closest('#inputFormRow').remove();
});
$(document).ready(function () {
$("#createButton").click(function ()
{
var inputData = $('form').serializeArray(); //change here...
$.ajax(
{
type: "POST", //HTTP POST Method
url: "Home/Create", // Controller/View
data: inputData,
success : function(response) {
console.log(response)
}
});
});
});
</script>
}
Controller:
public class HomeController : Controller
{
[HttpPost]
public IActionResult Create(VLSM_Model model)
{
//...
}
}
Note:
Actually if you just use form submit, it also can work well. If you use form submit, just change your original code:name="LansValues[' + (rowCount - 1) + '].InitialLanValues" in $("#addRow").click() function. Then remove the $("#createButton").click() function. No need change any other code.

VueJs: How to create a select where options come from a query to other model

I'm new on VueJs and I don't know why I have the following problem:
I'm creating a view called Owners.vue where I show pub owners. In UpdateProfile.vue I show the owner data and here is where I have my problem: I'd like to build a select where the options are the possible pubs stored in my table "pubs":
My vue component is as follows:
UpdateProfile.vue
<template>
<confirm title="Edit User" ok="Save user" :show="show"
v-on:save="save"
v-on:close="close">
<div class="field">
<label class="label">Name</label>
<div class="control">
<input class="input" type="text" placeholder="User name" v-model="data.name">
</div>
</div>
<div class="field">
<label class="label">Lastname</label>
<div class="control">
<input class="input" type="text" placeholder="last name" v-model="data.lastname">
</div>
</div>
<div class="field">
<label class="label">Email</label>
<div class="control">
<input class="input" type="email" placeholder="email" v-model="data.email">
</div>
</div>
<!--Owner Pubs-->
<div class="field">
<label class="label">Pubs</label>
<div v-for="pub in data.userPubsOwned" class="control">
<input class="input" type="text" placeholder="Pub tapps" v-model="pub.name">
<div class="button is-danger" #click="deletePubFromOwner(pub.id)">
<span class="icon"><i class="far fa-trash-alt"></i></span>
<span>Delete</span>
</div>
</div>
<br>
</div>
<!--Owner Pubs-->
<!--Add Pubs to Owner-->
<div class="field">
<label class="label">Add new Pub</label>
<div class="select">
<select v-model="pubs">
<option v-for = "pub in pubs" :value="pub.id" >{{pub.name}}</option>
</select>
</div>
<br>
<br>
<div class="button is-info" #click="addPubToOwner()">
<span class="icon"><i class="fas fa-save fa-lg"></i></span>
<span>Add Tapp</span>
</div>
</div>
<!--Add Pubs to Owner-->
</confirm>
import User from "../../models/user";
export default {
props: {
show: Boolean,
data: Object,
},
data() {
return {
selected: null,
data: new User(),
pubs: [],
pub: new Pub(),
}
},
computed: {
},
methods: {
save() {
this.$emit('save', this.data);
},
close() {
this.$emit('close');
},
hasRootPermissionsAndIsNotRoot() {
return this.CONSTANTS.hasRootPermissions() && this.data.permissions !== this.CONSTANTS.ROOT_USER.permissions;
},
addPubToOwner(){
this.api.post('/owners/' + this.data.id + '/' + this.selected).then(response => {
this.data = response.data;
});
},
deletePubFromOwner(ownerpub) {
this.api.delete('/owners/' + this.data.id + '/' + ownerpub).then(response => {
this.data = response.data;
});
},
}
}
I just need to show all the pubs stored in my table pub...do I have to create a function? And how it would be?
Thanks a lot for your help!!
Yes, create a method in the mounted() section. I use a similar process to show all of the flavors/prices of a product in a shopping cart. Here is my code that you can use and hopefully extrapolate your answer from:
Mounted function to load upon vue mount
mounted: function() {
this.getPrice();
},
getPrice() function:
getPrice: function(){
axios.post('/getproductinfo', this.$data.model)
.then((response) => {
console.log(response);
this.display_name = response.data.display_name;
this.price = '$' + response.data.price;
})
.catch(error => {
this.errors.record(error.response.data.errors);
});
},
And finally the code in your view blade file
<select class="centerSelect" v-show="!loading && ordering" ref="quantitySelect" v-model="model.id" name="code_id" #change="getPrice">
#foreach ($code as $item)
<option value="{{$item->id}}">{{$item->display_name}}</option>
#endforeach
</select>

how to make ajax call inside a edit form view in laravel

i have created a form for editing the record from db there is different time slots and i want to make delete function for them so i made a ajax call but am confused in URL www.hostname.com/dental/public/admin/manageschedule/1/api/ajax 404 (Not Found)
how to call ajax inside a laravel edit form
here is what i have done:
#extends('admin.layouts.app_inner')
#section('htmlheader_title')
Home
#endsection
#section('content')
#if (count($errors))
#foreach($errors->all() as $error)
<div class="alert alert-danger"><i class="fa fa-fw fa-close"></i> {{ $error }}</div>
#endforeach
#endif
#if ($message = Session::get('success'))
<div class="alert alert-success alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-check"></i>Success</h4>
{{ $message }}
</div>
#endif
<div class="box box-info">
<div class="box-header with-border">
<h3 class="box-title text-green"><b>Add Schedule</b></h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<div class="box-body">
{!! Form::model($doctors, ['method' => 'PATCH','route' => ['manageschedule.update', $doctors->doctor_id],'class' => 'form-horizontal','files'=>true]) !!}
<div class="form-group">
<label class="col-md-3 control-label"> Select Doctor :</label>
<div class="col-md-5">
<select class="form-control" required name="doctor_name">
<?php $results = DB::select(DB::raw("SELECT day FROM schedule_times where doctor_id='" . $doctors->doctor_id . "' Order BY id DESC ")); ?>
<option value="{{$doctors->doctor_name}}" SELECTED="YES">{{$doctors->doctor_name}}</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" required> Day :</label>
<div class="col-md-5">
<div class="md-checkbox-inline">
<?php $day = array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'); ?>
#foreach($day as $days)
<input name="day[]" value="<?php echo $days; ?>" type="checkbox" class="md-checkbox" <?php
foreach ($results as $row) {
if ($row->day == $days) {
echo 'checked="checked"';
} else {
}
}
?> >
<label for="checkbox7"> <?php echo $days; ?> </label>
#endforeach
</div>
</div>
</div>
<?php foreach ($results as $row) { $d=$row->day;}
$result= DB::select(DB::raw("SELECT * FROM schedule_times where doctor_id='" . $doctors->doctor_id . "' And day='".$d."' "));
?>
<div class="form-group">
<label class="col-md-3 control-label" required>Time slots</label>
<div class="col-md-6">
<table class="table table-bordered" id="employee_table" width="50%" >
<th>Start Time</th>
<th>End Time</th>
<th>Manage</th>
<?php foreach ($result as $key=>$vari) {
$id = $vari->id;
?>
<tr id="row1">
<td><div class="input-group ">
<input type="text" class="form-control" id="time" placeholder="Start Time" name="s_time[]" value="<?php echo $vari->start_time; ?>" >
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div></td>
<td><div class="input-group ">
<input type="text" class="form-control" id="time1" placeholder="Start Time" name="e_time[]" value="<?php echo $vari->end_time; ?>" >
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div></td>
<?php if ($key == 0) { ?>
<td><input type='button' class='fa fa-plus fa-4 btn btn-primary' value='DELETE' disabled></td>
<?php } else { ?>
<td><span class='delete' id='del_<?php echo $id; ?>'><input type='button' class='fa fa-plus fa-4 btn btn-primary' value='DELETE' id='del_<?php echo $id; ?>' ></td>
</tr>
<?php }
}
?>
</table>
<a type="button" onclick="add_rows();" class="fa fa-plus-circle btn btn-primary"> Add More Time Slots</a>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label"> Per Patient Time :</label>
<div class="col-md-5">
<div class=" input-daterange">
<input type="text" name="p_time" class="form-control" placeholder="Set per patient time" id="time1" value="<?php
echo $result[0]->p_time; ?>">
<span class="help-block"> You can set only minute </span>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Visibility :</label>
<div class="col-md-5">
<input type="radio" id="checkbox2_5" value="Yes" name="visible" class="md-radiobtn" <?php
foreach($result as $check)
{
if($check->visibility=='Yes'){ echo 'checked="checked"';}else{}
} ?> >
<label for="checkbox2_5"> Yes </label>
<input type="radio" id="checkbox2_10" value="No" name="visible" class="md-radiobtn" <?php foreach($result as $check)
{
if($check->visibility=='No'){ echo 'checked="checked"';}else{}
} ?>>
<label for="checkbox2_10"> No </label>
</div>
</div>
<br><br>
<div class="box-footer">
<button type="submit" class="btn btn-info pull-right"id="submit">Update Schedule </button>
</div>
{!! Form::close() !!}
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$('#time').timepicker();
})
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$('#time1').timepicker();
})
});
</script>
<script type="text/javascript">
function add_rows()
{
$rowno = $("#employee_table tr").length;
$rowno = $rowno + 1;
$("#employee_table tr:last").after("<tr id='row" + $rowno + "'><td><div class='input-group '><input type='text' class='form-control' placeholder='Start Time' name='s_time[]' onclick=showtime('row" + $rowno + "')><span class='input-group-addon'><span class='glyphicon glyphicon-time'></span></span></div> </td><td><div class='input-group '><input type='text' class='form-control' id='time1' placeholder='End Time' name='e_time[]'><span class='input-group-addon'><span class='glyphicon glyphicon-time'></span></span></div> </td><td><input type='button' class='fa fa-plus fa-4 btn btn-primary' value='DELETE' onclick=delete_row('row" + $rowno + "')></td></tr>");
}
function delete_row(rowno)
{
$('#' + rowno).remove();
}
</script>
<script type="text/javascript">
//Variant Deleting script///
$(document).ready(function () {
// Delete
$('.delete').click(function () {
var el = this;
var id = this.id;
var splitid = id.split("_");
// Delete id
var deleteid = splitid[1];
alert('Are you sure you want to delete?');
$.ajax({
url: 'api/ajax',
type: 'delete',
data: {id: deleteid},
success: function (response) {
// Removing row from HTML Table
$(el).closest('tr').css('background', 'tomato');
$(el).closest('tr').fadeOut(800, function () {
$(this).remove();
});
}
});
});
});
</script>
<meta name="_token" content="{!! csrf_token() !!}" />
#endsection
here is my controller of api
Route::post('ajax','Controller#ajax')->name('ajax');
here is my web route:
Route::get('/', function () {
return view('auth.login');
});
Route::post('/', function () {
return view('auth.login')->with('successMsg','Please Select A role .');
});
Route::prefix('admin')->group(function() {
Route::get('/login', 'Auth\AdminLoginController#showLoginForm')->name('admin.login');
Route::post('/login', 'Auth\AdminLoginController#login')->name('admin.login.submit');
Route::get('/', 'AdminController#index')->name('admin.home');
Route::resource('managedoctor', 'AddDocController');
Route::resource('managefront', 'AddFrontController');
Route::resource('managepatient', 'AddPatientController');
Route::resource('manageschedule', 'AddScheduleController');
Route::get('/logout', 'Auth\AdminLoginController#logout')->name('admin.logout');
});
Route::prefix('doctor')->group(function() {
Route::get('/login', 'Auth\DoctorLoginController#showLoginForm')->name('doctor.login');
Route::post('/login', 'Auth\DoctorLoginController#login')->name('doctor.login.submit');
Route::get('/', 'DoctorController#index')->name('doctor.home');
Route::get('/logout', 'Auth\DoctorLoginController#logout')->name('doctor.logout');
});
Route::prefix('frontdesk')->group(function() {
Route::get('/login', 'Auth\FrontdeskLoginController#showLoginForm')->name('frontdesk.login');
Route::post('/login', 'Auth\FrontdeskLoginController#login')->name('frontdesk.login.submit');
Route::get('/', 'FrontdeskController#index')->name('frontdesk.home');
Route::get('/logout', 'Auth\FrontdeskLoginController#logout')->name('frontdesk.logout');
});
my issue is resolved now the mistake i have done is i was not using the same route group in which am calling the controller with AUTH method

stripe token is not passing

I have an application built in Laravel 4 and uses this package
I am following this tutorial
This is the error I am getting http://postimg.org/image/c4qwjysgp/
My issue is $token is not correctly passing or the $token is empty.
I have already done a var_dump($token); die(); and get nothing but a white screen so not data is passing.
Here is the view
#extends('layouts.main')
#section('content')
<h1>Your Order</h1>
<h2>{{ $download->name }}</h2>
<p>£{{ ($download->price/100) }}</p>
<form action="" method="POST" id="payment-form" role="form">
<input type="hidden" name="did" value="{{ $download->id }}" />
<div class="payment-errors alert alert-danger" style="display:none;"></div>
<div class="form-group">
<label>
<span>Card Number</span>
<input type="text" size="20" data-stripe="number" class="form-control input-lg" />
</label>
</div>
<div class="form-group">
<label>
<span>CVC</span>
<input type="text" size="4" data-stripe="cvc" class="form-control input-lg" />
</label>
</div>
<div class="form-group">
<label>
<span>Expires</span>
</label>
<div class="row">
<div class="col-lg-1 col-md-1 col-sm-2 col-xs-3">
<input type="text" size="2" data-stripe="exp-month" class="input-lg" placeholder="MM" />
</div>
<div class="col-lg-1 col-md-1 col-sm-2 col-xs-3">
<input type="text" size="4" data-stripe="exp-year" class="input-lg" placeholder="YYYY" />
</div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-lg">Submit Payment</button>
</div>
</form>
#stop
Here is the route
Route::post('/buy/{id}', function($id)
{
Stripe::setApiKey(Config::get('laravel-stripe::stripe.api_key'));
$download = Download::find($id);
//stripeToken is form name, injected into form by js
$token = Input::get('stripeToken');
//var_dump($token);
// Charge the card
try {
$charge = Stripe_Charge::create(array(
"amount" => $download->price,
"currency" => "gbp",
"card" => $token,
"description" => 'Order: ' . $download->name)
);
// If we get this far, we've charged the user successfully
Session::put('purchased_download_id', $download->id);
return Redirect::to('confirmed');
} catch(Stripe_CardError $e) {
// Payment failed
return Redirect::to('buy/'.$id)->with('message', 'Your payment has failed.');
}
});
Here is the js
$(function () {
console.log('setting up pay form');
$('#payment-form').submit(function(e) {
var $form = $(this);
$form.find('.payment-errors').hide();
$form.find('button').prop('disabled', true);
Stripe.createToken($form, stripeResponseHandler);
return false;
});
});
function stripeResponseHandler(status, response) {
var $form = $('#payment-form');
if (response.error) {
$form.find('.payment-errors').text(response.error.message).show();
$form.find('button').prop('disabled', false);
} else {
var token = response.id;
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
$form.get(0).submit();
}
}
Here is the stripe.php in package
<?php
return array(
'api_key' => 'sk_test_Izn8gXUKMzGxfMAbdylSTUGO',
'publishable_key' => 'pk_test_t84KN2uCFxZGCXXZAjAvplKG'
);
Seems like the Config::get might be wrong.
It would have to be written this way.
Stripe::setApiKey(Config::get('stripe.api_key'));
I figured out the problem. In the source for the external javascript file, the "/" was missing at the beginning of the relative path. That is why the javascript file for the homepage was rendering fine but the /buy page was not rendering the javascript file.

Resources