hi im new to coding and ive been watching this youtube tutorial about a simple server side processing crud and datatable in laravel and im getting this error which i have no idea why im getting it.
I am trying to create an update function to my code but cant cuz of this error. I have a feeling this is because of my update url but im using the same syntax in the tutorial so can you god tier people help me.
Missing required parameters for [Route: Clients.update] [URI:
Clients/{Client}]. (View:
C:\xampp\htdocs\project\resources\views\clients\clients.blade.php)
this is my view code
<div id="formmodal" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Client Form</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>{{-- header --}}
<div class="modal-body">
<span class="result" id="result"></span>
<form method="post" id="client_form" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label for="client_name">Name</label>
<input type="text" class="form-control" name="client_name" id="client_name" placeholder="Enter Name">
</div>
<div class="form-group">
<label for="client_address">Addres</label>
<input type="text" class="form-control" name="client_address" id="client_address" placeholder="Enter Addres">
</div>
<div class="form-group">
<label for="client_date">Birth Date</label>
<input type="date" class="form-control" name="client_bdate" id="client_bdate">
</div>
<div class="modal-footer">
<input type="text" name="action" id="action">
<input type="text" name="hidden_id" id="hidden_id">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary" name="savebtn" id="savebtn" value="Add">
</div>
</form>
</div>
</div>
</div>
</div>
$('#client_form').on('submit', function(event){
event.preventDefault();
var url;
if($('#action').val() == 'Add')
{
url = "{{ route('Clients.store') }}";
}else{
url = "{{ route('Clients.update') }}";
}
$.ajax({
url: url,
method: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
dataType: "json",
success:function(data)
{
var html = '';
if(data.errors)
{
html = '<diV class="alert alert-danger">';
for(var count = 0; count < data.errors.length; count++)
{
html += '<p>' + data.errors[count] + '</p>';
}
html += '</div>';
}
if(data.success)
{
alert("add");
html = '<diV class="alert alert-success">' + data.success + '</div>';
$('#client_form')[0].reset();
$('#table_id').DataTable().ajax.reload();
}
$('#result').html(html);
}
})
});
my controller code
public function update(Request $request)
{
$rules = array(
'client_name' => 'required',
'client_address' => 'required',
'client_bdate' => 'required'
);
$error = Validator::make($request->all(), $rules);
if($error->fails())
{
return response()->json(['errors'=>$error->errors()->all()]);
}
$form_data = array(
'client_name' => $request->client_name,
'client_address' => $request->client_address,
'client_bdate' => $request->client_bdate
);
Clients::find($request->hidden_id)->update($form_data);
return response()->json(['success' => 'Data Updated']);
}
Edit...
My route
Route::resource('/Clients', 'clientsCont');
In your controller you are missing second parameter.
So try like this:
public function update(Request $request, Client $client)
{
$rules = array(
'client_name' => 'required',
'client_address' => 'required',
'client_bdate' => 'required'
);
$error = Validator::make($request->all(), $rules);
if($error->fails())
{
return response()->json(['errors'=>$error->errors()->all()]);
}
$form_data = array(
'client_name' => $request->client_name,
'client_address' => $request->client_address,
'client_bdate' => $request->client_bdate
);
// You should get your client in variable $client
//Clients::find($request->hidden_id)->update($form_data);
$client->update($form_data);
return response()->json(['success' => 'Data Updated']);
}
Also note if you want to your code look simplier you can validate your request like this:
public function update(Request $request, Client $client)
{
$request->validate([
'client_name' => 'required',
'client_address' => 'required',
'client_bdate' => 'required'
])
$client->update($form_data);
return response()->json(['success' => 'Data Updated']);
}
You can read more here.
Good luck!
In your routes file remove the {} from Clients/{Client} or preferably change it to: Clients/update, when you put {} around some text, you are binding some parameter (actually Eloquent Model), and you should provide it (provide the ID) when you call the route.
Read more Laravel Documentations
Firstly, let's put certain conventions in place.
Change your route definition to
Route::resource('clients', 'ClientsCont');
By convention, controller names should be camel case and start with a capital letter. The route names are usually lower case.
Next, ensure that your controller file is correctly named ClientsCont.php and also the class name should be ClientsCont. Finally, you have to provide a second parameter to your update() method to hold the client object to update.
ClientsCont.php
namespace App\Http\Controllers;
use App\Client;
class ClientsCont extends Controller
{
// class definition
public function update(Request $request, Client $client)
{
$rules = array(
'client_name' => 'required',
'client_address' => 'required',
'client_bdate' => 'required'
);
$error = Validator::make($request->all(), $rules);
if($error->fails())
{
return response()->json(['errors'=>$error->errors()->all()]);
}
$form_data = array(
'client_name' => $request->client_name,
'client_address' => $request->client_address,
'client_bdate' => $request->client_bdate
);
$client->update($form_data);
return response()->json(['success' => 'Data Updated']);
}
}
Now, setup your Ajax request properly.
$('#client_form').on('submit', function(event){
var url;
if($('#action').val() == 'Add')
{
url = "{{ route('clients.store') }}";
}else{
url = "{{ route('clients.update') }}";
}
$.ajax({
url: url,
method: "POST",
data: new FormData(this),
cache: false,
dataType: "json",
success:function(data)
{
var html = '';
if(data.errors)
{
html = '<diV class="alert alert-danger">';
for(var count = 0; count < data.errors.length; count++)
{
html += '<p>' + data.errors[count] + '</p>';
}
html += '</div>';
}
if(data.success)
{
alert("add");
html = '<diV class="alert alert-success">' + data.success + '</div>';
$('#client_form')[0].reset();
$('#table_id').DataTable().ajax.reload();
}
$('#result').html(html);
}
})
return false;
});
Usually using return false; is the preferred way for stopping default event action and propagation.
[return false;] Usually seen in jQuery code, it Prevents the browsers default behaviour, Prevents the event from bubbling up the DOM, and immediately Returns from any callback.
See this medium write-up for full details.
Also, from your code, certain of your ajax settings are unnecessary and should be omitted so that their default values are used. These default values are usually sufficient for most forms.
For instance, using jQuery Ajax setting of processData: false disables processing the form data and uses the toString() method of the object to form the request data string.
When you set data to a general object other than a string with processData set to false jQuery doesn't process the object. The object is passed to the Ajax call exactly as it is and used as if it was a String. This by default calls the toString method and sends the result to the sever as the data in the Ajax request.
See this for full description. Be sure you need this setting or you discard it all together.
Another Ajax setting you probably need to discard is contentType: false, except you have a good reason for setting it.
Related
Scenario:
I am developing CMS system and I wan to add some categories to the objects (pages, posts, media etc.). In my view, to save a new category I use HTML form placed in Bootstrap modal which is sent via AJAX to my controller. The CSRF protection is enabled on the entire site.
While sending the data for the first time, I pass the CSRF token name and hash via form. Once being processed by PHP code in controller, I want to pass CSRF values in the response so I will be able to "re-use" the form in the modal (e.g. display error messages or/and create another category).
Yet, I am not able to access the get_csrf_token_name() and get_csrf_hash() methods to pass values back to the view.
In my view admmin/category/create.php:
...
<!-- CREATE CATEGORY MODAL MODAL -->
<div class="modal" id="createCategory" tabindex="-1">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Nová kategorie</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Zavřít"></button>
</div>
<div class="modal-body">
<form action="" method="post" id="createCategoryForm">
<input type="hidden" value="<?= csrf_hash(); ?>" name="<?= csrf_token(); ?>" id="csrf">
<div class="form-group mb-3">
<label for="title" class="form-label">Název kategorie</label>
<input type="text" class="form-control" name="title" id="title" value="">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" id="createCategoryConfirm">Vytvořit novou kategorii</button>
</form>
</div>
</div>
</div>
</div>
...
<script>
$('#head').on('click', '.create', function() {
$('#createCategory').modal('show');
$('#createCategoryForm').attr('action', '<?= base_url(); ?>/admin/category/create');
$('#createCategoryConfirm').click(function(e) {
e.preventDefault();
var url = $('#createCategoryForm').attr('action');
var csrfElement = $('#csrf');
var csrfName = csrfElement.attr('name');
var csrfHash = csrfElement.attr('value');
var categoryTitle = $('input[name=title]').val();
var data = {
[csrfName]: csrfHash,
'title': categoryTitle
};
console.log(data);
$.ajax({
type: 'ajax',
method: 'POST',
url: url,
data: data,
dataType: 'json',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
headers: {'X-Requested-With': 'XMLHttpRequest'},
success: function(result) {
console.log(result);
},
error: function(result) {
console.log(result);
},
});
});
});
</script>
In my controller Category.php:
<?php
namespace App\Controllers\Admin;
use App\Controllers\BaseController;
use App\Models\CategoryModel;
use CodeIgniter\I18n\Time;
class Category extends BaseController {
protected $model;
protected $validator;
protected $security;
public function __construct() {
$this->model = new CategoryModel();
$this->validation = \Config\Services::validation();
$this->security = \Config\Services::security();
helper(['form', 'date', 'url']);
}
...
public function create() {
$response = [];
// This part of code returns error
//
// $response['csrf'] = array(
// 'name' => $this->security->get_csrf_token_name(),
// 'hash' => $this->security->get_csrf_hash()
// );
$response['security'] = $this->security;
if ($this->request->isAJAX()) {
$newCategory = [
'title' => $this->request->getVar('title'),
'slug' => url_title($this->request->getVar('title')),
'author' => session()->get('id'),
'created_at' => Time::now('Europe/Prague')->toDateTimeString(),
'updated_at' => Time::now('Europe/Prague')->toDateTimeString(),
'parent' => '0'
];
$this->validation->run($newCategory, 'categoryRules');
if (!empty($this->validation->getErrors())) {
$this->model->save($newCategory);
$response['errors'] = $this->validation->getErrors();
echo json_encode($response);
} else {
$this->model->save($newCategory);
$response['success'] = 'New category was created';
echo json_encode($response);
}
}
}
...
In the browser console, the AJAX response is POST http://localhost/admin/category/create 500 (Internal Server Error) with full response:
code: 500
file: "D:\Web\XAMPP\htdocs\lenka\app\Controllers\Admin\Category.php"
line: 38
message: "Call to undefined method CodeIgniter\Security\Security::get_csrf_token_name()"
title: "Error"
Could anyone please see the issue here? Is there any good solution on how to reuse CSRF tokens in CI4? I tried set config values of CSRF regenerate both to true and false, with no effect.
update this line cod in .ENV
or
app/config/security
CSRF Regenerate = false
In his life, he only encountered an ajax 2 times and here again our paths intertwined with him and he gave me 422 errors. I googled and realized that 422 error is a validation error, but in what specific place the error, I just can not understand.
This is my script
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$( "#form" ).submit(function( e ) {
e.preventDefault();
var message = $('#message').val();
var img = $('#img').val();
var user_id = $('#user_id').val();
$.ajax({
type: "POST",
url: "{{route('profile.store', ['id' => Auth::user()->id])}}",
data: {message:message, img:img, user_id:user_id},
success: function (data) {
$("#textpost").html($(data).find("#textpost").html());
},
});
});
</script>
And my method
public function store(Request $request) {
$validator = $this->validate($request,[
'message' => 'required|max:1000',
'img' => 'mimes:jpeg,png,gif|max:3000',
]);
if($validator ) {
$post = new Profile();
$post->message = $request->message;
$post->user_id = Auth::user()->id;
if($request->file('img')) {
$path = Storage::putFile('public', $request->file('img'));
$url = Storage::url($path);
$post->img = $url;
}
$post->save();
}
return redirect()->back();
}
And my form
<div class="card-header">
<div class="input-group">
<form action="{{route('profile.store', ['id' => Auth::user()->id])}}" method="post" enctype="multipart/form-data" id="form">
#csrf
<textarea class="form-control" id="message" name="message" cols="100" rows="4" placeholder="О чем думаешь?"></textarea>
<input type="file" id="img" name="img" value="Прикрепить изображение" class="mt-2">
<div class="text-right">
{{-- <input type="submit" id="btn" value="Отправить" class="btn btn-outline-dark btn-sm mt-4">--}}
<button type="submit" id="btn" class="btn btn-outline-dark btn-sm mt-4">Отправить</button>
</div>
</form>
</div>
</div>
$validator = $this->validate($request,[
'message' => 'required|max:1000',
'img' => 'mimes:jpeg,png,gif|max:3000',
]);
This portion of your code throws a validation errors exception which returns 422.
If you wish to handle validation on your own, try this logic instead:
$validator = validator($request->all(), [
'message' => 'required|max:1000',
'img' => 'mimes:jpeg,png,gif|max:3000',
]);
if($validator->fails()) {
// return as appropriate
return response()->son($validatior->errors(), 422);
}
// rest of your code
There is a problem with your Ajax call, because you are uploading text and file at the same time you can pass it through FormData. You were also missing
contentType: false,
processData: false,
Here is the updated ajax call:
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$( "#form" ).submit(function( e ) {
e.preventDefault();
var formData = new FormData(this); //set formData to selected instance
var message = $('#message').val();
var img = $('#img').val();
var user_id = $('#user_id').val();
$.ajax({
type: "POST",
url: "{{route('profile.store', ['id' => Auth::user()->id])}}",
data: formData, //pass to our Ajax data to send
success: function (data) {
$("#textpost").html($(data).find("#textpost").html());
},
contentType: false,
processData: false,
});
});
</script>
Setting processData makes it so your FormData is not converted to a string. Setting contentType to false is used for forms that pass files, when false, no header will be added to the request, which is exactly what we want when submitting multipart/form-data.
Hi I am trying to create a post using form data, because I have a file input to upload images. I am really struggling with getting the upload file to work. I get an error 500 when I try to create a post, with the message
SQLSTATE[HY000]: General error: 1364 Field 'title' doesn't have a default value (SQL: insert into posts ('updated_at', 'created_at') values (2018-01-30 12:31:18, 2018-01-30 12:31:18).
I am not sure what is meant by default value. I checked my $fillables and title is definitely there. When I run the following code in my controller right at the top it passes:
$request->all();
return response()->json('passed');
But when I have the following in my controller it gives the error:
public function create(Request $request)
{
Post::create($request->all());
$response = [
'response' => 'Post Created Successfully',
'error' => 'Something went wrong'
];
return response()->json($response);
}
Here is my HTML:
<div class="container">
<div class="row">
<h1>Create your post</h1>
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" id="title" class="form-control">
</div>
<div class="form-group">
<label for="post">Post</label>
<textarea name="post" rows="8" cols="80" id="post" class="form-control"></textarea>
</div>
<div class="form-group">
<label for="image">Add image</label>
<input type="file" name="image" id="image" class="form-control">
</div>
<input type="submit" name="submit" value="Submit Post" id="submit" class="btn btn-primary">
</div>
</div>
AJAX:
<script>
$(document).ready(function() {
$("#submit").on("click", function(e) {
e.preventDefault();
var formData = new FormData();
var fileData = $('#image').prop('files')[0];
var title = $('#title').val();
var post = $('#post').val();
formData.append('fileData', fileData);
formData.append('title', title);
formData.append('post', post);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr("content")
}
});
$.ajax({
url:'/post/create/create',
type: "POST",
data: {
formData: formData
},
processData: false,
contentType: false,
dataType: 'json',
success:function(response){
toastr.success(response.response);
},
error: function(error){
toastr.error(error.error)
}
});
});
});
</script>
Here is my Post model with the fillables:
protected $fillable = ['title', 'post', 'user_id', 'uploadImage'];
In-order to obtain the data from your ajax in your controller, pass the data as
data: formData
instead of
data: {
formData: formData
}
and you could process the information in your controller as
public function create(Request $request)
{
$path = '';
if ($request->hasFile('fileData')) {
if ($request->file('fileData')->isValid()) {
// Upload the file
$path = $request->fileData->store('your directory');
}
}
$post = Post::create([
'title' => $request->title,
'post' => $request->post,
'user_id' => auth()->user()->id,
'uploadImage' => $path
]);
if ($post) {
return response()->json([
'response' => 'Post Created Successfully!'
]);
}
return response()->json([
'error' => 'Something went wrong!'
], 500)
}
Documentation on storing uploaded files
I'd like some help please.
I'm having a form placed inside a bootstrap modal window.
<div class="modal-content">
<div class="modal-body">
<div id="ajaxResults"></div>
<?php echo form_open('controller-name/form-process'), array('id' => 'modal-form'); ?>
<input type="hidden" name="title" id="hid-title" />
<div class="form-group">
<?php echo form_input('first_name', set_value('first_name', $this->input->post('first_name')), 'id="first-name" class="form-control" placeholder="First name"'); ?>
</div>
<div class="form-group">
<?php echo form_input('last_name', set_value('last_name', $this->input->post('last_name')), 'id="last-name" class="form-control" placeholder="Last name"'); ?>
</div>
<div class="form-group">
<?php echo form_input('email', set_value('email', $this->input->post('email')), 'id="email" class="form-control" placeholder="Email"'); ?>
</div>
<div class="form-group">
<?php echo form_input('company', set_value('company', $this->input->post('company')), 'id="company" class="form-control" placeholder="Company"'); ?>
</div>
<?php echo form_close(); ?>
</div><!-- /.modal-body -->
<div class="modal-footer">
<button type="button" class="btn btn border-black" data-dismiss="modal">Close</button>
<button type="button" class="btn btn border-theme" id="form-submit-btn">Submit form</button>
</div><!-- /.modal-footer -->
</div><!-- /.modal-content -->
When I click the Submit the Form button I'm sending an ajax request to my form_process controller where I do the form validation. Here's my code for the form_process function and the ajax script
public function form_process() {
if ($this->input->post()) {
$rules = array(
'first_name' => array(
'field' => 'first_name',
'label' => 'First name',
'rules' => 'required|trim|min_length[2]',
),
'last_name' => array(
'field' => 'last_name',
'label' => 'Last name',
'rules' => 'required|trim|min_length[2]',
),
'email' => array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required|trim|valid_email',
),
'company' => array(
'field' => 'company',
'label' => 'Company',
'rules' => 'required|trim',
),
);
$this->load->library('form_validation');
$this->form_validation->set_rules($rules);
// validate the form
if ($this->form_validation->run()) {
$response = array(
'status' => '200',
'message' => 'Thank you! We have sent an email to ' . $this->input->post('email') . ' to get your white paper.',
);
} else {
$response = array(
'status' => '400',
'message' => validation_errors(),
);
}
// return the result of the form process
$this->output->set_status_header($response['status'])->set_content_type('application/json', 'utf-8')
->set_output(json_encode($response, JSON_PRETTY_PRINT))->_display();
exit();
}
The ajax script looks like this
$('#myModal').on('show.bs.modal', function (event) {
$('#modal-form').show();
$('#ajaxResults').removeClass('alert alert-success alert-error');
// Button that triggered the modal
var button = $(event.relatedTarget);
// Extract info from data-* attributes
var recipient = button.data('whatever');
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this);
modal.find('.modal-title').html('New message to <br/>' + recipient);
modal.find('.modal-body input[type=hidden]').val(recipient);
// submit the form
$('#form-submit-btn').on('click', function (event){
event.preventDefault();
var url = $('#modal-form').attr('action');
// send ajax request
$.ajax({
url: url,
type : 'POST',
data : {
'first_name' : $('#first-name').val(),
'last_name' : $('#last-name').val(),
'email' : $('#email').val(),
'company' : $('#company').val(),
'title' : $('#hid-title').val(),
},
dataType: 'json',
success : function(response) {
alert(response.message);
// console.log(response.message);
$('#ajaxResults').removeClass('alert alert-success alert-error');
if (response.status == 200) {
$('#modal-form').hide();
$('#ajaxResults').addClass('alert alert-success').html(response.message);
alert('AAAAAAAAAAAAAAAAAAAAAAAAAAAA');
}
if (response.status == 400) {
$('#modal-form').show();
$('#ajaxResults').addClass('alert alert-error').html(response.reason);
alert('BBBBBBBBBBBBBBBBBBBBBBBBBBBB');
}
},
error: function(response){
// code ...
$('#ajaxResults').removeClass('alert alert-success alert-error');
if (response.status == 200) {
$('#modal-form').hide();
$('#ajaxResults').addClass('alert alert-success').html(response.message);
alert('CCCCCCCCCCCCCCCCCCCCCCCCCCC');
}
if (response.status == 400) {
$('#modal-form').show();
$('#ajaxResults').addClass('alert alert-error').html(response.reason);
alert('DDDDDDDDDDDDDDDDDDDDDDDDDDDD');
}
}
});
});
});
EDIT I did an update on my ajax script and placed some alert messages, as you can see. When I click the submit button without submitting the form ( so there are errors), the alert DDDDDDD pops up.
When I fill all fields and submit the form the alert CCCCCCC pops up (!!!). In addition the ajaxResults div gets the .alert and .allert-success classes, but still can't see any message.
Any ideas what I'm doing wrong ?
Additional question: Is the error: function(response) used to show the the case where validation fails ?
I have also tried to move the validation errors inside this function and keep on success : function(response) only the success submition of the form, but still no luck.
I can see you are not parsing the data properly
example : in alert('DDDDDDDDDDDDDDDDDDDDDDDDDDDD'); line
before appending data to your ajaxResults you need to convert data Properly
response.responseText => will give you json string .
JSON.parse => will convert string to JSON Obj so that you can
use it like .variableName
Please add the following code before your
$('#ajaxResults').addClass('alert alert-error').html(response.reason);
add following line
var mess = JSON.parse(response.responseText).message;
replace response.reason to mess it should show you error Messages
Please mark it as answer if it works
full Code :
if (response.status == 400) {
$('#modal-form').show();
var mess = JSON.parse(response.responseText).message;
$('#ajaxResults').addClass('alert alert-error').html(mess);
alert('DDDDDDDDDDDDDDDDDDDDDDDDDDDD');
}
working
If it takes you to the error part, then you must use something like this to catch it:
,
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError) ; // or alert(xhr.responseText);
$('#ajaxResults').addClass('alert alert-error').html(thrownError) ;
}
And if the ajax call is successful, something like this:
,
succes: function(data, status, jqXHR){
if (status == 200) {
$('#modal-form').hide();
$('#ajaxResults').addClass('alert alert-success').html(response.message);
alert(data);
}
}
The "problem" was this output->set_status_header($response['status']) the request was always successful, but setting a header to 400 messed up the functionality.
I removed this piece of code and now works fine! However I still needed to add the
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError) ; // or alert(xhr.responseText);
$('#ajaxResults').addClass('alert alert-error').html(thrownError) ;
}
to get any errors in cases that the request fail.
Am fairly new to using Jquery and am creating a login for a simple site am creating using CodeIgniter and bootstrap. After submitting the Log in button, it won't show any error or success message, meaning that I don't even know if it actually post the data to the controller
here's my code,
Jquery Code
<script>
//Wait until the DOM is fully loaded
$(document).ready(function(){
//Listen for the form submit
$('#loginform').submit(logIn);
});
//The function that handles the process
function logIn(event)
{
//Stop the form from submitting
event.preventDefault();
//Hide our form
// $('#loginform').slideUp();
//Collect our form data.
var form_data = {
email : $("[name='email']").val(),
password : $("[name='password']").val(),
};
//Begin the ajax call
$.ajax({
url: "admin",
type: "POST",
data: form_data,
dataType: "json",
cache: false,
success: function (json) {
if (json.error==1)
{
//Show the user the errors.
$('#message').html(json.message);
} else {
//Hide our form
$('#loginform').slideUp();
//Show the success message
$('#message').html(json.message).show();
}
}
});
}
</script>
login.php
<?php
echo $this->session->flashdata('alert');
?>
<div id="message"></div>
<?php
$attr = array('class' => 'admin-login form-horizontal well form-signin', 'id' => 'loginform');
echo validation_errors('<div class="alert alert-error">', '</div>');
?>
<?php echo form_open(site_url('admin'), $attr) ?>
<!--<form action="<?php echo site_url('track-order'); ?>" method="post" class="form-horizontal form-search" id="trackModalform">-->
<div class="control-group">
<label class="control-label">Track Your Order</label>
</div>
<div class="control-group">
<label class="control-label" >Email:</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-qrcode"></i></span>
<input type="text" name="email" class="input-block-level email" placeholder="Email address">
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" >Password:</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-key"></i></span>
<input type="password" name="password" class="input-block-level password" placeholder="Password">
</div>
</div>
</div>
<div class="form-actions" style="margin-bottom: 0px; padding-bottom: 0px;">
<input type="submit" class="btn btn-primary " name="signin" value="Sign In!" id="login">
</div>
</form>
my controller
public function index()
{
if (!file_exists('application/views/admin/index.php'))
{
//sorry that page is not available
show_404();
}
$this->form_validation->set_rules('email', 'Name', 'required|min_length[5]|max_length[50]|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[5]');
if($this->form_validation->run() === TRUE)
{
echo json_encode(array('error' => '1', 'message' => validation_errors('<div class="alert alert-error"><strong>Error!</strong> ', '</div>')));
} else {
//Save the data to the database, of course you will need all the data first.
if($this->admin_model->validate_admin_login()):
//Send the success to our javascript file.
echo json_encode(array('error' => '0', 'message' => '<div class="alert alert-success"><strong>Success!</strong> You have been registered!</div>'));
endif;
}
$data['title'] = ucfirst('Admin - Home');
$data['currentpage'] = 'home';
$this->load->view('admin/index', $data);
}
model
public function validate_admin_login()
{
$this->str = do_hash($this->input->post('password')); // SHA1
$this->db->where('email', $this->input->post('email'));
$this->db->where('password', $this->str);
$query = $this->db->get('ip_admin');
if($query->num_rows == 1)
{
$data['admin_sess'] = $this->admin_model->admin_details($this->input->post('email'));
$data = array(
'email' => $this->input->post('email'),
'is_admin_logged_in' => true
);
$this->session->set_userdata($data);
return true;
}
}
public function admin_details($user)
{
$query = $this->db->select('*')->from('ip_admin')->where('email', $user);
$query = $query->get();
return $data['admin_sess'] = $query->row();
}
I don't really responding or outputting any message to indicate success or failure, maybe I got everything wrong to start with.
I need it to query the db, returns the message for me on the view page using the json parameter on my controller.
Thanks all.
I suggest you add a data in var_data like this:
var form_data = {
email : $("[name='email']").val(),
password : $("[name='password']").val(),
//add a data which is
ajax: '1'
};
And in your controller check if it is POST'ed:
if($this->input->post('ajax'){
//do something
}else{
//do something
}
so from there you could check if it is working or not. and also install firebug for debugging purposes in Firefox. In Chrome try to inspect element and see console
I honestly haven't gone through all your code as it really isn't that complicated, instead I'd like to suggest you install Firebug to debug your jquery if you haven't already installed it. Its essential when developing with javascript. It will print any errors or success as events are called and handled.
How to use: Firebug FAQ
EDIT:
As you asked for code:
if($this->form_validation->run() === TRUE)
{
echo json_encode(array('error' => '1', 'message' => validation_errors('<div class="alert alert-error"><strong>Error!</strong> ', '</div>')));
} else {
//Save the data to the database, of course you will need all the data first.
if($this->admin_model->validate_admin_login()):
//Send the success to our javascript file.
echo json_encode(array('error' => '0', 'message' => '<div class="alert alert-success"><strong>Success!</strong> You have been registered!</div>'));
endif;
}
$data['title'] = ucfirst('Admin - Home');
$data['currentpage'] = 'home';
$this->load->view('admin/index', $data);
Wtihin this block, you're echo'ing json once and then spitting out the HTML view afterwards. Just try removing the:
$data['title'] = ucfirst('Admin - Home');
$data['currentpage'] = 'home';
$this->load->view('admin/index', $data);
Or create separate controller functions for your requests, things get really messy when you try to stuff everything into a single function.