Infinite scroll in Symfony using Ajax - javascript

I wanted to show products from db using infinite scroll.
Here is my Controller:
$start=0;
$limit= 6;
$query = $repository->createQueryBuilder('classified')
->join('classified.statusId','status')
->andWhere('status.name=:status')
->setParameter('status','active')
->setFirstResult($start)
->setMaxResults($limit)
->getQuery();
$results = $query->getResult();
if ($request->isXmlHttpRequest()){
$list = $this->renderView('search-result.html.twig', [
'results' => $results
]);
$response = new JsonResponse();
$response->setData(array('classifiedList' => $list));
return $response;
}
Ajax:
$(window).scroll(function () {
if($(window).scrollTop() + $(window).height()>= $(document).height()){
getmoredata();
}
})
function getmoredata() {
$.ajax({
type: "GET",
url: "{{ path('classified_list', {'type' : 'all'}) }}",
dataType: "json",
cache: false,
success: function (response) {
$('.card-deck').append(response.classifiedList);
$('#spinner').hide();
console.log(response);
},
error: function (response) {
console.log(response);
}
});
}
So now what is happening is the first 6 results is repeatedly showing when the scrolling is triggered. I know this is not correct and I don't expect this to work properly. But what I don't know is what is the next step.
So do I need to add paginator or something?
Any help would be appreciated,Thanks!

