How to get Stripe token in the controller of MVC framework? - javascript

I am using CodeIgniter and I can't get the Stripe Token in the controller function.
I got the PHP Error :
Severity: Notice
Message: Undefined index: stripeToken
Filename: controllers/App.php
Line Number: 339
Here is my code:
HTML:
<script src="https://js.stripe.com/v3/"></script>
<form action="<?php echo site_url('app/save/'.$event['code']);?>" method="post" id="payment-form">
<div class="form-row">
<label for="card-element">
Please pay:
</label>
<div id="card-element">
<!-- A Stripe Element will be inserted here. -->
</div>
<!-- Used to display form errors. -->
<div id="card-errors" role="alert"></div>
</div>
<button>Pay</button>
</form>
I checked the action URL in front-end. It shows the link:
https://www.example.com/enrollment/index.php/app/save/EVENT_A
This is the correct link to my controller.
The JS: (I have changed the key here)
<script>
// Create a Stripe client.
var stripe = Stripe('my_correct_key');
// Create an instance of Elements.
var elements = stripe.elements({
locale: 'en',
});
// Create an instance of the card Element.
var card = elements.create('card', {hidePostalCode: true});
// Add an instance of the card Element into the `card-element` <div>.
card.mount('#card-element');
// Handle real-time validation errors from the card Element.
card.addEventListener('change', function(event) {
var displayError = document.getElementById('card-errors');
if (event.error) {
displayError.textContent = event.error.message;
} else {
displayError.textContent = '';
}
});
// Handle form submission.
var form = document.getElementById('payment-form');
form.addEventListener('submit', function(event) {
event.preventDefault();
stripe.createToken(card).then(function(result) {
if (result.error) {
// Inform the user if there was an error.
var errorElement = document.getElementById('card-errors');
errorElement.textContent = result.error.message;
console.log(errorElement.textContent);
} else {
// Send the token to your server.
stripeTokenHandler(result.token);
console.log(result.token);
}
});
});
// Submit the form with the token ID.
function stripeTokenHandler(token) {
// Insert the token ID into the form so it gets submitted to the server
var form = document.getElementById('payment-form');
var hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', 'stripeToken');
hiddenInput.setAttribute('value', token.id);
form.appendChild(hiddenInput);
// Submit the form
form.submit();
}
</script>
In my Controller:
public function save($event_code){
$token=$_POST['stripeToken'];
echo $token;
}
I can't get the token here. I am not familiar with CodeIgniter. What's going wrong?

