return blade after execute ajax - php

i´m traying to load #include() blade in other blade in laravel after response ok in ajax. I´m doing a statistics in tab pane and i need send data to my controller, for this i´m doing ajax i have this ajax:
$("#createStatistcs").on('click', function(){
let fromDate = $("#fromDate").val();
let toDate = $("#toDate").val();
let token = $('meta[name=csrf-token]').attr('content');
$.ajax({
type: 'GET',
url: "{{ route('admin.llamadas.estadisticas') }}",
data: { 'fromDate': fromDate, 'toDate': toDate },
success: function(response){
},
error: function(xhr){
alert(xhr.responseText);
}
});
})
and i have this in my controller:
public function index(Request $request)
{
$estadosLlamadas = EstadoLlamada::orderBy('desc')->get();
if(isset($request->fromDate) && isset($request->toDate)){
$fromDate = Carbon::parse($request->get('fromDate'));
$toDate = Carbon::parse($request->get('toDate'));
$fromDate = $fromDate->format('Y-m-d');
$toDate = $toDate->format('Y-m-d');
}else{
$fromDate = new Carbon('first day of this month');
$toDate = new Carbon('last day of this month');
$fromDate = $fromDate->format('Y-m-d');
$toDate = $toDate->format('Y-m-d');
}
$teleoperadoras = auth()->user()->whereIs('teleoperadora')->activos()->select(['id', 'nombre'])->orderBy('nombre', 'desc')->get();
$array = [
'toDate' => $toDate,
'fromDate' => $fromDate,
'nombresEstados' => $estadosLlamadas->pluck('desc')->toArray(),
'coloresEstados' => $estadosLlamadas->pluck('hex')->toArray()
];
$query = Llamada::query()
->whereDate('llamada.created_at', '<=', $toDate)
->whereDate('llamada.created_at', '>=', $fromDate)
->whereIn('llamada.id_teleoperadora', $teleoperadoras->pluck('id'))
->join('users', 'llamada.id_teleoperadora', '=', 'users.id')->latest('llamada.created_at')->get();
foreach($teleoperadoras as $teleoperadora) {
$array['teleoperadoras'][] = $teleoperadora->nombre;
$array['id_teleoperadoras'][] = $teleoperadora->id;
$array[$teleoperadora->id]['resultados'] = [];
$array['llamadas'][] = $query->where('id_teleoperadora', $teleoperadora->id)->count();
$array['llamadasTodo'][$teleoperadora->id] = $query->where('id_teleoperadora', $teleoperadora->id);
foreach($estadosLlamadas as $estado) {
$array[$teleoperadora->id]['resultados'][] = $query->where('id_teleoperadora', $teleoperadora->id)->where('id_estado', $estado->id)->count();
}
}
$array['nllamadas'] = $query->count();
$roleUser = auth()->user()->getRoles()->first();
$view = view('admin.llamadas.filtrado', [
'datos' => $array, 'estados' => $estadosLlamadas,
'teleoperadoras' => $teleoperadoras, 'roleUser' => $roleUser,
])->render();
echo response()->json(['html'=>$view]);
}
this function return all data i need. But i want that don´t reload my page and generate graphic in this view.
i´m traying this, don´t return error, but return nothing. I´m reading in google and many people say that use ->render() but i can´t show result
Thanks for help me and readme

If you have a div in your template where you want this blade view to be displayed, you can do:
$("#createStatistcs").on('click', function(){
let fromDate = $("#fromDate").val();
let toDate = $("#toDate").val();
let token = $('meta[name=csrf-token]').attr('content');
$.ajax({
type: 'GET',
url: "{{ route('admin.llamadas.estadisticas') }}",
data: { 'fromDate': fromDate, 'toDate': toDate },
success: function(response){
$('your-element').html(response.html);
},
error: function(xhr){
alert(xhr.responseText);
}
});
})

Related

clear blade laravel for render new response ajax

