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
Related
When I request different data than pressing select, it does not perform a single operation, and when they are combined, only one operation is performed,
It does a process called getStatesByCountryId but it doesn't call get_shipping_price, and because I'm requesting information from two different tables I can't merge them,
And when we merge them, the information is not sent to the span text, so I preferred to separate them,
I using a php codeigniter framework
javascript code:
$("select[name='country']").change(function () {
var countryId = $(this).val();
$.ajax({
url: "/Ajax/getStatesByCountryId",
method: "post",
data: { countryId },
success: function (data) {
var rJson = $.parseJSON(data);
if (rJson.status === true) {
$("select[name='state']").html("");
$.each(rJson.data, function (e, v) {
$("select[name='state']").append(
"<option value='" + v.id + "'>" + v.name + "</option>"
);
});
} else {
$("select[name='state']").html("");
}
}
});
});
$("select[name='country']").change(function () {
var countryname = $(this).val();
$.ajax({
url: "/Ajax/get_shipping_price",
method: "post",
data: { 'countryname': countryname },
success: function (data2) {
if (data2) {
$("span[name='shipping_price']").text(data2.shipping_price);
} else {
$("span[name='shipping_price']").text("");
}
}
});
});
Ajax Code:
public function get_shipping_price()
{
$countryName = $this->request->getPost("countryname");
$result = $this->con->query("SELECT shipping_price FROM table2 WHERE country = '{$countryName}'")->getResult();
if ($result) {
$data2 = array('shipping_price' => $result[0]->shipping_price);
} else {
$data2 = array('shipping_price' => 0);
}
echo json_encode($data2);
}
public function getStatesByCountryId()
{
$countryId = $this->request->getPost("countryId");
$states = $this->con->query("select * from table where ID = {$countryId}")->getResult();
if ($states) {
$data = [
"status" => true,
"data" => $states
];
} else {
$data = [
"status" => false
];
}
echo json_encode($data);
}
and here respon:
I'm having trouble figuring out the best approach to checking if a record exists while using an ajax. If the CNIC exists, I want to alert, "user already exists". If it doesn't exist, I want it to insert the form data into the database. I've got the jquery function that only submits data using ajax but I want to validate CNIC if it exists it gives an alert message. Any help would be appreciated. Thanks in advance.
**
jquery
**
$(document).ready(function() {
$("#save1").on('click', function(e) {
var cnic = $("#cnic").val();
if (cnic == '') {
alert("Kindly Enter CNIC");
return false;
}
var gender = $("#gender").val();
if (gender == '') {
alert("Kindly Enter Gender");
return false;
}
var contactno = $("#contactno").val();
if (contactno == '') {
alert("Kindly Enter Contact No");
return false;
}
var fname = $("#fname").val();
if (fname == '') {
alert("Kindly Enter Contact No");
return false;
}else{
$.ajax({
url: "/save",
type: "get",
data: $('#registrationform').serialize(),
dataType: 'json',
success: function(data) {
$("#patientid").val(data.patientid);
// console.log(data);
}
})
}
});
});
**
controller
**
<?php
namespace App\Http\Controllers;
use Haruncpi\LaravelIdGenerator\IdGenerator;
use Illuminate\Http\Request;
use App\Helpers\Helper;
use Illuminate\Support\Facades\DB;
use App\User;
use App\Models\patient;
use Illuminate\Support\Facades\Validator;
class Helpercontroller extends Controller
{
function save(Request $request)
{
$temppatientId = IdGenerator::generate(['table' => 'patients', 'length' => 5, 'prefix' =>
'22']);
$patientid = $temppatientId + 1;
$query = new patient;
$query->patientid = $patientid;
$query->fname = $fname;
$query->lname = $lname;
$query->cnic = $cnic;
$query->contactno = $contactno;
$query->gender = $gender;
$query->age = $age;
$query->dob = $dob;
$query->city = $city;
$query->address = $address;
$query->husbandname = $husbandname;
$query->fathername = $fathername;
$query->bloodgroup = $bloodgroup;
$query->maritalstatus = $maritalstatus;
$query->save();
return $query;
}
Quick way to do it is to use Validation from Laravel.
public function save(Request $request)
{
$validator = \Validator::make($request->all(), [
// I suppose your table name is 'patients'
'cnic' => 'required|unique:patients',
]);
if ($validator->fails()) {
// you can return a custom message if needed
return response()->json(['success' => false, 'errors' => $validator->errors()->all()]);
}
// ... your actuel code to save data
return response()->json(['success' => true, 'patient' => $query]);
}
And in your Ajax call:
$.ajax({
url: "/save",
type: "get",
data: $('#registrationform').serialize(),
dataType: 'json',
success: function(data) {
if (data.success === false) {
alert('User already exist !');
} else {
$("#patientid").val(data.patient.patientid);
// console.log(data.patient);
}
}
})
Respect cases of variables and don't use a GET method to POST a resource.
I just can't get my head around this, I'm probably just missing it but let me know if you can help.
Issue: It's stating that the User is a member, even though they are not.
For example if the user is not in the User Auth table, it should display "Not a Member" where if the user is in the table it should display "Member"
Issue
Table Structure :
user_auth table :
This is the Js that is executed on all pages
function GetUserinfo(token)
{
var info = { Token: token };
$.ajax({
type: "POST",
url: "http://localhost/Api/CurrentUser",
data: JSON.stringify(info),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$(".account .user").html(data.Username);
if(data.Member == 0)
{
$(".account .status").html("<p style=\"color:red;\">Not a member</p>");
} else {
$(".account .status").html("<p style=\"color:green;\">Member</p>");
}
},
error: function(xhr, status, error) {
var err = JSON.parse(xhr.responseText);
console.log(xhr);
}
});
}
Rest API
` elseif($parameter == "CurrentUser") {
$params = $this->dataStream();
$user = new User(null, $params['Token']);
echo '{ "Username":"' . htmlspecialchars($user->fetch("username")) . '", "Member": ' . $user->hasMembership() . ' }';
http_response_code(200);
}
}`
Here is the hasMembership function
public function hasMembership()
{
$uid = $this->fetch("uid");
$this->queryObj->Execute("SELECT * FROM user_auth WHERE uid=:uid ", "prepare", array($uid), 0);
return ($this->queryObj->rows >= 1);
}
Any help will be greatly appreciated, thank you.
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;
}
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;