<!DOCTYPE html>
<html>
<head>
<title>Codeigniter Stripe Payment Integration Example - ItSolutionStuff.com</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style type="text/css">
.panel-title {
display: inline;
font-weight: bold;
}
.display-table {
display: table;
}
.display-tr {
display: table-row;
}
.display-td {
display: table-cell;
vertical-align: middle;
width: 61%;
}
</style>
</head>
<body>
<div class="container">
<h1>Codeigniter Stripe Payment Integration Example <br/> ItSolutionStuff.com</h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-default credit-card-box">
<div class="panel-heading display-table" >
<div class="row display-tr" >
<h3 class="panel-title display-td" >Payment Details</h3>
<div class="display-td" >
<img class="img-responsive pull-right" src="http://i76.imgup.net/accepted_c22e0.png">
</div>
</div>
</div>
<div class="panel-body">
<?php if($this->session->flashdata('success')){ ?>
<div class="alert alert-success text-center">
×
<p><?php echo $this->session->flashdata('success'); ?></p>
</div>
<?php } ?>
<form role="form" action="/stripePost" method="post" class="require-validation"
data-cc-on-file="false"
data-stripe-publishable-key="<?php echo $this->config->item('stripe_key') ?>"
id="payment-form">
<div class='form-row row'>
<div class='col-xs-12 form-group required'>
<label class='control-label'>Name on Card</label> <input
class='form-control' size='4' type='text'>
</div>
</div>
<div class='form-row row'>
<div class='col-xs-12 form-group card required'>
<label class='control-label'>Card Number</label> <input
autocomplete='off' class='form-control card-number' size='20'
type='text'>
</div>
</div>
<div class='form-row row'>
<div class='col-xs-12 col-md-4 form-group cvc required'>
<label class='control-label'>CVC</label> <input autocomplete='off'
class='form-control card-cvc' placeholder='ex. 311' size='4'
type='text'>
</div>
<div class='col-xs-12 col-md-4 form-group expiration required'>
<label class='control-label'>Expiration Month</label> <input
class='form-control card-expiry-month' placeholder='MM' size='2'
type='text'>
</div>
<div class='col-xs-12 col-md-4 form-group expiration required'>
<label class='control-label'>Expiration Year</label> <input
class='form-control card-expiry-year' placeholder='YYYY' size='4'
type='text'>
</div>
</div>
<div class='form-row row'>
<div class='col-md-12 error form-group hide'>
<div class='alert-danger alert'>Please correct the errors and try
again.</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<button class="btn btn-primary btn-lg btn-block" type="submit">Pay Now ($100)</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script type="text/javascript">
$(function() {
var $form = $(".require-validation");
$('form.require-validation').bind('submit', function(e) {
var $form = $(".require-validation"),
inputSelector = ['input[type=email]', 'input[type=password]',
'input[type=text]', 'input[type=file]',
'textarea'].join(', '),
$inputs = $form.find('.required').find(inputSelector),
$errorMessage = $form.find('div.error'),
valid = true;
$errorMessage.addClass('hide');
$('.has-error').removeClass('has-error');
$inputs.each(function(i, el) {
var $input = $(el);
if ($input.val() === '') {
$input.parent().addClass('has-error');
$errorMessage.removeClass('hide');
e.preventDefault();
}
});
if (!$form.data('cc-on-file')) {
e.preventDefault();
Stripe.setPublishableKey($form.data('stripe-publishable-key'));
Stripe.createToken({
number: $('.card-number').val(),
cvc: $('.card-cvc').val(),
exp_month: $('.card-expiry-month').val(),
exp_year: $('.card-expiry-year').val()
}, stripeResponseHandler);
}
});
function stripeResponseHandler(status, response) {
if (response.error) {
$('.error')
.removeClass('hide')
.find('.alert')
.text(response.error.message);
} else {
var token = response['id'];
$form.find('input[type=text]').empty();
$form.append("<input type='hidden' name='stripeToken' value='" + token + "'/>");
$form.get(0).submit();
}
}
});
</script>
</html>
/**
* Get All Data from this method.
*
* #return Response
*/
public function index()
{
$this->load->view('my_stripe');
}
/**
* Get All Data from this method.
*
* #return Response
*/
public function stripePost()
{
require_once('application/libraries/stripe-php/init.php');
\Stripe\Stripe::setApiKey($this->config->item('stripe_secret'));
\Stripe\Charge::create ([
"amount" => 100 * 100,
"currency" => "usd",
"source" => $this->input->post('stripeToken'),
"description" => "Test payment from itsolutionstuff.com."
]);
$this->session->set_flashdata('success', 'Payment made successfully.');
redirect('/my-stripe', 'refresh');
}

Related

Fill in radio input with database data

