Ajax jquery form submission codeigniter doesn't work - codeigniter

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();

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");
}
});

Symfony\Component\HttpKernel\Exception\HttpException- Ajax post request

In the step 2 of a multi step form, if a radio button is selected and "go to step 3" is clicked or if no radio button is selected and "go to step 3" is clicked it appears always this error below:
{message: "", exception: "Symfony\Component\HttpKernel\Exception\HttpException",…}
exception"Symfony\Component\HttpKernel\Exception\HttpException"
file "/Users/johnw/projects/store/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php" line : 203 message: "" trace:[{,…},…]
Do you know where can be the issue?
Html for the step 2:
<form method="post" id="step2form" action="">
<h6>Payment method</h6>
<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="radio" name="payment_method" value="option1">
<label class="form-check-label d-flex align-items-center" for="exampleRadios1">
<span class="mr-auto">Payment method 1</span>
</label>
</div>
<br>
<div class="form-check">
<input class="form-check-input" type="radio" name="payment_method" value="option1">
<label class="form-check-label d-flex align-items-center" for="exampleRadios1">
<span class="mr-auto">Payment method 2</span>
</label>
</div>
</div>
<br>
<div class="text-right">
<button type="button" href="#step3" data-toggle="tab" role="tab"
class="btn btn-outline-primary prev-step">
Go back to step 2
</button>
<input type="submit" href="#step2" id="goToStep3"
class="btn btn-primary btn float-right next-step"
value="Go to step 3"/>
</div>
</form>
PaymentController method to handle ajax request for step 2:
public function storePaymentMethods(Request $request, $id, $slug = null, Validator $validator){
$validator = Validator::make($request->all(),[
'payment_method' => 'required',
]);
if($validator->passes())
{
return response()->json([
'success' => true,
'message' => 'success'
], 200);
}
$errors = $validator->errors();
$errors = json_decode($errors);
return response()->json([
'success' => false,
'errors' => $errors
], 422);
}
ajax:
$('#goToStep3').on('click', function (event) {
event.preventDefault();
var custom_form = $("#" + page_form_id);
$.ajax({
method: "POST",
url: '{{ route('products.storePaymentMethods', compact('id','slug') ) }}',
data: custom_form.serialize(),
datatype: 'json',
success: function (data, textStatus, jqXHR) {
},
error: function (data) {
var errors = data.responseJSON;
var errorsHtml = '';
$.each(errors['errors'], function (index, value) {
errorsHtml += '<ul class="alert alert-danger mt-3"><li class="text-danger">' + value + '</li></ul>';
console.log(errorsHtml);
});
$('#response').show().html(errorsHtml);
}
});
you have not added any csrf token with your form. There are several ways to do it like below mentioned ways -
Add {{ csrf_field() }} inside your form
or add token with your ajax request like _token:"{{ csrf_token() }}"

Ajax post request- Unresolvable dependency resolving and error 500

I'm trying to create a multi-step form using jQuery anad AJAX. But Im getting this error when "go to step 2" is clicked:
jquery.min.js:4 POST http://store.test/product/1/product-test/payment/storeUserInfo 500 (Internal Server Error)
Also when clicking in network tab and then click in "storeUserInfo" it appears:
exception
:
"Illuminate\Contracts\Container\BindingResolutionException"
file
:
"/Users/jakeB/projects/store/vendor/laravel/framework/src/Illuminate/Container/Container.php"
line
:
933
message
:
"Unresolvable dependency resolving [Parameter #1 [ <required> array $data ]] in class Illuminate\Validation\Validator"
Do you know where is the error?
In the PaymentController there is the storeUserInfo() Method that is the method for the step 1:
public function storeUserInfo(Request $request, $id, $slug = null, Validator $validator){
$validator = Validator::make($request->all(),[
'buyer_name' => 'required|max:255|string',
'buyer_surname' => 'required|max:255|string',
'buyer_email' => 'required|max:255|string',
'name_invoice' => 'required|max:255|string',
'country_invoice' => 'required|max:255|string',
]);
if ($validator->fails()) {
if($request->ajax())
{
return response('test');
}
$this->throwValidationException(
$request, $validator
);
}
}
Route:
Route::post('/product/{id}/{slug?}/payment/storeUserInfo', [
'uses' => 'PaymentController#storeUserInfo',
'as' =>'products.storeUserInfo'
]);
// step 1 and step 2 html
<div class="tab-pane fade show active clearfix" id="step1" role="tabpanel" aria-labelledby="home-tab">
<h6>User Info</h6>
<form method="post" id="step1form" action="">
{{csrf_field()}}
<div class="form-group font-size-sm">
<label for="name" class="text-gray">Name</label>
<input name="name" type="text" required class="form-control" value="{{ (\Auth::check()) ? Auth::user()->name : old('name')}}">
</div>
<!-- other form fields -->
<input type="submit" id="goToStep2" href="#step2"
class="btn btn-primary btn float-right next-step" value="Go to step 2"/>
</form>
</div>
<div class="tab-pane fade clearfix tabs hide" id="step2" role="tabpanel" aria-labelledby="profile-tab">
<form method="post">
<h6>Payment method</h6>
<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="radio" name="paymentmethod1" value="option1" checked>
<label class="form-check-label d-flex align-items-center" for="exampleRadios1">
<span class="mr-auto">payment method 1</span>
</label>
</div>
<br>
<div class="form-check">
<input class="form-check-input" type="radio" name="credit_card" value="option1">
<label class="form-check-label d-flex align-items-center" for="exampleRadios1">
<span class="mr-auto">Stripe</span>
</label>
</div>
</div>
<div class="text-right">
<button type="button" href="#step3" data-toggle="tab" role="tab"
class="btn btn-outline-primary prev-step">
Go back to step 2
</button>
<button type="button" data-nexttab="#step3" href="#step3"
class="btn btn-primary btn ml-2 next-step">
Go to step 3
</button>
</div>
</form>
</div>
// ajax in payment.blade.php
$('#goToStep2').on('click', function (event) {
event.preventDefault();
var custom_form = $("#" + page_form_id);
$.ajax({
method: "POST",
url: '{{ route('products.storeUserInfo',compact('id','slug') ) }}',
data: custom_form.serialize(),
datatype: 'json',
success: function (data, textStatus, jqXHR) {
setTimeout(function () {
}, 3000);
},
error: function (data) {
console.log(data);
var errors = data.responseJSON;
var errorsHtml = '';
$.each(errors['errors'], function (index, value) {
errorsHtml += '<ul class="list-group"><li class="list-group-item alert alert-danger">' + value + '</li></ul>';
});
$('#response').show().html(errorsHtml);
}
});
});
});
Use Validator facade class in your PaymentController
use Validator;
class PaymentController extends Controller
{
public function storeUserInfo(Request $request, $id, $slug = null){
$validator = Validator::make($request->all(),[
'buyer_name' => 'required|max:255|string',
'buyer_surname' => 'required|max:255|string',
'buyer_email' => 'required|max:255|string',
'name_invoice' => 'required|max:255|string',
'country_invoice' => 'required|max:255|string',
]);
if ($validator->fails()) {
if($request->ajax())
{
return response('test');
}
$this->throwValidationException(
$request, $validator
);
}
}
}

