I am submitting a form and AJAX is displaying errors as it should but when everything goes right, it means that when form values are saving in database correctly AJAX is not triggering the success function.
Here's the Laravel product verification code:
public function productVerify(Request $request)
{
$val = $request->validate
(
[
'name' => 'required',
's_description' => 'required',
'l_description' => 'required',
'image_src' => 'required|mimes:jpg,png,jpeg',
'category' => 'required',
'quantity' => 'required|integer|not_in:0|regex:^[1-9][0-9]+^',
'price' => 'required|integer|not_in:0|regex:^[1-9][0-9]+^',
],
[
'required' => 'The :attribute field is required',
'mimes' => 'Image should be a JPG, JPEG, or PNG',
'integer' => 'The :attribute field should be an integer.',
's_descripton.required' => 'The short description is required',
'l_descripton.required' => 'The long description is required',
'image_src.required' => 'The image file is required.'
]
);
if (!$val)
{
return response()->json(['errors']);
}
else
{
return response()->json(['success' => 'Product Added Successfully']);
}
}
Here's the AJAX code:
$(document).ready(function()
{
$("#addForm").submit(function(event)
{
// Store all data from form as object;
var formData = new FormData(this);
$.ajaxSetup({
headers:
{
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
// AJAX implementation error:function() return errors without page reload.
$.ajax(
{
url: '/save_product',
type: "POST",
processData:false,
contentType:false,
cache:false,
dataType: 'json',
data:formData,
success: function(xhr)
{
responseSu = xhr.responseJSON.success;
alert(responseSu);
},
error:function(xhr, status, error)
{
// Errors from the XML Http Request JSON Response
responseER = xhr.responseJSON.errors;
// console.log(responseER);
$("#error").html(" ");
// For Each loop for printing errors from the response
$.each(responseER, function (key, item)
{
console.log(item);
$("#error").append("<li class='text-danger'>"+item+"</li>")
// Hide Errors after 15 seconds with a fadeout animation
$("#error").show().delay(15000).fadeOut();
});
}
});
// Stop form from submitting normally
event.preventDefault();
});
});
After the form is submitted successfully and data is inserted into database it gives the error:
Related
I've tried passing through using string (teachers_remark.*) from what I searched, but it is not validated in the controller. I expected it to return an error, but it is successfully saved instead.
Need help, I'm a beginner in jQuery.
This is my jQuery:
var students_id = $('#students').val();
var teachers_id = $('#teachers').val();
var teacherArray = $('#my_teachers_remarks input').map(function () {
return {
"value": this.value,
}
}).get();
sessionStorage['teachers'] = JSON.stringify(teacherArray);
var teachers_remark_arr = [];
teachers_remark_arr = sessionStorage['teachers'];
event.preventDefault();
swal({
title: "{{ __('Are you sure?') }}",
text: "{{ __('No further changes allowed.') }}",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then(function(willAssign) {
if (willAssign) {
return axios.post(route('students.report'), {
students: students_id,
teachers: teachers_id,
'teachers_remark.*': teachers_remark_arr,
})
.then(function (response) {
if (response.data.status === 'ERROR'){
swal({
title: "Error",
text: response.data.errors,
icon: "error"
}).then(function(){
location.reload();
});
}
if (response.data.status === 'SUCCESS'){
swal("Success", response.data.message , "success");
}
})
This is my Controller:
$this->validate(
$request,
[
'students' => ['required'],
'teachers' => ['required'],
'teachers_remark.*' => ['required'],
],
[
'students.required' => 'There is no students selected.',
'teachers.required' => 'There is no teachers selected.',
'teachers_remark.*.required' => 'You must include remarks',
]
);
how i cant redirect o return a view after a ajax request.
i try validate the request and after (if the request are ok) return a view, but this dont work, i try redirect to the new route but dont work too.
this is my controller:
public function searchActivity(Request $request){
$validator = Validator::make($request->all(), [
'search' => 'required',
'date' => 'required_with:search|required|date|date_format:d-m-y|after:yesterday'
]);
if ($validator->fails()){
return response()->json([
'sucess' => false,
'errors' => $validator->errors()->toArray(),
'data' => $request->all()
]);
}else{
$queries = DB::table('activities')->where('name', $request->search)->orWhere('City', $request->search)->paginate(1);
return redirect()->route('ActivitiesResults', ['results' => $queries]);
}
JS code:
function selectDate(){
$(document).ready(function () {
$( "#datepicker" ).datepicker({ dateFormat: 'dd-mm-yy' });
});
}
function searchActivity(event) {
event.preventDefault();
console.log(event);
$.ajax({
type: 'POST',
url: searchRoute,
data: {
search: $('.search').val(),
date: $('#datepicker').val(),
_token: $('#token').val()
},
dataType : "json",
success: function (data) {
if (data.success){
console.log(data)
}else{
console.log(data.errors);
}
}
})
}
thanks for the help!
you need to change your php code
if ($validator->fails()){
return response()->json([
'sucess' => false,
'errors' => $validator->errors()->toArray(),
'data' => $request->all()
]);
}else{
return response()->json([
'sucess' => true,
'what_you_want' => ''
]); }
change your ajax code like this
success: function (data) {
if (data.success){
//console.log(data)
window.location.replace("http://stackoverflow.com");
}else{
console.log(data.errors);
window.location.replace("http://google.com");
}
}
use header("url) or window.location.href="url" in you success funciton.
I'm trying to send data through AJAX put method. I don't know what I'm doing wrong.
All code posible code
link
My route file
Route::resource('restaurant', 'RestaurantController');
RestaurantController
public function update(Request $request, $id)
{
$rules = array (
'address_id' => 'required|alpha',
'name' => 'required|alpha',
'description' => 'required',
'phone' => 'required',
'email' => 'required|email',
'homemade' => 'required'
);
$validator = Validator::make ( Input::all (), $rules );
if ($validator->fails ())
return Response::json ( array (
'errors' => $validator->getMessageBag ()->toArray ()
) );
else {
$items = Restaurant::find ($id);
$items->address_id = ($request->address_id);
$items->name = ($request->name);
$items->description = ($request->description);
$items->phone = ($request->phone);
$items->email = ($request->email);
$items->homemade = ($request->homemade);
$items->save ();
return response ()->json ( $items );
}
}
ajax request
$('.modal-footer').on('click', '.edit', function() {
$.ajax({
type: 'PUT',
url: '/restaurant',
data: {
'_token': $('input[name=_token]').val(),
'id': $("#fid").val(),
'address_id': $('#address_id').val(),
'name': $('#name').val(),
'description': $('#description').val(),
'phone': $('#phone').val(),
'email': $('#email').val(),
'homemade': $('#homemade').val(),
'lat': $('#lat').val(),
'lng': $('#lng').val(),
'bank_name': $('#bank_name').val(),
'bank_code': $('#bank_code').val(),
'paypal_email': $('#paypal_email').val(),
'paypal_merchantname': $('#paypal_merchantname').val(),
'zipcode': $('#zipcode').val(),
'easypeisa': $('#easypeisa').val(),
'cod': $('#cod').val()
},
success: function(data) {
if (data.errors){
$('#myModal').modal('show');
if(data.errors.address_id) {
$('.address_id_error').removeClass('hidden');
$('.address_id_error').text("address_id name can't be empty !");
}
if(data.errors.name) {
$('.name_error').removeClass('hidden');
$('.name_error').text("name can't be empty !");
}
if(data.errors.description) {
$('.description_error').removeClass('hidden');
$('.description_error').text("description must be a valid one !");
}
I am new to jquery and ajax and now I have a hard time finding a fix to this problem of mine when inserting data into database using ajax and codeigniter.
All errors are okay but when there's no error on the form, I get a database error and all the inputs become NULL.
Controller
public function add () {
$this->load->model('user_model');
$data => array (
'first_name' => $this->input->post['first_name'],
'last_name' => $this->input->post['last_name'],
'active' => $this->input->post['active'],
'date_registered' => date('Y/m/d h:i:sa')
);
// assume validation rules are already set.
if ($this->form_validation->run() == FALSE) {
$result['message'] = validation_errors();
} else {
$result['data'] = $this->user_model->save($data);
}
}
Ajax 1:
$(document).ready(function() {
$('#create-user').click( function(e) {
var is_valid = false;
var form_id = '#'+ $(this).parents('form').attr('id');
// Validate required fields are not blank
// do a js validation?
// Apply action
if(is_valid) {
var add_result = do_submit(form_id);
} else {
$('#error-msg').html(result.message); // if form is not valid
}
});
});
Ajax 2:
function do_submit(form_id) {
var url = $(form_id).attr("action");
var ajax_result = false;
var formData = {};
// Submit form using ajax
ajax_result = $.ajax({
type: "POST",
url: url,
data: $(form_id).serialize(),
dataType: 'json',
success: function(result) {
// return result;
// do something
console.log(result);
if (result.data) {
make_alert();
}
},
error: function(textStatus) {
/* Note: decide how all errors should be shown. */
swal({
title: "Error!",
text: "Oops, something went wrong. Check fields and try again.",
type: "error"
});
}
});
return ajax_result;
} // End do_submit()
I think you have a syntax error here
$this->load->model('user_model');
'data' => array (
'first_name' => $this->input->post['first_name'],
'last_name' => $this->input->post['last_name'],
'active' => $this->input->post['active'],
'date_registered' => date('Y/m/d h:i:sa')
);
Should probably be
$this->load->model('user_model');
$data => array (
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'active' => $this->input->post('active'),
'date_registered' => date('Y/m/d h:i:sa')
);
Your parameter array seems to be a key, but of what variable? So you need to have $data instead of 'data'.
To get post data in codeigniter we use
$this->input->post('field_name');
SO you need to change all post['field_name'] to post('field_name')
Your final code would be
$this->load->model('user_model');
$data => array (
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'active' => $this->input->post('active'),
'date_registered' => date('Y/m/d h:i:sa')
);
Read https://www.codeigniter.com/user_guide/libraries/input.html
I have a form which is created using cakephp form builder, this form has a couple of file upload fields as below:
<?php echo $this->Form->create('application', array('type' => 'file', 'url' => array('app' => true, 'controller' => 'jobs', 'action' => 'save_new_application'), 'id' => 'create-application-form'));
echo '<p>'.$this->Form->input('cv', array('type' => 'file', 'label' => "Upload CV (Required)", 'required' => true)).'</p>';
echo '<p>'.$this->Form->input('cover-letter', array('type' => 'file', 'label' => "Upload Cover Letter (optional)")).'</p>';
echo $this->Form->input('campaignid', array('type' => 'hidden', 'class' => 'form-control sendid', 'label' => false, 'value' => $campaignid));
echo $this->Form->input('profileid', array('type' => 'hidden', 'class' => 'form-control sendid', 'label' => false, 'value' => $profileid));
echo $this->Form->submit('Apply', array('class' => 'form-control')); ?>
<?php echo $this->Form->end(); ?>
I however need this form to be submitted via ajax so that the page doesnt refresh, as with other forms on the site I have the below jquery, however the controller only gets the two hidden fields and no information about the upload files.
$('#create-application-form').off().on('submit', function(e){
e.preventDefault();
$.ajax({
url: '/app/jobs/save_new_application/',
dataType: 'json',
method: 'post',
data: $(this).serialize()
})
.done(function(response) {
//show result
if (response.status == 'OK') {
} else if (response.status == 'FAIL') {
} else {
//show default message
}
})
.fail(function(jqXHR) {
if (jqXHR.status == 403) {
window.location = '/';
} else {
console.log(jqXHR);
}
});
});
What do i need to change in the ajax call to be able to pass the actual file data to the controller so the files can be saved on the server?
You have to send New FormData() object to send file using ajax
Updated code
$('#create-application-form').off().on('submit', function(e){
e.preventDefault();
var formdatas = new FormData($('#create-application-form')[0]);
$.ajax({
url: '/app/jobs/save_new_application/',
dataType: 'json',
method: 'post',
data: formdatas,
contentType: false,
processData: false
})
.done(function(response) {
//show result
if (response.status == 'OK') {
} else if (response.status == 'FAIL') {
} else {
//show default message
}
})
.fail(function(jqXHR) {
if (jqXHR.status == 403) {
window.location = '/';
} else {
console.log(jqXHR);
}
});
});