I'm trying to use the same blade to return a response from ajax.
In my first controller function I return a view with data:
public function index()
{
$data = (object) array(
'title' => trans('web.blog_title'),
'description' => trans('web.blog_header_info'),
);
$posts = \DB::table('blogs')->paginate(3);
return view('web.blog')->with('data', $data)->with('posts', $posts);
}
But now I'm doing a search with ajax and I want to use the same blade template for the response.
My second function that should render my response is:
public function getLocalNews($restaurant_id) {
$data = (object) array(
'title' => trans('web.blog_title'),
'description' => trans('web.blog_header_info'),
);
$news = Blog::query()->where('restaurant_id', '=', $restaurant_id)->paginate(3);
return view('web.blog')->with('data', $data)->with('posts', $news);
}
but it doesn't do anything...
ajax:
$("#submit_btn_blog_res").on("click", function(e){
e.preventDefault();
var form = $('#searchRestaurant');
$(this).find('input').removeClass('is-invalid');
$(this).find('.error').html('');
$.ajax({
url: "blog/getLocalNews/" + $(".suggest-element").attr('id'),
data: form.serializeArray(),
type: 'GET',
dataType: form.data('type'),
success: function(data){
console.log(data);
$(".post-article").remove();
},
error: function(jqXHR){
var response = JSON.parse(jqXHR.responseText);
if (response.errors.name) {
$(form).find('input[name="name"]').addClass('is-invalid');
$(form).find('.name-error').html(response.errors.name);
} else if (response.errors.email) {
$(form).find('input[name="email"]').addClass('is-invalid');
$(form).find('.email-error').html(response.errors.email);
} else if (response.errors.phone) {
$(form).find('input[name="phone"]').addClass('is-invalid');
$(form).find('.phone-error').html(response.errors.phone);
} else if (response.errors.comments) {
$(form).find('input[name="comments"]').addClass('is-invalid');
$(form).find('.comments-error').html(response.errors.comments);
} else if (response.errors.gRecaptchaResponse) {
$(form).find('input[name="g-recaptcha-response"]').addClass('is-invalid');
$(form).find('.g-recaptcha-response-error').html(response.errors.gRecaptchaResponse);
}
}
});
}); //submit search form restaurant
You should pass your response with a content-type of application/json. Hopefully, laravel has a function as response() which do this for you.
public function getLocalNews($restaurant_id){
$data = (object) array(
'title' => trans('web.blog_title'),
'description' => trans('web.blog_header_info'),
);
$news = Blog::query()->where('restaurant_id', '=', $restaurant_id)->get();
$response_data = ['data'=>$data, 'posts'=>$news];
return response()->json($response_data, 200);
}
As said in laravel helpers functions doc First parameter of response() receives the data that you want to be included in the body. If you pass an array, it will be converted to json, and the second parameter is the http status code of the response.
Notice: If you want to send your results with pagination. You can use laravel api resource.
Update: Use your ajax to add new received data to your html.
success: function(response){
console.log(response);
$('#desired-element-for-data').html('');
$.each(response.data, function(item){
html1 += '<p>item</p>';
});
$('#desired-element-for-posts').html('');
$.each(response.posts, function(item){
html2 += '<p>item</p>';
});
$('#desired-element-for-data').html(html1);
$('#desired-element-for-posts').html(html2);
$(".post-article").remove();
},

how to retrive form.serialize() data in laravel controller

