My ajax call:
$('#password_change_form').submit(function(e) {
e.preventDefault();
var saveThis = this;
$.ajax({
type: "POST",
url: "{{ url('/changepassword') }}",
data: $(saveThis).serialize(),
success: function(data) {
$("#password_change_form").trigger("reset");
alert(data);
}
});
}),
My Controller method:
public function changepassword(Request $request){
$user = Auth::guard()->user();
$request_data = $request->All();
$validator = $this->admin_credential_rules($request_data);
if($validator->fails()) {
$errors = $validator->errors();
$errors = json_decode($errors);
return response()->json([
'success' => false,
'message' => $errors
], 422);
} else {
$current_password = $user->password;
if(md5($request_data['password']) == $current_password) {
$user_id = $user->id;
$obj_user = User::find($user_id);
$obj_user->password = md5($request_data['new_password']);
$obj_user->save();
$msg = "password has been changed";
return response()->json(array('change_password'=> $msg), 200);
} else {
$error = array('error' => array('Heslo, které jste zadali, je neplatné.'));
return response()->json([
'modal_message_danger' , "Heslo, které jste zadali, je neplatné.",
'message' => $error
], 422);
}
}
}
When I hit the submit button on the popup form it shows me the HTML alert. I have also attached the screen shot of this alert:
Here my data is not saving. I am kind of confused about this problem. Please help me regarding this problem.
Your help will be highly appreciated!
Here is a screenshot of my alert:
The question is if your javascript in within your blade.php file if it's not in your blade.php you can't use the blade syntax:
url: "{{ url('/changepassword') }}",
the bracers or only valid within the blade template area not in your js just replace it with this
url: "/changepassword",
Further add check if you get any data from your javascript like this in your controller method
dd($request->all());
If it does output your the data you are trying to sent your ajax works if not it does not.
Related
I do not know what I am missing, but I cant make this work. It's throwing an error, POST 500 (Internal Server Error) "Too few arguments to function" in Laravel.
$(document).on('click', '.btnUpdateStudent', function (e) {
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$td=$(this).closest('td');
$tr=$(this).closest('tr');
var id=$td.attr("data-studId");
var inputEditName="<input type='text' class='inputEditName form-control'>";
$tr.find('td:eq(1)').val(inputEditName);
$tr.find('td:eq(1)').find("input.inputEditName").val();
var inputEditEmail="<input type='text' class='inputEditEmail form-control'>";
$tr.find('td:eq(2)').val(inputEditEmail);
$tr.find('td:eq(2)').find("input.inputEditEmail").val();
var options = $('#selectDepartment option');
var optionValues = $.map(options ,function(option){
return "<option value='"+option.value+"'>"+option.text+"</option>";});
var selectDepartment ="<select class='selectDepartment form-select form-control'></select>";
var updateDept=$('.selectDepartment').val();
$tr.find('td:eq(3)').val(selectDepartment);
$tr.find('td:eq(3)').find("select.selectDepartment").html(optionValues);
$tr.find('td:eq(3)').find("selectDepartment").val();
$tr.find('td:eq(3)').find("select.selectDepartment").val(updateDept);
var editname=$tr.find('td:eq(1)').find("input.inputEditName").val();
var editemail=$tr.find('td:eq(2)').find("input.inputEditEmail").val();
var editdepartment=$tr.find('td:eq(3)').find("select.selectDepartment").val();
var data = {
'id' : id,
'name' : editname,
'email': editemail,
'department_id': editdepartment
}
console.log(data);
$.ajax({
type: "POST",
url: "/update-student",
data: data,
dataType: "json",
success: function (response) {
console.log(response);
if (response.status == 400) {
$('#saveform_errList').html("");
$('#saveform_errList').addClass('alert alert-danger');
$.each(response.errors, function (key, err_values){
$('#saveform_errList').append('<li>'+err_values+'</li>');
});
}else {
$('#saveform_errList').html("");
$('#success_message').addClass('alert alert-success')
$('#success_message').text(response.message)
$("#inputForm").find('input').val("");
}
}
});
});
this is my controller. did i missed something? or is there part that should be there?
public function update(Request $request)
{
$validator = Validator::make($request->all(), [
'name'=> 'required|max:100',
'email'=>'required|email|max:100',
'department_id'=>'required'
]);
if($validator->fails())
{
return response()->json([
'status'=>400,
'errors'=>$validator->messages()
]);
}
else
{
$student = Student::find();
if($student)
{
$student->id = $request->input('id');
$student->name = $request->input('name');
$student->email = $request->input('email');
$student->department_id = $request->input('department_id');
$student->update();
return response()->json([
'status'=>200,
'message'=>'Student Updated Successfully.'
]);
}
else
{
return response()->json([
'status'=>404,
'message'=> 'No Student Found.'
]);
}
}
}
I tried reviewing my code but I really can't distinguish the problem. I need help
$student = Student::find() is where your issue is. The find() method requires one parameter which is the primary key id gotten from your database.
Now, since you already passed the id via your ajax just change your code to this:
public function update(Request $request)
{
$validator = Validator::make($request->all(), [
'name'=> 'required|max:100',
'email'=>'required|email|max:100',
'department_id'=>'required'
]);
if($validator->fails())
{
return response()->json([
'status'=>400,
'errors'=>$validator->messages()
]);
}
else
{
$student = Student::find($request->id); // here I have added the required parameter
if($student)
{
$student->id = $request->input('id');
$student->name = $request->input('name');
$student->email = $request->input('email');
$student->department_id = $request->input('department_id');
$student->update();
return response()->json([
'status'=>200,
'message'=>'Student Updated Successfully.'
]);
}
else
{
return response()->json([
'status'=>404,
'message'=> 'No Student Found.'
]);
}
}
}
UPDATE:
To refresh the page automatically after the Ajax request is successful, do this:
Add this directly above where you have if (response.status == 400) {:
if (response.status == 200) {
location.reload();
}
This will reload the page automatically.
I'm working on a project in CodeIgniter4. I'm trying to make an Ajax call to an endpoint (/adjustments/store). I'm validating the form using CodeIgniter and showing the validation errors in my view. The issue is when the first time, i submit the form, it works and shows some validation errors. But when i fill the form correclty (to get not validation errors) and resubmit it again it gives me 403 forbidden error in the console.
Ajax call
$.ajax({
type: 'post',
url: '/adjustments/store',
dataType: 'html',
data: {
number,
date,
type,
account,
description,
adjData,
csrf_test_name
},
success: function (res) {
if (IsJsonString(res)) {
const response = JSON.parse(res);
if (response.hasOwnProperty('validation_errors')) {
const errors = response.validation_errors;
for (err in errors) {
$(`input[name=${ err }]`)
.parent()
.append(`<small class="text-danger">${ errors[err] }</small>`)
}
}
}
function IsJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
console.log(res);
}
CodeIgniter Controller
public function store () {
$data = $this->request->getPost(NULL);
// Validate
if (! $this->validate([
'number' => 'required',
'date' => 'required',
'type' => 'required',
'adjData' => 'required',
]))
{
echo json_encode(['validation_errors' => $this->validator->getErrors()]);
return;
}
echo json_encode($data);
}
Any solution to this?
If you are resubmitting a form then you have update csrf token on every request with ajax.
Whenever validation fails pass csrf token and update it every time.
In your controller -
public function store () {
$data = $this->request->getPost(NULL);
// Validate
if (! $this->validate([
'number' => 'required',
'date' => 'required',
'type' => 'required',
'adjData' => 'required',
]))
{
echo json_encode(['validation_errors' => $this->validator->getErrors(), 'csrf' => csrf_hash()]);
return;
}
echo json_encode($data);
}
In you ajax -
$.ajax({
type: 'post',
url: '/adjustments/store',
dataType: 'html',
data: {
number,
date,
type,
account,
description,
adjData,
csrf_test_name
},
success: function (res) {
if (IsJsonString(res)) {
const response = JSON.parse(res);
$("input[name='csrf_test_name']").val(response ["csrf"]);
if (response.hasOwnProperty('validation_errors')) {
const errors = response.validation_errors;
for (err in errors) {
$(`input[name=${ err }]`)
.parent()
.append(`<small class="text-danger">${ errors[err] }</small>`)
}
}
}
function IsJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
So once you update csrf then it will work fine.
Thanks.
I want to check data in database through ajax in codeigniter how can get check name already exist through ajax
controller
public function insert(){
$user = array('Name' => $this->input->post('name'),
'Cnic' => $this->input->post('cnic'),
'Phone' => $this->input->post('phone'),
'Address' => $this->input->post('address'),
);
$this->load->model('suppliermodel');
if($this->suppliermodel->checkData($user['Name'])){
if ($this->session->userdata('user_id'))
$detail = 'Already exist';
$this->load->view('admin/includes/header');
$this->load->view('admin/includes/sidemenu');
$this->load->view('admin/add_supplier',['exist'=>$detail]);
$this->load->view('admin/includes/footer');
$this->load->view('admin/includes/add_supplier_footer');
}
else{
$this->suppliermodel->add($user);
}
}
model
public function checkData()
{
$name = $this->input->post('name');
$this->db->select('*');
$this->db->where('Name', $name);
$this->db->from('suppliers');
$query = $this->db->get();
if($query->num_rows() >0){
return $query->result();
}
else{
return $query->result();
return false;
}
}
what is ajax code and controller function
How about this?
Controller
public function insert(){
// set a rule that make the Name field is unique by 'set_rules'
$this->form_validation->set_rules('Name', 'Name Field', 'required|is_unique[suppliers.name]');
//$this->form_validation->set_rules('[Other Field]', '[Field Name to Display]', '[Restriction]');
// if the field cannot pass the rule
if ($this->form_validation->run() === FALSE) {
$errors = array();
foreach ($this->input->post() as $key => $value) {
// Add the error message for this field
$errors[$key] = strip_tags(form_error($key));
}
// Clear the empty fields (correct)
$response['errors'] = array_filter($errors);
$response['status'] = false;
}
else {
// otherwise, call the model
$result = $this->suppliermodel->add($user);
if ( $result ) {
$response['status'] = true;
}
}
echo json_encode($response);
}
JavaScript
$.ajax({
url: '//localhost/insert',
data: {
Name: $('input[name=Name]').val(),
Cnic: $('input[name=Cnic]').val(),
Phone: $('input[name=Phone]').val(),
Address: $('input[name=Address]').val()
},
dataType: 'JSON',
type: 'POST',
error: function(xhr) {
alert('request failed!');
},
success: function(response) {
var response = $.parseJSON(JSON.stringify(response));
if (response.status != true) {
$.each(response.errors, function(field, i) {
alert( field+ ' errors with ' + i)
});
}
else {
alert('success!');
}
}
});
Use is_unique[table.fieldToCompare] to make the field is always unique.
Wish it helps.
set_rules restrictions, see the Codeigniter User Guide Form validation
If fails, the controller would return a set of JSON, with field and error message. Then you can handle it in $.ajax's success.
I tried to convert the codeigniter form handling using ajax then display validation error if validation is false but in my current state, it always throw an error. Check the code below for reference.
PHP:
public function add () {
$post_data = $this->input->post('formdata');
$data = array (
'identity' => $post_data ['email'],
'password' => $post_data ['password'],
'email' => $post_data ['email'],
'group' => array($post_data['group_id']),
'additional_data' => array (
'first_name' => $post_data['first_name'],
'last_name' => $post_data['last_name'],
'active' => $post_data['active'],
'date_registered' => date('Y/m/d h:i:sa')
)
);
// custom error message
$this->form_validation->set_message('alpha_dash_space', '%s appears to be invalid. Must contain only alphabets.');
$this->form_validation->set_message('matches', '%s does not match the Confirm Password field. ');
if ($this->form_validation->run() == TRUE) {
$result['data'] = $this->ion_auth->register($data['identity'], $data['password'], $data['email'], $data['additional_data'], $data['group']);
} else {
$result['message'] = validation_errors();
}
echo json_encode($result);
}
JS:
function submit_form (form_id) {
var url = $(form_id).attr("action");
var formData = {};
$(form_id).find("input[name]").each(function (index, node) {
formData[node.name] = node.value;
});
$(form_id).find('select[name]').each(function (index, node) {
formData[node.name] = node.value;
});
$(form_id).find('textarea[name]').each(function (index, node) {
formData[node.name] = node.value;
});
$.ajax({
type: "POST",
data: {
'formdata': formData
},
url: url,
dataType: 'json',
success: function(result) {
if (result.data) {
console.log(success);
swal({
title: "Success!",
text: "You've done it great!",
type: "success"
},
function(){
location.reload();
});
} else {
$('#error-msg').html(result.message);
}
},
error: function(data) {
swal({
title: "Error!",
text: "Oops, something went wrong. Check and try again.",
type: "error"
});
}
});
}
Note: Form validation are set in config directory. So no issues in form rules. All are running good except I think the jquery that handles the condition.
Edit like below:
if ($this->form_validation->run() == FALSE) {
$result['message'] = validation_errors();
} else {
$result['data'] = $this->ion_auth->register($data['identity'],
$data['password'], $data['email'], $data['additional_data'],
$data['group']);
}
Also you have set_message but not set_rules. If you want to use form_validation library, you should set some rules.
I am trying to post user emails to subscribe to my site but my console keeps giving me a 404 exception for the route. I have a table called betas, and a model called Beta in App\Beta.php. Here is my route:
use App\Beta;
use Illuminate\Http\Request;
Route::post('/email',['middleware'=>'csrf',function (Request $request){
$validator=Validator::make($request->all(),[
'email' => 'required|max:64|email|unique:betas,email'
]);
//if validator passes save the email in the database
if($validator->passes()){
$beta = new App\Beta;
$beta->email=$request->email;
$beta->save();
$response=array(
'status' => 'Email posted successfully'
);
}
else{
$messages = $validator->messages();
$response=array(
'messages' => $messages->first('email'),
'status' => 'Email post failed',
);
}
return response()->json($response);
}]);
Below is my js file:
$("#betaForm").submit(function(){
$(".loadingPic").show();
var email=$("#emailInput").val();
console.log("email:"+email);
//pause for a bit to see pretty loading icon
console.log("before setTimeout");
var load=setTimeout(function(){return undefined;}, 1000);
console.log("after setTimeout");
if(email==""){
$("#warningMessage").html("please input your email");
$("#warningMessage").show();
}
else{
$.post({
url: $(this).prop('action'),
data: {
"_token": $( this ).find( 'input[name=_token]' ).val(),
"email": email
},
success: function(result){
if (result.status!='Email posted successfully'){
$("#warningMessage").html(result.messages);
$("#warningMessage").removeClass( "alert-success");
$("#warningMessage").addClass("alert-danger");
$("#warningMessage").show();
}
else{
$("#betaForm button").prop("disabled",true);
$("#betaForm button").html("Awesome! Well Be In Touch.");
}
},
dataType: 'json'
});
}
$(".loadingPic").hide();
return false;
});
When the submit button is pressed, I receive the error in my browser console.
I think issue on 'middleware'=>'csrf'.