CodeIgniter can't Login in the first time

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]));
}

AJAX response issue in modal

I have an AJAX request to add form fields in a database, but got issues while appending the new entry in my select list.
Here's the HTML
<select id="jform_proprietaire" name="jform[proprietaire]">
<option value="8">Hello World</option>
<option value="35">Jon Jon</option>
<option value="9">Jack Jonhson</option>
</select>
The Form in modal :
<div id="myModal" class="modal hide fade in" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="false" style="display: block;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Ajouter un proprietaire</h3>
</div>
<div class="modal-body">
<form method="post" name="adminForm" id="propritaire-form">
<fieldset class="adminform">
<div class="resultats"></div>
<div class="control-group">
<div class="control-label"><label id="nom-lbl" for="nom" aria-invalid="false">
Nom</label>
</div>
<div class="controls"><input type="text" name="nom" id="nom" value=""></div>
</div>
<div class="control-group">
<div class="control-label"><label id="prenom-lbl" for="prenom" aria-invalid="false">
Prénom</label>
</div>
<div class="controls"><input type="text" name="prenom" id="prenom" value=""></div>
</div>
<div class="control-group">
<div class="control-label"><label id="societe-lbl" for="societe" aria-invalid="false">
Société</label>
</div>
<div class="controls"><input type="text" name="societe" id="societe" value=""></div>
<div class="control-group">
<div class="control-label"><label id="email-lbl" for="email" aria-invalid="false">
Email</label>
</div>
<div class="controls"><input type="email" name="email" class="validate-email" id="email" value=""></div>
</div>
</fieldset>
<input type="hidden" name="6f179ffa2a28133151f3cfe1553978e3" value="1">
</form>
</div>
<div class="modal-footer">
<a id="enregistrerproprio" class="btn btn-primary">Enregistrer</a>
</div>
</div>
And the script :
jQuery(document).ready(function(){
jQuery('#myModal').on('shown', function () {
jQuery('#enregistrerproprio').click(function(){
form=jQuery('#propritaire-form')
jQuery('#propritaire-form .resultats').html('<div class=\"progress progress-striped\"><div class=\"bar\" style=\"width: 30%;\"></div></div>');
jQuery.ajax({
type: 'POST',
url: 'index.php?option=com_visites&task=ajax.ajouteProprietaire&format=raw',
data: form.serializeArray(),
dataType: 'json',
success: function(data) {
jQuery('#propritaire-form .resultats').empty();
if(data.succes==1){
jQuery('#myModal').modal('hide');
jQuery('#jform_proprietaire').append('<option selected=\"true\" value=\"'+data.proprietaire.id+'\">'+data.proprietaire.nom+' '+data.proprietaire.prenom+'</option>');
} else {
jQuery('#propritaire-form .resultats').html('<div class=\"alert alert-error\"></div>');
for (i=0;i<data.retour.length;i++){
jQuery('#propritaire-form .resultats .alert').append('<p>'+data.retour[i].message+'</p>')
}
}
}
});
})
})
})
My data is well imported to the database but I have in console :
Uncaught TypeError: Cannot read property 'id' of null
at Object.success (index.php?option=com_jea&view=property&layout=edit&id=344:60)
at i (jquery.min.js?7c0336fabba01bb5fea27139dbdfd8c1:2)
at Object.fireWith [as resolveWith] (jquery.min.js?7c0336fabba01bb5fea27139dbdfd8c1:2)
at y (jquery.min.js?7c0336fabba01bb5fea27139dbdfd8c1:4)
at XMLHttpRequest.c (jquery.min.js?7c0336fabba01bb5fea27139dbdfd8c1:4)
For this line :
jQuery('#jform_proprietaire').append('<option selected=\"true\" value=\"'+data.proprietaire.id+'\">'+data.proprietaire.nom+' '+data.proprietaire.prenom+'</option>');
If someone could help would be great!!
Thanks in advance !
PS : I ommited to show the php ajouteproprietairefunction :
class VisitesControllerAjax extends JControllerAdmin
{
public function ajouteProprietaire(){
require_once JPATH_ADMINISTRATOR.'/components/com_visites/models/propritaire.php';
$input = JFactory::getApplication()->input;
$data=$input->getArray(array('nom' => '', 'prenom' => '', 'societe' => '','email' => '', 'telephone' => '', 'mobile' => '','adresse' => '', 'codepostal' => '', 'ville' => '', 'notes' => ''));
$data["state"]=1;
$model=new VisitesModelPropritaire();
$reussite=$model->save($data);
if ($reussite) {
$db= JFactory::getDbo();
$query=$db->getQuery(true);
$query->select('*')
->from('#__visites_proprio')
->where('id='.$db->insertid());
$db->setQuery($query);
$proprietaire=$db->loadObject();
echo json_encode(array('succes'=>1, 'proprietaire'=>$proprietaire));
} else {
echo json_encode(array('succes'=>0, 'retour'=>JFactory::getApplication()->getMessageQueue()));
}
}
}
Ok found the solution....
In the latest version of MySql the Last Insert ID isn't working very well.
So I changed my function to check on the email field since It's Unique for each user, Here's the updated code :
if ($reussite) {
$db= JFactory::getDbo();
$query=$db->getQuery(true);
$query->select('*');
$query->from('#__visites_proprio');
$query->where('email = \''.$data['email'].'\'');
$db->setQuery($query);
$proprietaire=$db->loadObject();
echo json_encode(array('succes'=>1, 'proprietaire'=>$proprietaire));
} else {
echo json_encode(array('succes'=>0, 'retour'=>JFactory::getApplication()->getMessageQueue()));
}

Resources