CodeIgniter can't Login in the first time - codeigniter

I'm new in CI. I just created login form in CI, Every first time I open my browser and login to the form it doesn't redirect to the page according to the action even the password & user are correct. it's only refresh the page. but the second time I do the login, it works fine.
I have trying with different browser and using incognito doesn't help either. So the error only occurs the first time I running the script.
any ideas?
Thanks
here's the view:
< script type = "text/javascript" >
$(function() {
$("#login_form").submit(function(evt) {
evt.preventDefault();
var url = $(this).attr('action');
var postData = $(this).serialize();
$.post(url, postData, function(o) {
if (o.result === 1) {
window.location.href = '<?=site_url('
dashboard ')?>';
} else {
alert('Invalid login');
}
}, 'json');
});
}); <
/script>
<div class="row">
<div class="span6">
<form id="login_form" class="form-horizontal" method="post" action="<?=site_url('api/login')?>">
<div class="control-group">
<label class="control-label">Login</label>
<div class="controls">
<input type="text" name="login" class="input-xlarge" />
</div>
</div>
<div class="control-group">
<label class="control-label">Password</label>
<div class="controls">
<input type="password" name="password" class="input-xlarge" />
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" value="Login" class="btn btn-primary btn-lg btn-block" />
</div>
</div>
</form>
</div>
</div>
And here's my controller:
<?php
public function login()
{
$login = $this->input->post('login');
$password = $this->input->post('password');
$this->load->model('user_model');
$result = $this->user_model->get([
'login' => $login,
'password' => hash('sha256', $password . PASX)
]);
$this->output->set_content_type('application_json');
if ($result){
$this->session->set_userdata(['user_id' => $result[0]['user_id']]);
$this->output->set_output(json_encode(['result' => 1]));
return false;
}
$this->output->set_output(json_encode(['result' => 0]));
}

Related

Modal box form submit in Laravel

