How to change error 302 in laravel with ajax - ajax

I am working with laravel and ajax. But when I register I see this error 302.
I know this may be a trivial question but I am just not able to get this ajax call to work.
Auth/RegisterController.php
protected function create(array $data, Request $request)
{
if ($request->hasFile('image')) {
$fileNameWithExt = $request->file('image')->getClientOriginalName();
$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extention = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extention;
$path = $request->file('image')->storeAs('public/images', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
return User::create([
'firstname' => $data['firstـname'],
'lastname' => $data['lastـname'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'mobile' => $data['mobile'],
'nasional_code' => $data['national_code'],
'birthdate' => $data['birthـdate'],
'document' => $data['document'],
'educational' => $data['educational'],
'gender' => $data['gender'],
'side' => $data['side'],
$fileNameToStore => $data['image']
]);
}
My ajax is register.js file
How do I pass the "Accept'=>'application/json" in request when testing:
I want to add 'accept'=>'application/json' to my request header.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function scroll_to_class(element_class, removed_height) {
var scroll_to = $(element_class).offset().top - removed_height;
if($(window).scrollTop() != scroll_to) {
$('html, body').stop().animate({scrollTop: scroll_to}, 0);
}
}
function bar_progress(progress_line_object, direction) {
var number_of_steps = progress_line_object.data('number-of-steps');
var now_value = progress_line_object.data('now-value');
var new_value = 0;
if(direction == 'right') {
new_value = now_value + ( 100 / number_of_steps );
}
else if(direction == 'left') {
new_value = now_value - ( 100 / number_of_steps );
}
progress_line_object.attr('style', 'width: ' + new_value + '%;').data('now-value', new_value);
}
jQuery(document).ready(function() {
$('form fieldset:first').fadeIn('slow');
$('form input[type="text"], form input[type="password"], form textarea').on('focus', function() {
$(this).removeClass('input-error');
});
$('form .btn-next').on('click', function() {
var parent_fieldset = $(this).parents('fieldset');
var next_step = true;
var current_active_step = $(this).parents('form').find('.form-wizard.active');
var progress_line = $(this).parents('form').find('.progress-line');
parent_fieldset.find('input[type="text"], input[type="password"], input[type="email"], input[type="radio"]').each(function() {
if( $(this).val() == "" ) {
$(this).addClass('input-error');
next_step = false;
}
else {
$(this).removeClass('input-error');
}
});
parent_fieldset.find('input[type="checkbox"]').each(function() {
if( $(this).prop("checked") == false ) {
$('.form-check-label').css("color","red");
next_step = false;
}
else {
$('.form-check-label').css("color","black");
}
});
if( next_step ) {
parent_fieldset.fadeOut(400, function() {
current_active_step.removeClass('active').addClass('activated').next().addClass('active');
bar_progress(progress_line, 'right');
$(this).next().fadeIn();
scroll_to_class( $('form'), 20 );
});
}
});
// previous step
$('form .btn-previous').on('click', function() {
var current_active_step = $(this).parents('form').find('.form-wizard.active');
var progress_line = $(this).parents('form').find('.progress-line');
$(this).parents('fieldset').fadeOut(400, function() {
current_active_step.removeClass('active').prev().removeClass('activated').addClass('active');
bar_progress(progress_line, 'left');
$(this).prev().fadeIn();
scroll_to_class( $('form'), 20 );
});
});
$('form').on('submit', function(e) {
$(this).find('input[type="text"], input[type="password"], input[type="username"], input[type="email"], input[type="tel"], input[type="url"], textarea').each(function() {
if( $(this).val() == "" ) {
e.preventDefault();
$(this).addClass('input-error');
}
else {
$(this).removeClass('input-error');
}
});
});
});

Related

Laravel 7: Full Calendar not showing events

Please see my code first:
Controller:
public function getHolidays($days, $start_date) {
$date = date('Y-m-d',strtotime($start_date));
$i = 0;
$response = array();
while ($i <= 42) {
$tsDate = strtotime($date. ' ' .'+ '.$i.' days');
$day = date('D', $tsDate);
if(in_array($day, $days)) {
$data = array();
$data['title'] = 'Weekend';
$data['start'] = date('Y-m-d',$tsDate);
$data['end'] = date('Y-m-d',$tsDate);
$response[] = $data;
}
$i++;
}
return $response;
}
public function index(request $request){
if($request->ajax()) {
$weekends = DB::table('working_days')
->where('status', 0)
->get(['day'])
->map(function($item) {
return $item->day;
})->toArray();
$holidays = DB::table('holidays')
->get()
->map(function($item) {
return [
'title' => 'Holiday',
'start' => Carbon::parse($item->date)->format('Y-m-d'),
'end' => Carbon::parse($item->date)->format('Y-m-d'),
];
})->toArray();
$attendances = DB::table('attendances as a')
// ->where('leave_cat_id', '!=', null)
->where('user_id', Auth::user()->id)
->get()
->map(function($item) {
return [
'title' => 'Leave',
'start' => Carbon::parse($item->date)->format('Y-m-d'),
'end' => Carbon::parse($item->date)->format('Y-m-d'),
'color' => 'red',
];
})->toArray();
$data = [...$this->getHolidays($weekends, $request->start), ...$holidays, ...$attendances];
return response()->json($data);
}
return view('admin.dashboard');
}
Blade File script:
<script>
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var calendar = $('#full-calendar').fullCalendar({
editable: true,
editable: true,
events: '/dashboard',
eventRender: function (event, element, view) {
if (event.allDay === 'true') {
event.allDay = true;
} else {
event.allDay = false;
}
},
});
});
</script>
Tables:
attendances
id
user_id
date
status
leave_cat_id
1
2
2022-07-13
1
null
2
2
2022-07-12
0
1
holidays
id
date
1
2022-07-13
2
2022-07-20
working_days
id
day
working_status
1
Fri
0
2
Sat
1
3
Sun
1
I want to show attendances on Full Calendar [https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.10.2/fullcalendar.min.js]
First, weekly holiday will show when the working_status = 0 and day is matched with calendar.
Second, holidays will show when it will match the dates with calendar date
Third, attendance will show on other days. If the status is 1 it will show present and if 0 it will show absent. Also, if the leave_cat_id column is not equal to null, then it will show On leave, others it will show the attendance status.
Can you please modify my code for this?
Thanks
public function getHolidays($days, $start_date) {
$date = date('Y-m-d',strtotime($start_date));
$i = 0;
$response = array();
while ($i <= 42) {
$tsDate = strtotime($date. ' ' .'+ '.$i.' days');
$day = date('D', $tsDate);
if(in_array($day, $days)) {
$data = array();
$data['title'] = 'Weekend';
$data['start'] = date('Y-m-d',$tsDate);
$data['end'] = date('Y-m-d',$tsDate);
$response[] = $data;
}
$i++;
}
return $response;
}
public function index(request $request){
if($request->ajax()) {
$weekends = DB::table('working_days')
->where('working_status''status', 0)
->get(['day'])
->map(function($item) {
return $item->day;
})->toArray();
$holiday$holidays = DB::table('holidays')
->get()
->map(function($item) {
return [
'title' => 'Holiday',
'start' => Carbon::parse($item->date)->format('Y-m-d'),
'end' => Carbon::parse($item->date)->format('Y-m-d'),
];
})->toArray();
$attendances = DB::table('attendances''attendances as a')
// ->where('leave_cat_id', '!=', null)
->where('user_id', Auth::user()->id)
->get()
->map(function($item) {
return [
'title' => $item->leave_cat_id ? 'Leave' : ($item->attendance_status == 1 ? 'Present' : 'Absent'),
'start' => Carbon::parse($item->attendance_date>date)->format('Y-m-d'),
'end' => Carbon::parse($item->attendance_date>date)->format('Y-m-d'),
'color' => $item->attendance_status == 1 ? 'green' : 'red',
];
})->toArray();
$data = [...$this->getHolidays($weekends, $request->start), ...$holiday$holidays, ...$attendances];
return response()->json($data);
}
return view('admin.dashboard');
}
<script type="text/javascript"><script>
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var calendar = $('#full-calendar').fullCalendar({
editable: true,
editable: true,
events: '/dashboard',
eventRender: function (event, element, view) {
if (event.allDay === 'true') {
event.allDay = true;
} else {
event.allDay = false;
}
},
});
});
</script>