When I query the form returns the input radio filled with the data of the database, as shown:
<input type="radio" id="Estado" name="Estado" value="Pendente" ' . ( ($row6["Estado"]=='Pendente') ? 'checked' : '' ) .' readonly="true"> Pendente <input type="radio" id="Estado" name="Estado" value="Concluído" ' . ( ($row6["Estado"]=='Concluído') ? 'checked' : '' ) .' readonly="true"> Concluído
I also show in the completed image:
But when I click the edit button it changes the filled input radio and should not, because it no longer fills according to the data of the database, as I show in the image:
script:
$(document).on('click', '.edit_data6', function(){
var employee_id6 = $(this).attr("Id");
$.ajax({
url:"./fetch26",
method:"POST",
data:{employee_id6:employee_id6},
dataType:"json",
success:function(data){
$('#data6').val(data.data6);
$('#Colaborador6').val(data.Colaborador6);
$('#Observacao6').val(data.Observacao6);
$('#Estado1').prop("checked", data.Estado);
$('#Conclusao').val(data.Conclusao);
$('#employee_id6').val(data.Id6);
$('#insert6').val("Gravar");
$('#exampleModal6').modal('show');
}
});
});
$('#insert_form6').on("submit", function(event){
event.preventDefault();
if($('#Colaborador6').val() == "")
{
alert("Colaborador é necessário");
}
else
{
$.ajax({
url:".conexao26",
method:"POST",
data:$('#insert_form6').serialize()
,
beforeSend:function(){
$('#insert6').val("Inserting");
},
success:function(data){
$('#insert_form6')[0].reset();
$('#exampleModal6').modal('hide');
$('#employee_table').html(data);
location.reload("exampleModal6");
}
});
}
});
HTML:
<form method="post" id="insert_form6">
<div class="col-md-4 col-xs-4">
<div class="form-group">
<h6><label for="Data-name" class="col-form-label">Data</label></h6>
<h6><input type="date" name="data6" id="data6" value="<?php echo date("Y-m-d");?>"></h6>
</div>
</div>
<div class="col-md-4 col-xs-4">
<div class="form-group">
<h6><label for="Colaborador-text" class="col-form-label">Colaborador</label></h6>
<h6><select style="width:150px" name="Colaborador6" id="Colaborador6" required>
<option></option>
<?php
$sql = "SELECT Funcionario FROM centrodb.InfoLuvas WHERE Ativo = '1' AND Funcao = 'Limpeza' AND Valencia = 'LAR'";
$qr = mysqli_query($conn, $sql);
while($ln = mysqli_fetch_assoc($qr)){
echo '<option value="'.$ln['Funcionario'].'">'.$ln['Funcionario'].'</option>';
}
?>
</select></h6>
</div>
</div>
<div class="row">
</div>
<div class="col-md-6 col-xs-6">
<div class="form-group">
<h6><label for="Observacao-name" class="col-form-label">Tarefa Pendente</label></h6>
<textarea type="text" id="Observacao6" name="Observacao6" class="form-control"></textarea>
</div>
</div>
<div class="col-md-6 col-xs-6">
<div class="form-group">
<h6><label for="Observacao-name" class="col-form-label">Estado</label></h6>
<div style="clear:both;"></div>
<h6><input type="radio" id="Estado1" name="Estado" value="Pendente"> Pendente <input type="radio" id="Estado1" name="Estado" value="Concluido"> Concluído</h6>
</div>
</div>
<div class="row">
</div>
<div class="col-md-6 col-xs-6">
<div class="disabled form-group">
<h6><label for="Observacao-name" class="col-form-label">Conclusão</label></h6>
<textarea type="text" id="Conclusao" name="Conclusao" class="form-control"></textarea>
</div>
</div>
<div class="col-md-2 col-xs-2">
<div class="form-group">
<h6><input type="hidden" name="Nome6" id="Nome6" value="Ana Ribeiro" readonly="true"></h6>
</div>
</div>
<div class="col-md-2 col-xs-2">
<div class="form-group">
<h6><input type="hidden" name="NomeConc" id="NomeConc" value="Ana Ribeiro" readonly="true"></h6>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Sair</button>
<input type="hidden" name="employee_id6" id="employee_id6" />
<input type="submit" name="insert6" id="insert6" value="Registo" data-toggle="modal" class="btn btn-success" />
</div>
</form>
I'm trying these ways but I still do not solve the problem:
1st form:
var tipo_conta = $('.tipo_conta').val(data.Estado);
if(tipo_conta == 'Pendente'){
$('#Estado1').prop('checked' , true);
}else{
$('#Estado2').prop('checked' ,true);
}
2st form:
var radios = document.getElementsByName("Estado");
if (radios.value == "Pendente") {
radios.checked = true;
}else{
radios.checked = true;
}
Can anyone help?
I found the issue inside the HTML file. As #daddygames suggested you have used the same ID in both Radio button. see below
<h6>
<input type="radio" id="Estado1" name="Estado" value="Pendente"> Pendente
<input type="radio" id="Estado1" name="Estado" value="Concluido"> Concluído
</h6>
An ID must be unique. Update the ID and make it unique. Then change the code in .ajax script according to your need. This will help you.
First I created the variable lis to receive the value that the radio input receives from the database:
var lis = $("#Estado").val();
Then inside the data function I created another variable with the value that the radio input receives from the function:
var teste = data.Estado;
and finally I check with if:
if(lis == teste){
$('#Estado').prop('checked' , true);
}else{
$('#Estado1').prop('checked' ,true);
}
Full Code:
$(document).on('click', '.edit_data6', function(){
var employee_id6 = $(this).attr("Id");
var lis = $("#Estado").val();
$.ajax({
url:"./fetch26",
method:"POST",
data:{employee_id6:employee_id6},
dataType:"json",
success:function(data){
var teste = data.Estado;
$('#data6').val(data.data6);
$('#Colaborador6').val(data.Colaborador6);
$('#Observacao6').val(data.Observacao6);
if(lis == teste){
$('#Estado').prop('checked' , true);
}else{
$('#Estado1').prop('checked' ,true);
}
$('#Conclusao').val(data.Conclusao);
$('#employee_id6').val(data.Id6);
$('#insert6').val("Gravar");
$('#exampleModal6').modal('show');
}
});
});

HTML not processing correctly