I have done a Modal form and trying to submit the form, but it is not working.
This is my form
<div class="modal-body">
<div class="card-body">
<form action="{{ url('/admin/modaluser/add')}}" method="POST" id="customerSubmit">
<div class="row">
<div class="col">
#if(session('success'))
<div class="alert alert-success">{{session('success')}}</div>
#endif
#if(session('error'))
<div class="alert alert-error">{{session('error')}}</div>
#endif
#csrf
<div class="row">
<div class="form-group col-md-6">
<label for="name">Name</label>
<input class="form-control" name="name" id="name"
type="text"
placeholder="Enter Name" data-original-title="" title=""
required>
</div>
<div class="form-group col-md-6">
<label for="hpcontact">HP Contact No</label>
<input class="form-control" name="hpcontact" id="hpcontact"
type="text"
placeholder="HP Contact No" data-original-title="" title=""
required>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="icno">IC No</label>
<input class="form-control" name="icno" id="icno"
type="text"
placeholder="Enter IC No" data-original-title="" title=""
required>
</div>
<div class="form-group col-md-6">
<label for="homephone">Home Contact No</label>
<input class="form-control" name="homephone" id="homephone"
type="text"
placeholder="Enter home contact no" data-original-title="" title=""
required>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="dob">D.O.B</label>
<input class="form-control" name="dob" id="dob"
type="date"
placeholder="Enter DOB" data-original-title="" title=""
required>
</div>
<div class="form-group col-md-6">
<label for="officeno">Office No</label>
<input class="form-control" name="officeno" id="officeno"
type="text"
placeholder="Enter Office No" data-original-title="" title=""
required>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="address">Address</label>
<input class="form-control" name="address" id="address"
type="text"
placeholder="Enter Address" data-original-title="" title=""
required>
</div>
<div class="form-group col-md-6">
<label for="email">Email</label>
<input class="form-control" name="email" id="email"
type="email"
placeholder="Enter Email" data-original-title="" title=""
required>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
This is my jQuery for the Ajax
$(document).ready(function(){
$('body').on('click','#addcustomer',function(e){
e.preventDefault();
// AJAX request
console.log($('#customerSubmit').serialize())
$.ajax({
method: 'post',
url: '/admin/modaluser/add',
data: $('#customerSubmit').serialize(),
success: function(msg) {
console.log(msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("some error");
}
});
});
});
And this my Controller
public function adduser(Request $request)
{
if(Request::ajax()){
$name = Input::get( 'name' );
$hpcontact = Input::get( 'hpcontact' );
$icno = Input::get( 'icno' );
$homephone = Input::get( 'homephone' );
$dob = Input::get( 'dob' );
$officeno = Input::get( 'officeno' );
$address = Input::get( 'address' );
$email = Input::get( 'email' );
$customer = new Customer();
$customer->name = $name;
$customer->hpcontact = $hpcontact;
$customer->icno = $icno;
$customer->homephone = $homephone;
$customer->dob = $dob;
$customer->officeno = $officeno;
$customer->address = $address;
$customer->email = $email;
$customer->save();
$response = array(
'status' => 'success',
'msg' => 'Customer created successfully',
);
return Response::json($response);
}
else {
echo 'no';
exit;
}
}
And finally, this is my Router
Route::post('modaluser/add', 'CustomerController#adduser')->name('customer.adduser');
When I click the button, nothing has happened. But this error is coming.
POST http://127.0.0.1:8000/admin/modaluser/add 500 (Internal Server Error)
And showing me the console error, which is defined in the ajax. Is there anything wrong I am doing. This is my First Ajax in Laravel. Please help me to solve this. Thanks in advance.
add /admin into your route:
Route::post('admin/modaluser/add', 'CustomerController#adduser')->name('customer.adduser');
and change url path in ajax:
$(document).ready(function(){
$(document).on('submit','#customerSubmit',function(e){
e.preventDefault();
// AJAX request
console.log($(this).serialize())
$.ajax({
method: 'post',
url: "{{route('customer.adduser')}}",
data: $(this).serialize(),
success: function(msg) {
console.log(msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("some error");
}
});
});
});
remove form action:
<form action="" method="POST" id="customerSubmit">
You should check all class used paths declared on top of the controller or not. You should add the CSRF header in your ajax request.
$.ajax({
method: 'post',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "route name or url",
data: $(this).serialize(),
success: function(msg) {
console.log(msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("some error");
}
});

Codeigniter Ajax Crud using DataTables - Insert _ Add Data

There is this codeigniter tutorial from weblesson youtube page About working with Datatables and Codeigniter.
But i'm having some difficulties inserting data into the database.
Controller:
function user_action(){
if($_POST["action"] == "Add")
{
$insert_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post("last_name"),
'image' => $this->upload_image()
);
$this->load->model('crud_model');
$this->crud_model->insert_crud($insert_data);
echo 'Data Inserted';
}
}
function upload_image()
{
if(isset($_FILES["user_image"]))
{
$extension = explode('.', $_FILES['user_image']['name']);
$new_name = rand() . '.' . $extension[1];
$destination = './upload/' . $new_name;
move_uploaded_file($_FILES['user_image']['tmp_name'], $destination);
return $new_name;
}
}
View Class:
<div id="userModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="user_form">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add User</h4>
</div>
<div class="modal-body">
<label>Enter First Name</label>
<input type="text" name="first_name" id="first_name" class="form-control" />
<br />
<label>Enter Last Name</label>
<input type="text" name="last_name" id="last_name" class="form-control" />
<br />
<label>Select User Image</label>
<input type="file" name="user_image" id="user_image" />
</div>
<div class="modal-footer">
<input type="submit" name="action" class="btn btn-success" value="Add" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
When i ran this code, i got the following errors:
Error message
And when i did
if(isset($_POST["action"]) && $_POST["action"] == "Add")
i got an empty alert box
In controller,at your constructor load url helper. and save file as Main.php with code::
function __construct()
{
$this->load->helper('url');
}
function user_action(){
if($_POST["action"] == "Add")
{
$insert_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post("last_name"),
'image' => $this->upload_image()
);
$this->load->model('crud_model');
$this->crud_model->insert_crud($insert_data);
echo 'Data Inserted';
}
}
function upload_image()
{
if(isset($_FILES["user_image"]))
{
$extension = explode('.', $_FILES['user_image']['name']);
$new_name = rand() . '.' . $extension[1];
$destination = './upload/' . $new_name;
move_uploaded_file($_FILES['user_image']['tmp_name'], $destination);
return $new_name;
}
}
at your view define a input of type hidden with name action and value add.And define action of your form.As follows..
<div id="userModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="user_form" action="<?php echo base_url('main/user_action');?>">
<input type="hidden" name="action" value="add">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add User</h4>
</div>
<div class="modal-body">
<label>Enter First Name</label>
<input type="text" name="first_name" id="first_name" class="form-control" />
<br />
<label>Enter Last Name</label>
<input type="text" name="last_name" id="last_name" class="form-control" />
<br />
<label>Select User Image</label>
<input type="file" name="user_image" id="user_image" />
</div>
<div class="modal-footer">
<input type="submit" name="action" class="btn btn-success" value="Add" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
Hope it will works..
I did fix the problem but don't know if it's the best way to do it
what i did was change this two codes:
controller:
public function user_action(){
if(isset($_POST["action"]) && $_POST["action"] == "Add")
{
$insert_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post("last_name"),
'image' => $this->upload_image()
);
$this->load->model('crud_model');
$this->crud_model->insert_crud($insert_data);
echo 'Data Inserted';
}
and Ajax:
$(document).on('submit', '#user_form', function(event){
event.preventDefault();
var firstName = $('#first_name').val();
var lastName = $('#last_name').val();
var extension = $('#user_image').val().split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
{
alert("Invalid Image File");
$('#user_image').val('');
return false;
}
if(firstName != '' && lastName != '')
{
$.ajax({
url:"<?php echo base_url() . 'main/user_action'?>",
method:'POST',
data:new FormData(this),
contentType:false,
processData:false,
success:function(data)
{
alert(data);
$('#user_form')[0].reset();
$('#userModal').modal('hide');
dataTable.ajax.reload();
}
});
}
else
{
alert("Bother Fields are Required");
}
});
for controller:
where it say:
if(isset($_POST["action"]) && $_POST["action"] == "Add")
remove it
In in the Ajax Code:
create a link variable to get the action attribute of the form like so:
var link = $('#user_form').attr('action');
and parse it to to the ajax url.
And that's it!
I did fix the problem but don't know if it's the best way to do it
<div class="modal-footer">
<input type="hidden" name="action" class="btn btn-success" value="Add">
<input type="submit" name="action" class="btn btn-success" value="Add" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
This is a hidden field that we have used to describe database operations like insert, update, delete

Laravel : Insert data into database using Bootstrap Modal

I want to insert some data into database using Bootstrap Modal. But the problem is Save button doesn't work properly on Bootstrap Modal as I couldn't insert the data into database through form. If anyone could help me to find it please!?
Here is the form part in blade:
<div id="myAlert" class="modal hide">
<div class="modal-header">
<button data-dismiss="modal" class="close" type="button">×</button>
<h3>Create User</h3>
</div>
<div class="modal-body">
<div class="row-fluid">
<div class="span12">
<div class="widget-box">
<div class="widget-content nopadding">
<form action="#" method="get" id="userForm" class="form-horizontal">
<div class="control-group">
<label class="control-label">Name :</label>
<div class="controls">
<input class="span11" placeholder="Name" type="text">
</div>
</div>
<div class="control-group">
<label class="control-label">Email :</label>
<div class="controls">
<input class="span11" placeholder="Email" type="email">
</div>
</div>
<div class="control-group">
<label class="control-label">Password</label>
<div class="controls">
<input class="span11" placeholder="Enter Password" type="password">
</div>
</div>
<div class="control-group">
<label class="control-label">Confirm Password</label>
<div class="controls">
<input class="span11" placeholder="Confirm Password" type="password">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer"><a data-dismiss="modal" class="btn btn-primary" href="#">Confirm</a> <a
data-dismiss="modal" class="btn" href="#">Cancel</a>
</div>
</div>
Here is the Ajax Part :
$('#userForm').on('success.form.fv', function(e) {
e.preventDefault();
$.ajax({
method: 'POST',
action:"{{ url('/register') }}",
data: $form.serialize()
});
});
You need the submit button. Try to put this code inside your form.
<button type="submit" class="btn btn-primary">Register</button>
Problem with your current Confirm button is: 1) he don't have type=submit; 2) he is outside the form.
first of all add type="submit" to your button
secondly check your network tab in the dev tools in your browser and check the request does it go to /register or not ?
if the request is hitting /register what's the parameters ?
Change form method get to post
I answer here for ajax call
Laravel ajax internal servor 500 (internal server-error)
Your input type elements are missing name attribute
<input class="span11" placeholder="Name" name="name" type="text">
<input class="span11" placeholder="Email" name="email" type="email">
<input class="span11" placeholder="Enter Password" name="password" type="password">
<input class="span11" placeholder="Confirm Password" name ="confirm_password" type="password">
You then retrieve the content using Request or Input by passing the value of the name attribute
At first change your form method from get to post. Then add save button with id btnSave.
Ajax :
$("#btnSave").click(function(e){
e.preventDefault()
var $form = $("#userForm");
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
success: function (data, status) {
if(data.error){
return;
}
alert(data.success); // THis is success message
$('#myModal').modal('hide'); // Your modal Id
},
error: function (result) {
}
});
});
In controller :
public function store(Request $request)
{ try {
$inputs = $request->all();
ModelName::create($inputs);
$data = ['success' =>'Data saved successfully'];
} catch (\Exception $e) {
$data = ['error' =>$e->getMessage()];
}
return Response::json($data);
}
Form part in blade:
<div class="modal-footer"><a data-dismiss="modal" class="btn btn-primary" id="btnAdd">Confirm</a></div>
Ajax Part
$('#btnAdd').click(function () {
$.ajax({
url: '{{url('/register')}}',
type: 'POST',
data: $('#userForm').serialize(),
success: function (object) {
},
error: function (result) {
}
});
});

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.