I use $("form").serialize() to submit form data. while I return value from a method it works fine. My method code is as below.
public function store(Request $request)
{
$list = #$request['lists'];
$total_amount = #$request->total_amount;
$r_g_amount = #$request->r_g_amount;
$type = #$request->type;
$cash = #$request->cash;
$credit = #$request->credit;
$bank = #$request->bank;
$from = #$request->from;
$to = #$request->to;
return $cash;
}
it sends me null value, if I return $request->formdata then it sends me all details of form. formdata is variable which I pass from ajax as formdata:$("form").serialize().
so how can I get values of form data into variable.
ajax request
$.ajax({
url: "{{ route('HK.store') }}",
data: {
lists: list, total_amount: total_amount, formdata : $("form").serialize(), "_token": "{{ csrf_token() }}"
},
type: "POST",
success: function (data) {
console.log(data);
}
});
enter code here
Use below code in your controller function of Laravel,
$box = $request->all();
$myValue= array();
parse_str($box['formdata'], $myValue);
print_r($myValue);
Hope it will help you!
You need to update your code like:
public function store(Request $request)
{
$list = $request->lists;
$total_amount = $request->total_amount;
$r_g_amount = $request->r_g_amount;
$type = $request->type;
$cash = $request->cash;
$credit = $request->credit;
$bank = $request->bank;
$from = $request->from;
$to = $request->to;
return response(['cash' => $cash]);
}
When you are using dynamic post data you have to be sure that variables exists. So here is an example how to get variables you need:
public function store(Request $request)
{
$data = $request->all();
$list = array_get($data, 'list', 'default value');
$total_amount = array_get($data, 'total_amount', 0);
...
return $whatever;
}
You can convert your serialized formData into Object first and then send it to your server:
const clientInfo= $('#checkoutForm').serialize();
const searchParams = new URLSearchParams(clientInfo);
clientInfo = Object.fromEntries(searchParams);// { 'type' => 'listing', 'page' => '2', 'rowCount' => '10' } 
And then in ajax request, pass the clientInfo to data property:
$.ajax({
url: ...,
method: "post",
data: clientInfo ,
success: function(){
}
})
In the Controller, when you dd the payload, it's gonna look like this:
array:6 [
"customer_name" => "Arely Torphy II"
"customer_email" => "lexi.kulas#jacobson.net"
"customer_phone" => "1-448-897-3923 x1937"
"address" => "1422 Ellie Stream Suite 859"
"post" => "37167"
"company_name" => "company"
]
Now, you can easily retrieve any data you'd like to.

Send Ajax data to Laravel controller

I am using fullcalendar, I need need to create a new event when user clicks on a specific date, I am using Laravel controller to store the data send by ajax request. I can create an event on calendar, but I cant send the data to controller and moreover browser tab freezes after creating the event. Anyone can correct where I am wrong? or provide better solution to the problem.
select: function(start, end, allDay) {
var title = event_name;// Event Title:
var eventData;
if (title) {
eventData = { //creates a new event on the calendar
title: title,
start: start,
end: end,
allDay: allDay
};
$('#calendar').fullCalendar('renderEvent', eventData, true); // stick? = true
$.ajax({
data:eventData,
type: 'POST',
url:"/projects/calendar/store", // your url
beforeSend: function (request) {
return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-token']").attr('content'));
},
success: function(response) {
console.log(response);
}
});
}
$('#calendar').fullCalendar('unselect');
},
This is my Route file, I have tried both get and post but none is working.
Route::get('/projects/calendar/store','FrontEndController#calendarStore');
This is the Controller, it will only process data sent by ajax request but no view.
public function calendarStore(Request $request)
{
$calendar = new Calendar;
Input::all();
$userId = Auth::user()->id;
$event_title =$request->input('title');
$start =$request->input('start');
$end =$request->input('end');
$calendar_event = Calendar::create([
'user_id' => $userId, // I can get the user ID
'project_id' => 2,
'event_title' => $event_title,
'start_date' =>$start,
'end_date' => $end
]);
}
replace your declaration of your ajax data parameter like this:
//creates a new event on the calendar
eventData = {
"title": title,
"start": start,
"end": end,
"allDay": allDay
};
I did the following modifications: and its working as Expected, once user click/selects on the specific day/day's it will ask for title and and save the event in database.
select: function(start, end, allDay) {
var title = prompt('Are u sure you want to apply for job? Yes/No:');// Event Title:
var start_time = moment(start).format();
var end_time = moment(end).format(); //onclick get date
var eventData;
if (title) {
eventData = {
title: title,
start: start,
end: end,
allDay: allDay
};
$('#calendar').fullCalendar('renderEvent', eventData, true); // stick? = true
$.ajax({
type: 'GET',//POST changed to GET
url: "/projects/calendar/store", // your url
data: { //event data from global variable
title: event_name,
start: start_time,
end: end_time,
event_id:event_id
},
beforeSend: function (request) {
return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-token']").attr('content'));
},
success: function(response) {
console.log(response);
}
});
}
$('#calendar').fullCalendar('unselect');
},
Updated Route
Route::get('/projects/calendar/store','FrontEndController#calendarStore');
Updated Controller
public function calendarStore(Request $request)
{
$userId = Auth::user()->id;
$event_title =$request->get('title');
$start =$request->input('start');
$end =$request->input('end');
$project_id= $request->input('event_id');
$calendar_event = Calendar::create([
'user_id' => $userId,
'project_id' => $project_id,
'event_title' => $event_title,
'start_date' =>$start,
'end_date' => $end
]);
return $calendar->all();
}