You need to track whether your ajax is requesting or not, so it will not do request multiple times when window reach the scroll limit. Also, you need to track the offset and whether you have more data to loads. e.g
window.__isFetching = false;
window.__offset = 0;
window.__hasMoreData = true;
$(window).scroll(function () {
if($(window).scrollTop() + $(window).height()>= $(document).height()){
if(!window.__isFetching && window.__hasMoreData) {
getmoredata();
}
}
})
function getmoredata() {
window.__isFetching = true;
$.ajax({
type: "GET",
// NOTE, you can pass current offset here in url
url: "{{ path('classified_list', {'type' : 'all', }) }}"+"&offset="+window.__offset,
dataType: "json",
cache: false,
success: function (response) {
$('.card-deck').append(response.classifiedList);
$('#spinner').hide();
console.log(response);
// Note that here, server side response must have next offset and hasMoreData attribut.
window.__isFetching = false;
window.__hasMoreData = response.hasMoreData;
window.__offset = response.offset
},
error: function (response) {
console.log(response);
}
});
}
in server side , which is symfony, you might want to do something like:
// Get offset from request query
$start= $request->query->get('offset');
$limit= 6;
$query = $repository->createQueryBuilder('classified')
->join('classified.statusId','status')
->andWhere('status.name=:status')
->setParameter('status','active')
->setFirstResult($start)
->setMaxResults($limit)
->getQuery();
$results = $query->getResult();
if ($request->isXmlHttpRequest()){
$list = $this->renderView('search-result.html.twig', [
'results' => $results
]);
$response = new JsonResponse();
// And add offset and hasMoreData fields in response
$response->setData(array(
'classifiedList' => $list,
'offset' => $start += 1
'hasMoreData' => count($list) < ($limit * &start)
)
);
return $response;

Related

pagination automatically sending multiple requests with laravel

hello guys recently I am developing a new website which have multiple filters so I use the session-based filter with laravel
it is working fine if I use only the Show filter one time but when I switch to another filter, it is sending multiple requests(as much time I repeat the filter)
when someone clicks the filter this code will run
<------- Laravel route where I am sending a request it returns me a HTML file and I am rendering in my div tag where I have all lists ------->
public function filter(Request $request){
$course = Course::query();
if (isset($request->show)) {
Session::put('show',$request->show);
$show = $request->show;
}
if(isset($request->type)){
$course->where('type',$request->type);
}
if (isset($request->ratting)) {
$course->where('ratting','>=',$request->ratting);
Session::put('ratting',$request->ratting);
}
if(isset($request->short_type))
{
$type = $request->short_type;
$course = $this->checkSort($course,$type);
Session::put('short',$type);
}
if (Session::has('search')) {
$search = Session::get('search');
$course->where(function($q) use ($search){
$q->where('title', 'LIKE', '%'.$search.'%')
->orWhere('slug', 'LIKE', '%'.$search.'%')
->orWhere('description', 'LIKE', '%'.$search.'%')
->orWhere('keyword', 'LIKE', '%'.$search.'%');
});
}
if(Session::has('show') && !isset($request->show)){
$show = Session::get('show');
}
if(Session::has('ratting') && !isset($request->ratting)){
$course->where('ratting','>=',Session::get('ratting'));
}
if(Session::has('short') && !isset($request->short)){
$type = Session::get('short');
$course = $this->checkSort($course,$type);
}
$course->select('id', 'title', 'slug', 'description', 'created_at', 'regular_price', 'sell_price', 'thumbnail','ratting','status');
return view('site.courses.ajax-listing',[
'active' => 'courses',
'type' => $request->type,
'courses' => $course->where('status',1)->paginate(isset($show) ? $show : 10),
]);
}
public function checkSort($courses,$type){
if($type == "alphabetically_a_z")
{
$courses->orderBy('title', 'ASC');
}
if($type == "alphabetically_z_a")
{
$courses->orderBy('title', 'DESC');
}
if($type == "date_new_to_old")
{
$courses->orderBy('created_at', 'ASC');
}
if($type == "date_old_to_new")
{
$courses->orderBy('created_at', 'DESC');
}
if($type == "popular")
{
$courses->where('is_popular', 1);
}
return $courses;
}
<------------------------------------------->
In the search input have route where i will send request
<input type="text" hidden id="search-url" value="{{route('ajax-search-course')}}">
<--------- Javascript Code ----->
$(document).ready(function(){
var url = "{{route('ajax-search-course')}}";
var Jobtype = "1";
var value;
$("input[name='RattingRadioDefault']:radio").change(function(){
value = $("[name=RattingRadioDefault]:checked").val();
ajaxFilter(url + "?ratting="+value+ "&type=" + Jobtype);
});
$("input[name='ShowingRadioDefault']:radio").change(function(){
value = $("[name=ShowingRadioDefault]:checked").val();
ajaxFilter(url + "?show=" + value + "&type=" + Jobtype);
});
$("input[name='ShortingRadioDefault']:radio").change(function(){
value = $("[name=ShortingRadioDefault]:checked").val();
console.log("this is value",value,$("[name=ShortingRadioDefault]:checked").val());
ajaxFilter(url + "?short_type=" + value + "&type=" + Jobtype);
});
});
function ajaxFilter(url, data = null) {
//Add Preloader
$('#listing-data').hide();
$('#loading-area').show();
$.ajax({
method: 'GET',
url: url,
data: data,
contentType: "application/json; charset=utf-8",
success: function(data) {
// console.log("this is return data",data);
$('#listing-data').html(data);
$('#loading-area').hide();
$('#listing-data').show();
},
error: function(jqXhr, textStatus, errorMessage) {
// error callback
$('#listing-data').hide();
$('#loading-area').show();
console.log("this is error", errorMessage);
}
});
}
<------------- Javascript pagination page ----------->
//Ajax Paginatio
$(document).one('click', '#ajaxPagination ul li a', function (e) {
console.log("ajax pagination function is running",$(this).attr("href"),"and",$(e).attr("href"));
e.preventDefault();
//Add Preloader
$('#listing-data').hide();
$('#loading-area').show();
var url = $(this).attr("href")+"&"+ "type=" + $('#data_sort_filter').attr('job-type'),
data = '';
e.preventDefault();
$.ajax({
method: 'GET',
url: url,
data: data,
contentType: "application/json; charset=utf-8",
success: function (data) {
$('#listing-data').html(data);
$('#loading-area').hide();
$('#listing-data').show();
},
error: function (jqXhr, textStatus, errorMessage) {
// error callback
$('#listing-data').hide();
$('#loading-area').show();
}
});
});
i was trying to add a multiple filters system with the session. now i have this error pagination function running as much i am repeating filters i want to solve this please help me it is a very important to project for me

CodeIgniter Ajax call

ajax call does not hit to controllers function, what is the reason and why I am not understanding kindly guide me
I am trying to send ajax call to controller update the record this is my ajax code
$(document).ready(function() {
$(".update").click(function(event) {
debugger;
event.preventDefault();
var vehno = $("input#vn").val();
var vbrand = $("input#vb").val();
var vmodel = $("input#vm").val();
var vcolor = $("input#vcol").val();
debugger;
$.ajax({
type: "ajax",
method:"Post",
url:'<?php echo base_url('index.php/vehicleCtrl/FunUpdate')?>',
//async:false,
dataType: 'json',
data: {vehicle: vehno, brand: vbrand, vmodel:vmodel,vcolor:vcolor},
success: function(res) {
alert("working");
// if (res)
// {
// // Show Entered Value
// jQuery("div#result").show();
// jQuery("div#value").html(res.username);
// jQuery("div#value_pwd").html(res.pwd);
// }
},
error:function(res){
alert(res);
}
});
});
});
this Controller's Function
this is a codeigniter controller
public function FunUpdate()
{
$as= $this->input->post('vehicle');
$id=-1;
$vehicleArray = array('vehicleNo' => $this->input->post('vehicle'),
'Brand' => $this->input->post('brand'),
'Model' => $this->input->post('vmodel'),
'Color' => $this->input->post('vcolor'),
);
echo json_encode($vehicleArray);
$Result=$this->VehicleModel->Update($vehicleArray,$no);
if($Result)
{
$data= array('error' =>'Vehicle Update Successful');
$data["DetailList"]=$this->VehicleModel->FunDetailSearch($no);
$data["EditTrack"]=$this->VehicleModel->EditTrackDetail($id);
$data["NewVehicle"]=$this->VehicleModel->FunfindVehicle($no);
$this->load->view('Layout/header');
$this->load->view('vehicle/create',$data);
$this->load->view('Layout/footer');
}
}
ajax request should look like this
$('#buttonid').click(function(){
var vehno = document.getElementById('vehno').value;
var brand = document.getElementById('brand').value;
$.ajax({
url:'<?=base_url()?>index.php/Controller/function',
method: 'post',
data: {vehno: vehno, brand: brand},
dataType: 'json',
success: function(response){
alert('data updated');
}
});
});
function
public function updateDetails(){
// POST data
$postData = $this->input->post();
//load model
$this->load->model('Main_model');
// get data
$data = $this->Main_model->updateVehicle($postData);
echo json_encode($data);
}
Modal
function updateVehicle($postData){
$response = array();
if($postData['id'] ){
$this->db->where('id',$postData['id']);
return $this->db->update('vehicle',$postData);
}
Hope Now You Update Your Data With Ajax

Not able to display the JSON success output in the view or alert

I am using CodeIgniter, I have a three input field called as name, emp_id,crm_id. I am entering the id value and sending to the controller to get all the information related to that id using AJAX an JSON. Now the issue is, I am getting the correct output in the network tab but not able to display in the view page even alert is also not displaying in the JSON.
Sometimes I am getting below error because of JSON is empty
[Show/hide message details.] SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
I think there is some issue with JSON.
Ajax
$("form[name='search_addSalaryrecord']").validate({
// errorElement: 'div',
submitHandler: function(form) {
//alert(baseUrl);
var employee_name = $('#employee_name').val();
var crm_id = $('#crm_id').val();
var employee_id = $('#employee_id').val();
$.ajax({
url: baseUrl + "/Employee_control/search_addSalaryrecord",
method: "POST",
dataType: "json",
data: {employee_name: employee_name,crm_id:crm_id,employee_id:employee_id},
success: function(response) {
//$('.search_record tbody').html(response);
// var data = JSON.parse(response);
//alert(data.status);
if (response.status === 'error')
{
alert(response.msg);
}
if (response.status === 'success') {
//alert('data avaliable');
alert(response.records);
console.log(response.records);
}
}
//error: function(error) { console.log(error); }
});
}
});
Controller
public function search_addSalaryrecord()
{
$employee_name=trim($this->input->post('employee_name'));
$emp_crmid=trim($this->input->post('crm_id'));
$employee_id=trim($this->input->post('employee_id'));
if((!empty($employee_name)) ||(!empty($emp_crmid)) || (!empty($employee_id))){
$arr_result =$this->Employee_model->get_salary_search_emp_id($employee_name,$emp_crmid,$employee_id);
if (!empty($arr_result)){
foreach ($arr_result as $row)
{
$result[] = array(
"name" => $row->firstname.' '.$row->lastname,
"mobileno" => $row->mobileno,
"email_id" => $row->email_id,
"employee_id" => $row->employee_id,
"month_year" => $row->month.' '.$row->year
);
}
//print_r($result);
$respnonse['status'] = 'success';
$respnonse['records'] = $result;
}
else
{
$respnonse['status'] = "error";
$respnonse['records'] = "No record found";
}
}
echo json_encode($arr_result);
exit;
}
Hope this will help you :
Use dataType: "json" in your ajax to avoid further parsing of response and return json_encode data with exit from your controller
Your ajax should be like this :
$("form[name='search_record']").validate({
submitHandler: function(form)
{
var employee_id = $('#employee_id').val();
$.ajax({
url: baseUrl + "/Employee_control/search_addSalaryrecord",
method: "POST",
dataType: "json",
data: {employee_id:employee_id},
success: function(response) {
//alert(data.status);
if (response.status == 'error')
{
alert(response.msg);
$('.personel_info').empty();
}
if (response.status == 'success')
{
alert(response.records);
$('.personel_info').empty();
$('.personel_info').show();
var trHTML = '';
$.each(data.records, function (i, o){
$('#name_emp').text(o.name);
$('#mobileno_emp').text(o.mobileno);
$('#employee_email').text(o.employee_email);
});
}
}
});
}
});
Your controller's method search_addSalaryrecord should be like this :
public function search_addSalaryrecord()
{
$employee_id = trim($this->input->post('employee_id'));
if(!empty($employee_id))
{
$arr_result = $this->Employee_model->get_salary_search_emp_id($employee_id);
if (! empty($arr_result))
{
foreach ($arr_result as $row)
{
$result[] = array(
"name" => $row->firstname.' '.$row->lastname,
"mobileno" => $row->mobileno,
"email_id" => $row->email_id,
);
}
$respnonse['status'] = 'success';
$respnonse['records'] = $result;
}
else
{
$respnonse['status'] = "error";
$respnonse['records'] = "No record found";
}
}
echo json_encode($respnonse);
exit;
}

AJAX if JSON-response = X -> do action

I am working on a site and now I am at the point that I have to make the AJAX-forms. The code I have now does insert the params in the database, but now I get stuck at the following point. I want my code to hide the form after the status of JSON is success. Working in a MVC. This is my code:
(I have let the unimportant part of the code away)
AJAX:
$("#submitAssignment").on("click", function () {
$.ajax({
type: "POST",
url: "/set/new/ass",
async: true,
data: data,
success: function (data) {
console.log("Het item is toegevoegd");
var err = jQuery.parseJSON(data);
sendAlert.createAlert(err.return, err.type);
if (jsonObj.status == 'success') {
$("#submitAssignment").hide();
}
}
});
});
Controller:
else {
$UserModel = new UserModel();
if ($UserModel->placeAssignment($title, $uploadable, $level, $points, $description)) {
$err['data'] = array("status" => "success", "type" => "success", "return" => "De opdracht is toegevoegd! Joepie :D" );
} else {
$err['data'] = array("status" => "failed", "type" => "danger", "return" => "Er is iets misgegaan!");
}
}
exit( $err['endpoint'] = json_encode( $err['data'], $options = 0 ) );
The part I want to hide after status = succes, does not hide, so thats my problem. I have searched other questions, but aint got success with that. What am I doing wrong in this case?
The problem in this case is that I used the wrong call-back in the ajax-code. I used JSONobj.status, but it need to be: err.status because I am handling it at that way. #timothyGroote gave this answer and now it works.
My ajax-code now:
$.ajax({
type: "POST",
url: "/set/new/ass",
async: true,
data: data,
success: function (data) {
console.log("Het item is toegevoegd");
var err = jQuery.parseJSON(data);
sendAlert.createAlert(err.return, err.type);
if (err.status == 'success') {
$("#submitAssignment").hide();
}
}
});

Passing custom error code to ajax error function

I'm trying to pass custom error code to the client-side to ajax error function.
In the server side:
$response = array();
if ( empty($post['parent_id']) ) {
$response = array('error' => true, 'status_code' => -2);
exit();
}
$is_valid_id = RC()->is_valid_id($post['parent_id']);
$row = RC()->get_row_data($post['parent_id']);
if ( ! $is_valid_id ) {
$response = array('error' => true, 'status_code' => -1);
} else if ( ! $row ) {
$response = array('error' => true, 'status_code' => 0);
} else {
$response = json_encode($row);
}
echo $response;
Then I want to check for this status code in my js script, but couldn't find a way to do this (found ways only without trigger the error event).
$.ajax({
url: ajax_url,
data: {
'action': 'rc_parent_sign_in',
'form_data': $('#parent-sign-in-form').serialize(),
'security': security_nonce
},
type: "post",
dataType: "json",
cache: false,
success: function (response) {
var query_vars = $.param(response);
window.location.replace('http://localhost/renecassin/user-registration/?' + query_vars);
},
error: function (response) {
$('.form-control-feedback').addClass('hide');
/* Looking for something like this */
switch ( response.status_code) {
case -2 :
parent_id_form_group.addClass('has-danger').children('#empty-field').
removeClass('hide');
prent_id_input.addClass('form-control-danger');
break;
case -1 :
parent_id_form_group.addClass('has-danger').children('#not-valid-id-feedback').
removeClass('hide');
prent_id_input.addClass('form-control-danger');
break;
default :
parent_id_form_group.addClass('has-danger').children('#id-not-exists-feedback').
removeClass('hide');
prent_id_input.addClass('form-control-danger');
}
}
});
Any help will be appreciate.
It's because the response will go to your response callback, you are successfully returning an object.
The error callback will only be called if the request itself failed (timeout,404 etc..)
You need to handle your internal error codes in your success callback

Categories