We are working on a dApp that is giving us problems. The site loads OK and the button to open the subform ("Post My Rental") works. When I fill out the subform and click the 'submit' button, nothing happens. I have confirmed that I am connected to Metamask and Ganache, but no transaction goes through. Checking inspect in Chrome, no errors there. I suspect there is something missing in this code, but I can't find it. If you could help out, we would really appreciate it. Here is the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Rent My Place</title>
<!-- Title will appear as a tab in browser on webpage -->
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- Application -->
<link href="css/app.css" rel="stylesheet">
<!-- stylesheet refers to the look of the page, Font, color-->
</head>
<body>
<div class="container">
<!-- container that contains title panel-->
<div class="jumbotron text-center">
<p style="font-size:80px;padding: 1em;padding-top: 10px;padding-bottom: 10px; border:10px;border-style:solid;border-color:#c3c3c3;">
<font color = "#880015" >Rent My Place</font></p>
</div>
<div class="col-md-12" id="article-list">
<div class="row">
<div class="col-lg-12">
<!--<p id="account" class="welcome pull-right"></p>
<p id="accountBalance" class="welcome pull-left"></p>-->
</div>
</div>
<div class="row panel panel-default">
<div class="panel-heading clearfix">
<div class="panel-title">
<p style="font-size:24px;padding: 1em;padding-top: 10px;padding-bottom: 10px; border:5px;border-style:solid;border-color:#c3c3c3;">
<font color = "#880015">Renter's Tip: </font><font color = "#000000">Inspect the property before you send money.</font><br><font color = "#880015">Landlord's Tip: </font><font color = "#000000">Meet prospective tenants in person.</font></p>
<!-- Button that opens second window to a form to fill out-->
<button class="btn btn-info btn-lg pull-right" data-toggle="modal" data-target="#sellArticle">Post a Rental</button>
</div>
</div>
<!-- when the event button gets click, it will show the list-->
<ul id="events" class="collapse list-group"></ul>
</div>
<div id="articlesRow" class="row">
<!-- ARTICLES with pertinent item information LOAD HERE -->
</div>
</div>
</div>
<!--Result that is displayed after input-->
<div id="articleTemplate" style="display: none;">
<div class="row-lg-12">
<div class="panel panel-default panel-article">
<div class="panel-heading">
<h3 class="panel-title"></h3>
</div>
<div class="panel-body">
<strong>Beds</strong>: <span class="beds"></span><br/>
<strong>Baths</strong>: <span class="baths"></span><br/>
<strong>Address</strong>: <span class="propaddress"></span><br/>
<strong>Rental Price</strong>: <span class="rental_price"></span><br/>
<strong>Description</strong>: <span class="article_description"></span><br/>
<strong>Property is available for showing</strong>: <span class="available"></span><br/>
<strong>Contact Email</strong>: <span class="contact_email"></span><br/>
<!--<strong>Sold by</strong>: <span class="article-seller"></span><br/>-->
</div>
<div class="panel-footer">
<button type="button" class= "btn btn-primary btn-success btn-buy" onclick="App.buyArticle(); return false;">Buy</button>
</div>
</div>
</div>
</div>
<!-- Modal form to sell an article -->
<div class="modal fade" id="sellArticle" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Rent Your Place</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-lg-12">
<form>
<div class="form-group">
<!--NOTE: For radio buttons to work, 'name' field must match-->
<label for="property_type">Property Type</label>
<input type="radio" name="property" id="property_type" value="house" > House
<input type="radio" name="property" id="property_type" value="apartment" > Apartment
<input type="radio" name="property" id="property_type" value="duplex" > Duplex
</div>
<div class="form-group">
<label for="propaddress">Address</label>
<input type="text" class="form-control" id="propaddress" placeholder="Enter the address">
</div>
<div class="form-group">
<label for="beds">Beds</label>
<input type="radio" name="beds" id="beds" value="0"> Studio
<input type="radio" name="beds" id="beds" value="1"> One
<input type="radio" name="beds" id="beds" value="2"> Two
<input type="radio" name="beds" id="beds" value="3"> Three +
</div>
<div class="form-group">
<label for="baths">Baths</label>
<input type="radio" name="baths" id="baths" value="1"> One
<input type="radio" name="baths" id="baths" value="2"> Two
<input type="radio" name="baths" id="baths" value="3"> Three +
</div>
<div class="form-group">
<label for="rental_price">Rent (in USD)</label>
<input type="text" class="form-control" id="rental_price" placeholder="$" pattern="[0-9]+([\.,][0-9]+)?">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea type="text" class="form-control vresize" id="article_description" placeholder="Describe your property" maxlength="255"></textarea>
</div>
<div class="form-group">
<label for="available"></label>
<input type="checkbox" name="available" value="available" id="available"> Property is available for showing
</div>
<div class="form-group">
<label for="contact_email">Contact Email</label>
<input type="text" class="form-control" id="contact_email" placeholder="Enter your contact email">
</div>
</form>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary btn-success" data-dismiss="modal" onclick="App.sellArticle(); return false;">Submit</button>
<button type="button" class="btn" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div id="footer" class="container">
<nav class="navbar navbar-default navbar-fixed-bottom">
<div class="navbar-inner navbar-content-center text-center">
<p class="text-muted" credit>AXbean - © 2018</a></p>
</div>
</nav>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/OurRentalManualInputDataInitWeb3appMay22.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/web3.min.js"></script>
<script src="js/truffle-contract.js"></script>
</body>
</html>
Here is the app.js that is called:
App = {
web3Provider: null,
contracts: {},
account: 0x0,
loading: false,
init: function() {
return App.initWeb3();
},
initWeb3: function() {
// initialize web3
if(typeof web3 !== 'undefined') {
//reuse the provider of the Web3 object injected by Metamask
App.web3Provider = web3.currentProvider;
} else {
//create a new provider and plug it directly into our local node
App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
}
web3 = new Web3(App.web3Provider);
App.displayAccountInfo();
return App.initContract();
},
displayAccountInfo: function() {
web3.eth.getCoinbase(function(err, account) {
if(err === null) {
App.account = account;
$('#account').text(account);
web3.eth.getBalance(account, function(err, balance) {
if(err === null) {
$('#accountBalance').text(web3.fromWei(balance, "ether") + " ETH");
}
})
}
});
},
initContract: function() {
$.getJSON('OurRentalTestFromClassMay24.json', function(chainListArtifact) {
//added May24 to json file name
// get the contract artifact file and use it to instantiate a truffle contract abstraction
App.contracts.OurRentalTestFromClassMay24 = TruffleContract(chainListArtifact);
// set the provider for our contracts
App.contracts.OurRentalTestFromClassMay24.setProvider(App.web3Provider);
// listen to events
App.listenToEvents();
// retrieve the article from the contract
return App.reloadArticles();
});
},
reloadArticles: function() {
//avoid reentry bugs
if(App.loading){
return;
}
App.loading = true;
// refresh account information because the balance might have changed
App.displayAccountInfo();
var chainListInstance;
App.contracts.OurRentalTestFromClassMay24.deployed().then(function(instance) {
chainListInstance = instance;
return chainListInstance.getArticlesForSale();
}).then(function(articlesIds) {
// retrieve the article placeholder and clear it
$('#articlesRow').empty();
for(var i = 0; i < articlesIds.length; i++){
var articleId = articlesIds[i];
chainListInstance.articles(articleId.toNumber()).then(function(article){
App.displayArticle(article[0], article[1], article[3], article[4], article[5]);
});
}
App.loading = false;
}).catch(function(err) {
console.error(err.message);
App.loading = false;
});
},
displayArticle: function(id, seller, beds, baths, propaddress, rental_price, description, available, contact_email){
var articlesRow = $('#articlesRow');
var etherPrice = web3.fromWei(price, "ether");
var articleTemplate = $("#articleTemplate");
//articleTemplate.find('.panel-title').text(name);
articleTemplate.find('.beds').text(beds);
articleTemplate.find('.baths').text(baths);
articleTemplate.find('.propaddress').text(propaddress);
articleTemplate.find('.rental_price').text(rental_price);
articleTemplate.find('.description').text(description);
articleTemplate.find('.available').text(available);
articleTemplate.find('.contact_email').text(contact_email);
// articleTemplate.find('.article_price').text(etherPrice + " ETH");
articleTemplate.find('.btn-buy').attr('data-id', id);
articleTemplate.find('.btn-buy').attr('data-value', etherPrice);
//seller
if(seller == App.account){
articleTemplate.find('.article-seller').text("You");
articleTemplate.find('.btn-buy').hide();
}else{
articleTemplate.find('.article-seller').text(seller);
articleTemplate.find('.btn-buy').show();
}
//add this new article
articlesRow.append(articleTemplate.html());
},
sellArticle: function() {
// retrieve the detail of the article
// var _article_name = $('#article_name').val();
var _description = $('#description').val();
var _beds = $('#beds').val();
var _baths = $('#baths').val();
var _propaddress = $('#propaddress').val();
var _rental_price = $('#rental_price').val();
var _property_type = $('#property_type').val();
var _available = $('#available').val();
var _contact_email = $('#contact_email').val();
// var _article_price = $('#article_price').val();
// var _price = web3.toWei(parseFloat($('#article_price').val() || 0), "ether");
//if((_article_name.trim() == '') || (_price == 0)) {
// nothing to sell
// return false;
// }
App.contracts.OurRentalTestFromClassMay24.deployed().then(function(instance) {
return instance.sellArticle(_description, _beds, _baths, _propaddress, _rental_price, _property_type, _available, _contact_email, {
from: App.account,
gas: 500000
});
}).then(function(result) {
}).catch(function(err) {
console.error(err);
});
},
// listen to events triggered by the contract
listenToEvents: function() {
App.contracts.OurRentalTestFromClassMay24.deployed().then(function(instance) {
instance.LogSellArticle({}, {}).watch(function(error, event) {
if (!error) {
$("#events").append('<li class="list-group-item">' + event.args._name + ' is now for sale</li>');
} else {
console.error(error);
}
App.reloadArticles();
});
instance.LogBuyArticle({}, {}).watch(function(error, event) {
if (!error) {
$("#events").append('<li class="list-group-item">' + event.args._buyer + ' bought ' + event.args._name + '</li>');
} else {
console.error(error);
}
App.reloadArticles();
});
});
},
buyArticle: function() {
event.preventDefault();
// retrieve the article price and data
var _articleId = $(event.target).data('id');
var _price = parseFloat($(event.target).data('value'));
App.contracts.OurRentalTestFromClassMay24.deployed().then(function(instance){
return instance.buyArticle(_articleId, {
from: App.account,
value: web3.toWei(_price, "ether"),
gas: 500000
});
}).catch(function(error) {
console.error(error);
});
}
};
$(function() {
$(window).load(function() {
App.init();
});
});