Doing live search in codeigniter via ajax , mongodb

This is my ajax code which fetches all data from data and display in the table, but when I input an alphabet in search-box, it again fetches complete data inside the table
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "<?php echo base_url() ?>Appconfig/get_masteradmin_data?query="+query,true);
xhttp.onload= function()
{
if (xhttp.status >=200 && xhttp.status <400)
{
var data= JSON.parse(xhttp.responseText);
var html = '';
var i;
for(i=0; i<data.length; i++){
html +='<tr>'+
'<td>'+data[i].full_name+'</td>'+
'<td>'+data[i].username+'</td>'+
'<td>'+data[i].designation+'</td>'+
'<td>'+data[i].department+'</td>'+
'<td>'+data[i].official_mobile_no+'</td>'+
'<td>'+data[i].official_email_id+'</td>'+
'<td>'+data[i].select_user_type+'</td>'+
'<td>'+data[i].permission+'</td>'+
'</tr>';
}
showdata.insertAdjacentHTML('beforeend',html);
}
else
{
console.log("Try again after some time");
}
};
xhttp.send();
}
$('#search').keyup(function(){
var search = $(this).val();
//console.log(search);
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
This is my model for fetching data from my mongodb collection.
public function get_masteradmin_data($query)
{
$mongo = new \MongoDB\Driver\Manager('mongodb://localhost:27017');
$query= '';
//$filter = ['full_name' => 'www'];
$regex = new MongoDB\BSON\Regex ($query);
$filter = ['full_name'=>$regex,];
$options =[
'projection' => [
'_id' => 0,
'full_name' => 1,
'username' => 1,
'designation'=> 1,
'department'=> 1,
'official_mobile_no'=> 1,
'official_email_id'=> 1,
'select_user_type'=> 1,
'permission'=> 1,
],
'sort' => [
'_id' => -1
],
];
$query = new MongoDB\Driver\Query($filter, $options);
//$readPreference = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
$result = $mongo->executeQuery('justrack_db.master_admin', $query);
$res = array();
foreach($result as $r)
{
$res[] = $r;
}
return json_encode($res,true);
//return $res;
}
This is my controller for displaying data. I am not sure, but I think there is some issue in my controller, as I tried to echo $query but it shows nothing. I am not able to understand how to fix this.
public function get_masteradmin_data()
{
$query = '';
$this->load->model('AppconfigModel');
$this->master_admin();
if($this->input->post('query'))
{
$query = $this->input->post('query');
}
$result= $this->AppconfigModel->get_masteradmin_data($query);
echo ($result);
}

Ajax with laravel Post returning

I am working with laravel and ajax. But when I register I see this error 302.
I know this may be a trivial question but I am just not able to get this ajax call to work.
Auth/RegisterController.php
protected function create(array $data, Request $request)
{
if ($request->hasFile('image')) {
$fileNameWithExt = $request->file('image')->getClientOriginalName();
$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extention = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extention;
$path = $request->file('image')->storeAs('public/images', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
return User::create([
'firstname' => $data['firstـname'],
'lastname' => $data['lastـname'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'mobile' => $data['mobile'],
'nasional_code' => $data['national_code'],
'birthdate' => $data['birthـdate'],
'document' => $data['document'],
'educational' => $data['educational'],
'gender' => $data['gender'],
'side' => $data['side'],
$fileNameToStore => $data['image']
]);
}
My ajax is register.js file
How do I pass the "Accept'=>'application/json" in request when testing:
I want to add 'accept'=>'application/json' to my request header.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function scroll_to_class(element_class, removed_height) {
var scroll_to = $(element_class).offset().top - removed_height;
if($(window).scrollTop() != scroll_to) {
$('html, body').stop().animate({scrollTop: scroll_to}, 0);
}
}
function bar_progress(progress_line_object, direction) {
var number_of_steps = progress_line_object.data('number-of-steps');
var now_value = progress_line_object.data('now-value');
var new_value = 0;
if(direction == 'right') {
new_value = now_value + ( 100 / number_of_steps );
}
else if(direction == 'left') {
new_value = now_value - ( 100 / number_of_steps );
}
progress_line_object.attr('style', 'width: ' + new_value + '%;').data('now-value', new_value);
}
jQuery(document).ready(function() {
$('form fieldset:first').fadeIn('slow');
$('form input[type="text"], form input[type="password"], form textarea').on('focus', function() {
$(this).removeClass('input-error');
});
$('form .btn-next').on('click', function() {
var parent_fieldset = $(this).parents('fieldset');
var next_step = true;
var current_active_step = $(this).parents('form').find('.form-wizard.active');
var progress_line = $(this).parents('form').find('.progress-line');
parent_fieldset.find('input[type="text"], input[type="password"], input[type="email"], input[type="radio"]').each(function() {
if( $(this).val() == "" ) {
$(this).addClass('input-error');
next_step = false;
}
else {
$(this).removeClass('input-error');
}
});
parent_fieldset.find('input[type="checkbox"]').each(function() {
if( $(this).prop("checked") == false ) {
$('.form-check-label').css("color","red");
next_step = false;
}
else {
$('.form-check-label').css("color","black");
}
});
if( next_step ) {
parent_fieldset.fadeOut(400, function() {
current_active_step.removeClass('active').addClass('activated').next().addClass('active');
bar_progress(progress_line, 'right');
$(this).next().fadeIn();
scroll_to_class( $('form'), 20 );
});
}
});
// previous step
$('form .btn-previous').on('click', function() {
var current_active_step = $(this).parents('form').find('.form-wizard.active');
var progress_line = $(this).parents('form').find('.progress-line');
$(this).parents('fieldset').fadeOut(400, function() {
current_active_step.removeClass('active').prev().removeClass('activated').addClass('active');
bar_progress(progress_line, 'left');
$(this).prev().fadeIn();
scroll_to_class( $('form'), 20 );
});
});
$('form').on('submit', function(e) {
$(this).find('input[type="text"], input[type="password"], input[type="username"], input[type="email"], input[type="tel"], input[type="url"], textarea').each(function() {
if( $(this).val() == "" ) {
e.preventDefault();
$(this).addClass('input-error');
}
else {
$(this).removeClass('input-error');
}
});
});
});
Update your ajax header, according to this:
$.ajaxSetup({
headers: {
accepts: "application/json; charset=utf-8",
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
The possibilities of this issue is CSRF token and missing route.

How to apply diffForHumans() in laravel using ajax?

I'm working with laravel and native ajax. I am wondering where do I put diffForhHumans() when using ajax. In my Controller. I just return the object fetch.
Here's my Controller
public function getDownlines($id) {
$upline = Upline::find($id);
return $upline->downlines;
}
Model
public function downlines() {
return $this->hasMany('App\Downline');
}
HTML Code in View
<div id="downlines">
<div class="downlines-title-container">
<p class="title"></p>
</div>
<div id="downlines-holder">
<div class="p_parent_header">
<p>ID</p>
<p>Account Code</p>
<p>Created By</p>
<p>Created At</p>
</div>
</div>
</div>
Script in Ajax
var downlines = document.getElementById('downlines'),
downlines_holder = document.getElementById('downlines-holder');
function getPromise(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function() {
if(xhr.status == 200) {
resolve(xhr.response);
} else {
reject(Error(xhr.statusText))
}
}
xhr.onerror = function() {
reject(Error('Network Error'));
};
xhr.send();
})
}
function getDownlines(e, id) {
getPromise('upline/getdownlines/' + id).then(function(response) {
var resp = JSON.parse(response),
p_parent = document.getElementsByClassName('p_parent'),
p = p_parent.length;
while(p--) p_parent[p].remove();
if(resp.length > 0) {
downlines.style.display = 'initial'
downlines.children[0].children[0].innerHTML = e.innerHTML;
for(var i = 0; i < resp.length; i++) {
var p_parent = document.createElement('div'),
p1 = document.createElement('p'),
p2 = document.createElement('p'),
p3 = document.createElement('p'),
p4 = document.createElement('p');
p_parent.classList.add('p_parent');
p1.innerHTML = resp[i].id;
p2.innerHTML = resp[i].account_code;
p3.innerHTML = resp[i].created_by;
p4.innerHTML = resp[i].updated_at;
p_parent.appendChild(p1);
p_parent.appendChild(p2);
p_parent.appendChild(p3);
p_parent.appendChild(p4);
downlines_holder.appendChild(p_parent);
}
} else {
downlines.style.display = 'none'
}
}, function(error) {
console.log(error);
})
}
I'm searching for the same problem and doesn't find one.
Any help would be appreciated. Thanks!!!
Please do this before returning the downlines
public function getDownlines($id)
{
$upline = Upline::find($id);
return $upline->downlines->map(function($downline) {
return [
'id' => $downline->id,
'account_code' => $downline->account_code,
'created_by' => $downline->created_by,
'created_at' => $downline->created_at->diffForHumans(),
'updated_at' => $downline->updated_at->diffForHumans(),
];
});
}
I am unsure if you want to use created_at or updated_at, because in the html you have written <p>Created At</p> but in the AJAX request, you have written p4.innerHTML = resp[i].updated_at;. So I added both in the return array :)

Modify request object in Symfony 2

i have the following code on my controller:
/**
*
* #Route("/{discountLevelItemId}/manage-product/update", name="discountlevel_manage_product_update", defaults={"_format"="json"} )
* #Method("POST")
*/
public function manageProductUpdateAction($discountLevelItemId, Request $request)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('CIInventoryBundle:DiscountLevelItem')->find($discountLevelItemId);
$form = $this->createForm(new DiscountLevelItemCollectionType(), $entity);
$form->bindRequest($request);
if ($form->isValid()) {
//remove items without discount type
foreach ($entity->getDiscountLevelItemProducts() as $item) {
if (!$item->getDiscountType()) {
$entity->getDiscountLevelItemProducts()->removeElement($item);
$em->remove($item);
}
}
$em->persist($entity);
$em->flush();
$responseData = array(
'status' => 'success',
'message' => 'Supplier product discounts successfully saved.'
);
} else {
$responseData = array(
'status' => 'error',
'form' => $this->renderView('CIInventoryBundle:DiscountLevel:manageProducts.html.twig', array(
'entity' => $entity,
'form' => $form->createView()
))
);
}
return new Response(json_encode($responseData), 200, array('Content-Type'=>'application/json'));
}
This action is called via ajax. Before calling this controller i filtered some data out like so:
initForm: function() {
//submit form function
var options = {
delegation: true,
dataType: "json",
beforeSubmit: function(arr, $form, options) {
//holds objects every four looping
var tempArray = new Array();
//holds changed objects that will only be submitted in the server.
var changedArray = new Array();
var found = false;
var idx = 1;
//get the token then remove from arr.
changedArray.push(arr.splice(arr.length-1,1)[0]);
for (var j = arr.length-1; j >= 0; j--) {
var obj = arr[j];
if ( viewCtrl.dliProductsChanged.indexOf(obj.value) != -1 ) {
found = true;
}
tempArray.push(arr[j]);
if(idx % 4 == 0) {
if (found == true) {
for(var i = 0; i < tempArray.length; i++){
changedArray.push(tempArray[i]);
}
found = false;
}
tempArray.length = 0;
}
idx++;
}
arr.length = 0;
for(var i = 0; i < changedArray.length; i++){
arr.push(changedArray[i]);
}
viewCtrl.dliProductsChanged.length = 0;
$form.find( ".submit-button" ).button( "loading" );
$form.find( ".discount-value, .trucking" ).addClass( "uneditable-input" );
$form.find( ".discount-type" ).attr( "readonly", true );
},
success: function(responseText, statusText, xhr, $form) {
if ( responseText.status == "success" ) {
viewCtrl.modal.modal( "hide" );
$.growl.notice({ title: "<strong>Saved</strong>", message: responseText.message, size: "large", duration: 5000, location: "br" });
viewCtrl.dliProductsChanged.length = 0;
} else {
viewCtrl.modal.find( ".modal-content" ).html( responseText.form );
}
$form.find( ".submit-button" ).button( "reset" );
}
};
$( "#manage-products-form" ).ajaxForm( options );
},
My question is, how can i repopulate the form with data i filtered out when the form gets invalid? The first thing came out of my mind is modifying the request object and then rebinding it again but i dont know how to implement that...
Any insights?
PS: I user JQUERY Form Plugin on form submission.
Thanks!

Resources