Passing a value from Controller to jQuery CodeIgniter

Straight to the case.
This is some functions from my model (Student Model):
public function get_exam_data($exam_id){
$this->db->select('exam_id, exam_name, duration');
$this->db->from('exams');
$this->db->where('exam_id', $exam_id);
$result = $this->db->get();
$exam = array();
$examrow = $result->row();
$exam['id'] = $examrow->exam_id;
$exam['name'] = $examrow->exam_name;
$exam['duration'] = $examrow->duration;
return $result;
}
public function start_exam($exam_id, $student_id)
{
$this->db->select('*');
$this->db->from('exam_record');
$exam_newstatus = array(
'student_id' => $student_id,
'exam_id' => $exam_id);
$this->db->set('start_time', 'NOW()', FALSE);
$this->db->insert('exam_record', $exam_newstatus);
//$examrecord_id is autoincrement in mysql exam_record table
$examrecord_id = $this->db->insert_id();
return $examrecord_id;
}
This is a function from the Student Controller:
public function get_student_exam_data()
{
$exam_id = $this->input->post('examId');
$examdata = $this->student_model->get_exam_data($exam_id);
$session = get_session_details();
if (isset($session->studentdetails) && !empty($session->studentdetails))
{
$loggeduser = (object)$session->studentdetails;
$examrecord_id = $this->student_model->start_exam($exam_id, $loggeduser->student_id);
}
echo json_encode($examdata);
}
This is how I access the $examdata value via Ajax:
jQuery(function()
{
$.ajax({
type : "POST",
url : "../get_exam_data/",
async : false,
data : {"examId": EXAM_ID },
success: function(response)
{
var data = $.parseJSON(response);
examId = data.id;
examName = data.name;
examDuration = data.duration;
}
});
}
I want to be able to pass $examrecord_id from the Student Controller to use it on my jQuery file, just like the $examdata.
I tried to use json_encode() twice on the Controller. Didn't work.
How do I pass $examrecord_id from the Controller to the jQuery file?
Can someone enlighten me, please? Thank you.
Add another index for your $examrecord_id
if (isset($session->studentdetails) && !empty($session->studentdetails))
{
$loggeduser = (object)$session->studentdetails;
$examrecord_id = $this->student_model->start_exam($exam_id, $loggeduser->student_id);
}
echo json_encode(array(
'examdata' => $examdata,
'examrecord_id' => (!empty($examrecord_id)?$examrecord_id:0)
));
Note the shorthand if condition to check if $examrecord_id is empty
Add a dataType option with 'json' as it's value. Then you can access the data
dataType : 'json',
success: function(response)
{
var data = response.examdata;
alert(response.examrecord_id); // your examrecord_id
examId = data.id;
examName = data.name;
examDuration = data.duration;
}

Full Calendar and CodeIgniter send Start and End date

I'm trying to get records by ajax request. I manage to get all the records from the table but now I want to send start and end date to controller to get only records from that interval.
What I have so far :
Script:
events: {
url: 'http://localhost/cms/calendar/get_calendar_ajax',
type: 'POST',
cache: true,
},
Controller:
public function get_calendar_ajax() {
$response = json_encode($this->Calendar_model->getRecords() );
echo $response;
}
Model:
public function getRecords() {
$data = $this->db->select()
->from('fullcalendar')
->get()->result();
return $data;
}
I have tried :
Controller :
$response = json_encode($this->Calendar_model->getRecords($_GET['start'], $_GET['end']) );
Model :
public function getRecords($start, $end) {
$data = $this->db->select()
->from('fullcalendar')
->where('start >=', $start)
->where('end <=', $end)
->get()->result();
return $data;
}
but with no luck ..
I manage to find the error:
from:
type: 'POST',
change to
type: 'GET',

Categories