Show loading image while my controller execute a function

need to show an image while my function "Mailcontroller/sendMail" is working sending an email. I passed values to this function from my view by a submit button in a form. I had try with other examples that I saw here, but I can't get what I need.
My view:
<div class="container" style="margin-right: 100px;">
<div class="row">
<div class="col-md-9 col-md-offset-3">
<form class="form-horizontal" enctype='multipart/form-data' method="POST" action="<?=base_url();?>Cpersona/sendMail">
<fieldset>
<div class="form-group">
<div class="col-md-6">
<label style="font-size: 15px; margin-left: 215px;">Destinatarios</label><br />
<input type="button" name="agregardes" id="agregardes" onclick="llenarDestino();correos();" style="font-size: 15px; margin-left: 215px;" value="Agregar Destinatarios">
<input style="margin-left: 215px;" id="email" name="email" type="text" class="form-control" required>
<label style="font-size: 15px; margin-left: 215px;">Asunto</label><br />
<input style="margin-left: 215px;" type="text" class="form-control" name="asunto" id="asunto">
<label style="font-size: 15px; margin-left: 215px;">Mensaje</label><br />
</div>
<div class="col-md-9" style="float: right;">
<textarea id="editor" name="mensaje"></textarea>
</div>
</div>
<section>
<div style="margin-left: 215px;">
<p id="msg"></p>
<input type="file" id="file" name="file" />
</div>
</section>
<div>
<br />
<input style="margin-left: 215px;" class="btn btn-primary" type="submit" id="enviar" name="enviar" value="Enviar">
</div>
</fieldset>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#enviar').click(function(){
//Añadimos la imagen de carga en el contenedor
$('#content').html('<div><img src="../assets/images/loading.gif"/></div>');
var page = $(this).attr('data');
var dataString = 'page='+page;
$.ajax({
type: "GET",
url: "http://localhost/empresa/Cpersona/sendMail",
data: dataString,
success: function(data) {
//Cargamos finalmente el contenido deseado
$('#content').fadeIn(1000).html(data);
}
});
});
});
</script>
An extract of my Controller:
public function sendMail{
$data = array(
'id_usuario' => $usuario,
'fecha' => $fecha,
'id' => $cliente
);
$this->Modelo_datos->historial($data);
$this->email->set_newline("\r\n");
$this->email->from('correopruebas#consultora.cl');
$this->email->to($value);
$this->email->subject($asunto);
$this->email->message($enviar);
//$path = set_realpath('./uploads/');
//$adjunto = $path.$archivo;
if($this->email->send())
{
$this->load->helper("file");
delete_files('./uploads/');
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Correo Enviado!!')
window.location.href='verLista';
</SCRIPT>");
}
else
{
show_error($this->email->print_debugger());
$this->load->helper("file");
delete_files('./uploads/');
}
}
}
first add image(that you want to be displayed) with id loader and make it hidden by using style="display:none";
loader = document.querySelector("#loader");
function sendMail() {
loader.style.display = "block";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
loader.style.display="none";
// some thing here when email is sent
}
};
xhttp.open("GET", "your_send_mail_file.php?send=true", true);
xhttp.send();
}
and in your_send_mail_file.php
<?php
if (isset($_GET["send"]) && $_GET["send"] === "true") {
$test = new your_class(); // that_contain_the_sendMail function;
$test->sendMail();
}