Ajax jquery form submission codeigniter doesn't work

i want to create form submit by using ajax jquery,but everytime i press submit, the form is always executed directly to controller without passing ajax call.
is there anything wrong with my code?
controller:
public function simpanSaran(){
$this->form_validation->set_rules('nama', 'Nama', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('sub', 'Subjek', 'required');
$this->form_validation->set_rules('isi', 'Isi', 'required');
if ($this->form_validation->run() == FALSE) {
$this->content("user/hal_saran");
}
else {
$insert = array(
'nama' => $this->input->post('nama'),
'email' => $this->input->post('email'),
'subjek' => $this->input->post('sub'),
'komentar' => $this->input->post('isi'),
);
$this->db->insert('guest',$insert);
}
}
my view,with ajax jquery:
<script>
$(document).ready(function() {
$('#myForm').submit(function() {
e.preventDefault();
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
success: function() {
$('#result').slideDown();
}
}
})
return false;
});
$('.close').click(function(){
$('#result').slideUp();
});
});
</script>
<div class=" span9">
<div class="span9" id="result" style="display:none;height:80px;">
<div class="notices" >
<div class="bg-color-green" style="height:60px;">
<div class="notice-header fg-color-white">Terima Kasih!</div>
<div class="notice-text">Anda telah Memberikan Kritik dan Saran pada Kami.</div>
</div>
</div>
</div>
<div id="hid" style="display:none;"></div>
<?php
$attr = array('id' => 'myForm');
echo (form_open('lowongan/simpanSaran',$attr)) ?>
<div class="input-control text span3" style="height:40px;">
<input type="text" placeholder="Nama" name="nama" required/>
<button class="btn-clear"></button>
</div>
<div class="input-control text span3" style="height:40px;">
<input type="text" placeholder="Email" name="email" required/>
<button class="btn-clear"></button>
</div>
<div class="input-control text span3" style="height:40px;">
<input type="text" placeholder="Subjek" name="sub" required/>
<button class="btn-clear"></button>
</div>
<div class="input-control textarea span9" >
<textarea placeholder="Komentar" name="isi" style="height:200px;" required></textarea>
<button type="submit" class="fg-color-white bg-color-purple" style="margin-top:20px;"><i class="icon-comments-5"></i> Kirim</button>
<p>*Saran atau kritik akan di-reply melalui email</p>
</div>
<?php echo(form_close())?>
</div>
Just a small change :
$('#myForm').submit(function(e) {
e.preventDefault();

Resources