Ajax success function not working on the second time

Aim: Continue to display any form validation errors through json callback
Problem: When I submit on the form with invalid input it shows an error message in a div element. If all inputs are valid it will process the ajax request and show a success message in a div element. After which, the form resets but the modal remain open. When I try to again validate the input in doesn't show any error message. When I try to test the valid input still the same no message shown.
In short: Ajax success function not working on the second time.
Here's my code:
Bootstrap Modal (where my form inputs placed)
<div class="modal fade" id='frmModal'>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button class='close' data-dismiss='modal'>×</button>
<h4 class='title'>Add new data</h4>
</div>
<div class="modal-body">
<?php echo form_open('Employee/save',array('id'=>'frm', 'class'=>'form-horizontal')); ?>
<div id="message"></div>
<div class="form-group">
<label for='fname' class='col-md-3 control-label'>First Name:</label>
<div class="col-md-9">
<input type="text" name="fname" id='fname' class='form-control' placeholder='First Name...'>
</div>
</div>
<div class='form-group'>
<label for='lname' class='col-md-3 control-label'>Last Name:</label>
<div class="col-md-9">
<input type="text" name="lname" id='lname' class='form-control' placeholder='Last Name...'>
</div>
</div>
<div class='form-group'>
<label for='age' class='col-md-3 control-label'>Age:</label>
<div class="col-md-9">
<input type="text" name="age" id='age' class='form-control' placeholder='Age...'>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary action" type='submit'><i class='glyphicon glyphicon-floppy-disk'></i> Save Data</button>
</div>
<?php echo form_close(); ?>
</div>
</div>
</div>
</div>
Jquery Code:
$(document).on('submit','#frm',function(e){
e.preventDefault();
var form = $('#frm');
$.ajax({
url: form.attr('action'),
type: 'POST',
dataType: 'json',
encode: true,
data: form.serialize(),
success: function(data) {
if (!data.success) {
if (data.errors) {
$('#message').html(data.errors).addClass('alert alert-danger');
}
} else {
reloadData();
$('#message').html("<span class='glyphicon glyphicon-ok'></span> " + data.message).removeClass('alert alert-danger').addClass('alert alert-success');
setTimeout(function() {
$("#message").fadeTo(500, 0).slideUp(500, function() {
$(this).remove();
});
}, 3000);
$('#frm')[0].reset();
}
}
});
});
CodeIgniter Controller:
$this->form_validation->set_rules('fname','First Name', 'required|trim');
$this->form_validation->set_rules('lname','Last Name', 'trim|required');
$this->form_validation->set_rules('age','Age', 'trim|numeric|required');
if($this->form_validation->run()===FALSE)
{
$info['success'] = false;
$info['errors'] = validation_errors();
}
else
{
$info['success'] = true;
$data = array(
"firstname" => $this->input->post('fname'),
"lastname" => $this->input->post('lname'),
"age" => $this->input->post('age'),
);
$this->Employee_model->save('ci_table', $data);
$info['message'] = 'Successfully saved data';
}
$this->output->set_content_type('application/json')->set_output(json_encode($info));
}
I think I understand... The form still works but the messages do not appear? If so then try the below...
You are removing the #message element instead of clearing it... try:
$("#message").fadeTo(500, 0).slideUp(500, function() {
$(this).empty();
This way you are emptying the #message element instead of removing it completely..

Validate form using jqueryvalidate.js and ckeditor Codeigniter

Hello. I have a form that gets validated by jqueryvalidate.js. I have a drop down menu and the menu will be different when I choose "Library Asset" because I need to choose another drop down menu that is hidden.
The problem is, when I am not choose other menu that is not showing another drop down menu..
the required rules still implemented.. so the form can't be submitted except the one that is showing another drop down menu..
Can someone help me here?
This is my code:
View(Js):
<script type="text/javascript">
function showbook()
{
var domObj1 = document.getElementById('emptybox');
var domObj2 = document.getElementById('showupbox');
if(domObj1.style.display =='none')
{
domObj1.style.display = 'block';
domObj2.style.display = 'none';
}
else
{
domObj1.style.display = 'none';
domObj2.style.display = 'block';
}
}
function closebook()
{
var domObj1 = document.getElementById('emptybox');
var domObj2 = document.getElementById('showupbox');
if(domObj1.style.display =='none')
{
domObj1.style.display = 'block';
domObj2.style.display = 'none';
}
}
function showhidebook()
{
console.log($('#CategoryAdviceSelect').val());
if($('#CategoryAdviceSelect').val() == 1)
{
showbook();
}
else{
closebook();
}
}
My validation rules:
<script>
$().ready(function() {
$("#feedback_form").validate({
ignore: "input:hidden:not(input:hidden.required)",
rules: {
CategoryAdviceSelect:"required",
Subject:"required",
Advice:"required",
BookSelect:"required"
},
messages: {
CategoryAdviceSelect:"Please select one of category advice",
Subject:"This field is required",
Advice:"This field is required",
BookSelect:"This field is required"
},
errorElement: "span",
highlight: function(element) {
$(element).parent().addClass("help-block");
},
unhighlight: function(element) {
$(element).parent().removeClass("help-block");
}
});
});
</script>
And my html view
<div class="row-fluid ">
<div class="box">
<hr>
<div class="paragraph">
<p>For enquiries about our services, write to: helpdesk#library.binus.ac.id.</p>
<p>You may also reach us at our helpdesk number 62-21-5350660. We value your feedback. Please fill in the form below, and help us improve our services.</p>
<p>Talk to me here
<a href = 'ymsgr:sendim?me_lieza93'>
<img src="http://opi.yahoo.com/online?u=me_lieza93&m=g&t=1" border=0>
</a>
</p>
</div>
<!--START FORM-->
<form id="feedback_form" name="feedback_form" action="<?php echo base_url();?>feedback/feedback/insert_to_db" method="post" class="form-horizontal" novalidate="novalidate">
<div class="control-group">
<!--FEEDBACK TYPE-->
<label class="span2 control-label" >Feedback for</label>
<div class="controls with-tooltip">
<select class="input-tooltip span5" tabindex="2" id="CategoryAdviceSelect" name="CategoryAdviceSelect" onchange="showhidebook();" >
<option value="" disabled selected>Choose Your Feedback For..</option>
<?php
for($x = 0 ; $x < count($feedback) ; $x++)
{ ?>
<option value="<?php echo $feedback[$x]['CategoryAdviceId']?>"><?php echo $feedback[$x]['CategoryAdviceName'] ?></option>
<?php
} ?>
</select>
</div>
</div>
<!--SUBJECT-->
<div class="control-group">
<label for="limiter" class="control-label">Subject</label>
<div class="controls">
<input type="text" class="span5" maxlength="50" id="Subject" name="Subject" placeholder="Type Your Feedback Subject.." />
<p class="help-block"></p>
</div>
</div>
<div id="emptybox"></div>
<!--CHOOSE BOOK-->
<div id="showupbox" style="display: none;">
<div class="control-group">
<label class="control-label">Choose Book</label>
<div class="controls">
<select class="chzn-select span5" tabindex="2" id="BookSelect" name="BookSelect">
<option value="" disabled selected>Choose Your Feedback For..</option>
<?php
for($y = 0 ; $y < count($booklist) ; $y++)
{ ?>
<option value="<?php echo $booklist[$y]['bi']?>"><?php echo $booklist[$y]['AssetTitle']?></option>
<?php
} ?>
</select>
</div>
</div>
</div>
<!--ADVICE-->
<div class="control-group">
<label for="limiter" class="control-label" >Suggestion</label>
<div class="controls">
<?php echo $this->ckeditor->editor("Advice",""); ?>;
</div>
</div>
<!--div class="alert alert-success">
<a class="close" data-dismiss="alert">×</a>
<strong>Success!</strong> Thanks for your feedback!
</div-->
<div class="bton1">
<button class="btn btn-primary round" type="submit">Submit</button>
<button class="btn btn-primary round" type="refresh">Reset</button>
</div>
</form>
</div><!--END BOX-->
Finally I can solve this..
<script>
$(document).ready(function() {
for(var name in CKEDITOR.instances) {
CKEDITOR.instances["Advice"].on("instanceReady", function() {
// Set keyup event
this.document.on("keyup", updateValue);
// Set paste event
this.document.on("paste", updateValue);
});
function updateValue() {
CKEDITOR.instances["Advice"].updateElement();
$('textarea').trigger('keyup');
}
}
$("#feedback_form").validate({
ignore: 'input:hidden:not(input:hidden.required)',
rules: {
CategoryAdviceSelect:"required",
Subject:"required",
Advice:"required",
BookSelect:{
required: function(element){
return $("#CategoryAdviceSelect").val()==1;
}
}
},
messages: {
CategoryAdviceSelect:"Please select one of category advice",
Subject:"This field is required",
Advice:"This field is required",
BookSelect:"This field is required",
},
errorElement: "span",
errorPlacement: function (error, element) {
if ($(element).attr('name') == 'Advice') {
$('#cke_Advice').after(error);
} else {
element.after(error);
}
},
highlight: function(element) {
$(element).parent().addClass("help-block");
},
unhighlight: function(element) {
$(element).parent().removeClass("help-block");
}
});
});
</script>

Categories

Resources