I have a problem with ajax search in my codeigniter project.
The search no show data, and after click SEARCH button page freez 1-2 sec. I think the problem is anywhere in getting the information from the database but, also the model is correct.
There is the code:
Model:
var $table = 'users';
function search($options = array(), $status = true, $limit = null, $offset = 0) {
$this->db->select('users.username,types.t_title,media.photo');
$str = '';
if ($options['username'] != '') {
$str .= ' AND users.username =' . $this->db->escape($options['username']);
}
if (!$status) {
$str .= ' AND users.active = 1';
}
$this->db->where('users.username', 'LIKE', '%' . $options['username'] . '%' . $str);
$this->db->group_by('users.id');
$this->db->limit($limit, $offset);
$search = $this->db->get($this->table);
return $search->result();
}
Controller:
public function search($offset = 0) {
$options = $this->Users->array_from_post(array('username'));
if ($this->form_validation->run('search')) {
$count = $this->Property->search($options, $status = FALSE);
$perpage = 10;
if (count($count) > $perpage) {
$config['base_url'] = site_url('welcome/search');
$config['total_rows'] = count($count);
$config['per_page'] = $perpage;
$config['uri_segment'] = 4;
$q = $this->pagination->initialize($config);
$offset = ($this->uri->segment(4)) ? $this->uri->segment(4) : 0;
} else {
$this->data['pagination'] = '';
$offset = 0;
}
$status = 1;
$this->data['search'] = $this->Users->search($options, $status = FALSE, $perpage, $offset);
$this->load_search('search');
}
}
And View with ajax:
<script type="text/javascript">
$(document).ready(function() {
$("form[name='search']").submit(function(e) {
var formData = new FormData($(this)[0]);
$.ajax({
url: "<?php echo site_url('welcome/welcome/search'); ?>",
type: "POST",
dataType: "text",
data: formData,
async: false,
success: function (msg) {
$(".search_area").html(msg);
},
cache: false,
contentType: false,
processData: false
});
e.preventDefault();
});
});
</script>
<form class="form-horizontal" method="post" name="search">
<div class="row">
<div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">
<div class="form-group">
<div class="col-md-12">
<input type="text" class="input-text" id="username" name="username" placeholder="Username">
</div>
</div>
</div>
<div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">
<div class="form-group">
<input type="submit" class="search-button" name="search" value="Search">
</div>
</div>
</div>
</form>
<div class="search_area">
</div>
All is connected and load the template, but the only message with No Record Found
And here is search view:
<div class="main-title">
<h1>Search Results</h1>
<div class="border">
<div class="border-inner"></div>
</div>
</div>
<?php if ($search) : ?>
<?php foreach ($search as $sr): ?>
<p>Tralalala <?php echo $sr['title']; ?></p>
<?php endforeach; ?>
<?php else:?>
<div class="notification-box">
<h3><?php echo $this->lang->line('no_record'); ?></h3>
</div>
<?php endif; ?>
Related
I have created a Leaderboard for my quiz and have a custom Wordpress table where I use $wpdb->get_results.
In the leaderboard I want to display the "score", "medal" and "display_name".
I'm trying to use AJAX to loop through the arrays and display it into the leaderboard like pagination to show users results(scores).
Below is what I have so far.
Leaderboard(with script:)
<div id="result" class='row col-12' style='padding-top: 90px; '>
<div class='card-group'>
<div class='card'>
<div class='card-body'>
<h5 class='card-title bg-info text-white'>Weekly Leaderboard</h5>
<div id="leader_board">
<?php for ($i = 0; $i <= count($display_result); $i++) { ?>
<div class="card-text-page" id="card-text-page1">
<div class='card-text border'>
<div class='leader-detail'>
<div class='leader-username'>
<?= $display_result[$i]['display_name']; ?>
</div>
<div class='leader-score'>
<p><?= $display_result[$i]['score'] ?>%</p>
</div>
</div>
<div class='leader-medal'>
<?= $display_result[$i]['medal'] ?>
</div>
</div>
</div>
<?php } ?>
<div id="tota_page_div">
<?php
for ($i = 1; $i <= $currentPage; $i++) {
echo "<input type='button' value='" . $i . "' onclick='get_data(" . $i . ")'>";
}
?>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
function get_data(no) {
$.ajax({
type: 'post',
url: '/quiz.php',
data: {
row_no: no
},
success: function(response) {
document.getElementById("card-text-page1").innerHTML = response;
}
});
}
});
</script>
<?php endif; ?>
Insert and request from DB
//Insert into database
global $wpdb, $current_user;
wp_get_current_user();
if (isset($_POST['submit'])) {
$data_total = array(
'score' => $_POST['totalscore'],
'finish_time' => $_POST['countdown'],
'medal' => $_POST['medal'],
'insert_date' => date('Y-m-d'),
'display_name' => $current_user->display_name
);
$table_name = 'wp_quiz';
$wpdb->insert($table_name, $data_total, $format = NULL);
}
//set pages for pagination
if (isset($_GET["page"])) {
$page = $_GET["page"];
} else {
$page = 1;
};
$limit = 4;
$start = ($page - 1) * $limit;
//Request from database
$get_result = $wpdb->get_results(
"select *
from
wp_quiz
order by
score desc
limit $start, $limit
"
);
$get_result1 = $wpdb->get_results(
"select
count(id)
as
id
from
wp_quiz
"
);
//change object into array
$display_result = json_decode(json_encode($get_result), true);
$display_result1 = json_decode(json_encode($get_result1), true);
$total_result = $display_result1[0]['id'];
$currentPage = ceil($total_result / $limit);
All the questions in the quiz are on the same page and the result page shows at the end with all the user's scores.
I just can't get this to work.
Any help will be much appreciated. Let me know if you need more information.
I am about to make a note system in procedural PHP and AJAX, which should allow me to both display new notes without refreshing and to load more notes without refreshing.
In my current case both works, but not together. If no notes to show from the database, then my site will display a text saying "There is no notes to display". If I then make a note, it still won't display the note, until I load it in via a click on the loading notes button.
I've tried to add in following to my success function:
if(res.indexOf("success")!=-1) {
location.reload(true);
}
Without any luck, even I could read on the internet, that it somehow worked out for other people.
Here is my ajax functions:
$(document).ready(function() {
var noteCount = 2;
$("#loadMore").click(function() {
noteCount = noteCount + 2;
$("#notes").load("load-notes.php", {
noteNewCount: noteCount
});
});
$("#noteform").on("submit", function(event) {
event.preventDefault();
noteCount = noteCount + 1;
var form_data = $(this).serialize();
$.ajax({
url: "add-notes.php",
method: "POST",
noteNewCount: noteCount,
data: form_data,
dataType: "JSON",
success: function(data) {
if(res.indexOf("success")!=-1) {
location.reload(true);
}
}
});
});
});
My add-notes.php
<?php
session_start();
require_once "../inc/core/config.php";
if ($_SERVER['REQUEST_METHOD'] != 'POST') exit;
$subject = mysqli_real_escape_string($dbconn, $_POST['subject']);
$note = mysqli_real_escape_string($dbconn, $_POST['note']);
$my_date = date("Y-m-d H:i:s");
$author = $_SESSION['u_firstname'];
$noteNewCount = $_POST['noteNewCount'];
$sql = "INSERT INTO notes(author, subject, note, created_at) VALUES ('$author', '$subject', '$note', '$my_date')";
mysqli_query($dbconn, $sql);
$sql = "SELECT * FROM notes LIMIT $noteNewCount";
$result = mysqli_query($dbconn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<div class="note">
<div class="noteHead">
<div class="row">
<div class="col-md-8">
<h3>' . $row["subject"] . '</h3>
</div>
<div class="col-md-4">
<p class="text-muted">Note created by ' . $row["author"] . '</p>
</div>
</div>
</div>
<div class="noteContent">
<div class="row">
<div class="col-12">
<p>' . $row["note"] . '</p>
</div>
</div>
</div>
<div class="noteFooter">
<div class="row">
<div class="col-12">
<p class="text-muted">Created ' . $row["created_at"] . '</p>
</div>
</div>
</div>
</div>';
}
} else {
echo "No comments yet...";
}
The note div where my notes are displayed and the form where they are created:
<form id="noteform" action="add-notes.php" method="POST" >
<div class="form-group">
<label for="usr">Titel:</label>
<input type="text" class="form-control" name="subject">
</div>
<div class="form-group">
<label for="pwd">Note:</label>
<textarea class="form-control" rows="5" name="note"></textarea>
</div>
<button class="btn btn-outline-success my-2 my-sm-0" name="submit" type="submit">Opret note</button>
</form>
<div id="notes">
<?php
$sql = "SELECT * FROM notes LIMIT 2";
$result = mysqli_query($dbconn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<div class="note">
<div class="noteHead">
<div class="row">
<div class="col-md-8">
<h3>' . $row["subject"] . '</h3>
</div>
<div class="col-md-4">
<p class="text-muted">Note created by ' . $row["author"] . '</p>
</div>
</div>
</div>
<div class="noteContent">
<div class="row">
<div class="col-12">
<p>' . $row["note"] . '</p>
</div>
</div>
</div>
<div class="noteFooter">
<div class="row">
<div class="col-12">
<p class="text-muted">Created ' . $row["created_at"] . '</p>
</div>
</div>
</div>
</div>';
}
} else {
echo "No comments yet...";
}
?>
</div>
So to sum up, I am looking for a way to display a new note made, without having to load it in via my load button. What can I do?
Instead of location.reload, you can just replace the HTML in #notes. Also, in add-notes.php you are echoing HTML but in your ajax, you are expecting dataType: json. Also, not sure what is noteNewCount being passed to AJAX.
$.ajax({
url: "add-notes.php",
method: "POST",
data: form_data,
success: function(data) {
$("#notes").html(data);
}
});
I want to make custom search page where I can filter results as shown in the screenshot below:
Currently my problem is that all the items of the list are coming in a single category while I want a grouped view according to different categories e.g. "Device Features", "Mobile Phone Operating System", etc. So far I've written below piece of PHP code:
<?php
$listCategories = get_categories();
if(isset($listCategories) && !empty($listCategories)){
?>
<div class="list-section">
<h3 class="list-heading">Topics</h3>
<ul id="post-grid">
<?php
foreach($listCategories as $categories){
$total_post = get_posts(array('post_type'=>'post', 'category'=>$categories->term_id, 'posts_per_page'=>'-1'));
$total_post = count($total_post);
?>
<li>
<div class="checkbox">
<input type="checkbox" id="cat<?php echo $categories->term_id; ?>" data-tax="category" data-name="<?php echo $categories->name; ?>" class="category_check" value="<?php echo $categories->term_id; ?>">
<label class="css-label" for="cat<?php echo $categories->term_id; ?>">
<span class="filter-name"><?php echo $categories->name; ?></span>
<span class="filter-count"><?php echo $total_post; ?></span>
<i class="icon fa fa-check"></i>
</label>
</div>
</li>
<?php } ?>
</ul>
</div>
<?php } ?>
I've created my own custom plugin for searching and filtering the search result.
1. Plugin file (index.php)
<?php
/*
Plugin Name: Search and Filter
Plugin URI: http://wordpress.org
Description: Search and Filter
Author: Naveen
Version: 1.0
*/
class SearchAndFilter{
public function __construct()
{
add_action('wp_enqueue_scripts', array($this, 'AddScript'));
add_action('wp_ajax_affordance_search_data' , array($this, 'AffordanceSearchData'));
add_action('wp_ajax_noprev_affordance_search_data' , array($this, 'AffordanceSearchData'));
add_action('wp_ajax_affordance_search_page_data' , array($this, 'AffordanceSearchPageData'));
add_action('wp_ajax_noprev_affordance_search_page_data' , array($this, 'AffordanceSearchPageData'));
add_shortcode('Search', array($this, 'CreateShortcode'));
}
public function AddScript()
{
wp_enqueue_script('saf-app', plugin_dir_url(__FILE__) . '/js/app.js', array('jquery'));
wp_localize_script('saf-app', 'my_ajax_object', array('ajaxurl' => admin_url('admin-ajax.php')));
}
function CreateShortcode($atts)
{
ob_start();
$keyword = $_REQUEST['s'];
?>
<form action="<?php echo home_url('/'); ?>" method="get">
<input type="text" name="s" id="search_keyword" value="<?php echo $keyword; ?>" class="form-control search-input" placeholder="Search..." />
</form>
<div class="search-suggestion"></div>
<?php
$output = ob_get_clean();
return $output;
}
// search autocomplete
function AffordanceSearchData()
{
$args = array('post_type'=>array('post'),'status'=>'publish');
$output = '';
$output = '<ul class="grid effect-3" id="grid">';
if(isset($_POST['keyword']) && !empty($_POST['keyword']))
{
$args['s'] = $_POST['keyword'];
}
$wpPosts = new WP_Query($args);
if($wpPosts->have_posts()) :
while($wpPosts->have_posts()) :
$wpPosts->the_post();
$output .= '<li class="col-md-4 col-sm-6 col-xs-12">'.get_the_title().'</li>';
endwhile;
endif;
$output .= '<li>See All Result of '.$_POST['keyword'].' </li>';
$output .= '</ul>';
wp_reset_query();
echo $output; die;
}
// filters search data
function AffordanceSearchPageData()
{
$args = array('post_type'=>'post','status'=>'publish');
$output = '';
$output .= '<ul class="grid effect-3" id="grid">';
if(isset($_POST['keyword']) && !empty($_POST['keyword']))
{
$args['s'] = $_POST['keyword'];
}
if(isset($_POST['page_number']) && !empty($_POST['page_number']) && $_POST['page_number'] != 1){
$args['paged'] = $_POST['page_number'];
}
if(isset($_POST['categories']) && !empty($_POST['categories'])){
$args['cat'] = $_POST['categories'];
}
$wpPosts = new WP_Query($args);
if($wpPosts->have_posts()) :
while($wpPosts->have_posts()) :
$wpPosts->the_post();
$output .= '<li class="col-md-4 col-sm-6 col-xs-12">
<h3 class="resources-content-heading">'.get_the_title().'</h3>
<p class="resources-content-description">'.get_the_excerpt().'</p>
<div class="resources-action-area">
Read More <i class="fa fa-angle-right" aria-hidden="true"></i>
</div>
</li>';
endwhile;
else :
$output .= "No records";
endif;
wp_reset_query();
$output .= the_posts_pagination();
$output .= '</main>';
echo $output; die;
}
}
new SearchAndFilter();
2. Js File (app.js)
jQuery(document).ready(function ($) {
// on searching keyword
$('#search_keyword').keyup(function () {
var inputvalue = $(this).val();
if (inputvalue != '') {
GetSuggestion(inputvalue);
}
});
// on pagination click
$('.ajaxclick').on('click', "a", function () {
var page_number = $(this).attr('data-page-num');
//console.log(page_number);
var current_page = $('.ajaxclick .current').attr('data-page-num');
var keyword = $('#search_keyword').val();
GetSearchData(keyword, page_number);
});
// on category select
$('.category_check').on('click', function () {
var page_number = 1;
var keyword = $('#search_keyword').val();
var blogWrapper = $('.blogWrapper');
var catTagHTML = '<ul>';
blogWrapper.find('input.category_check:checked').each(function () {
catTagHTML += '<li><a class="exclude_cat" href="javascript:void(0)" data-cat-id="' + $(this).attr('value') + '">' + $(this).attr('data-name') + '</a></li>';
});
$('#selected-category-tags').html(catTagHTML);
GetSearchData(keyword, page_number);
});
// on tag click
$('#selected-category-tags').on('click', "a.exclude_cat", function () {
var page_number = 1;
var keyword = $('#search_keyword').val();
var catID = $(this).attr('data-cat-id');
$('#cat' + catID).attr('checked', false);
$(this).closest('li').remove();
GetSearchData(keyword, page_number);
});
function GetSuggestion(keyword) {
var formData = {
'action': 'affordance_search_data',
'keyword': keyword
}
$.ajax({
type: "post",
url: my_ajax_object.ajaxurl,
data: formData,
success: function (data) {
setTimeout(function () {
$('.search-suggestion').html(data);
}, 1000);
}
});
}
function GetSearchData(keyword, page_number) {
if (page_number == '') {
page_number = 1;
}
var blogWrapper = $('.blogWrapper');
var categories = [];
blogWrapper.find('input.category_check:checked').each(function () {
categories.push($(this).attr('value'));
});
var formData = {
'action': 'affordance_search_page_data',
'page_number': page_number,
'keyword': keyword,
'categories': categories,
}
$.ajax({
type: "post",
url: my_ajax_object.ajaxurl,
data: formData,
success: function (data) {
setTimeout(function () {
$('.site-main').html(data);
}, 1000);
}
});
}
});
Here I'm using ajax to achieve this functionality.
I have a dropdown select box whose values are populated from a field priority from database. Then, there are three div tags in which, display_duration and arrival and dispatch date are calculated according to the option selected shown.
I am able to perform the required functionality, the code is running smoothly but there is one more condition which is Normal should be selected as default option value and its values should be displayed in the div tags by default.
For now, I am not able to set normal as default value and thus, I am not getting its related values in div tag.
Here's my code:
Database:
CREATE TABLE `tblpriority` (
`priority_id` INT(11) NOT NULL AUTO_INCREMENT,
`priority` VARCHAR(15),
`dispatch_interval_days` INT,
`arrival_interval_days` INT,
`display_duration` VARCHAR(50),
`created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
`updated_at` DATETIME,
PRIMARY KEY (`priority_id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
;
Query for inserting values:
INSERT INTO `tblpriority` (`priority`,`dispatch_interval_days`,`arrival_interval_days`,`display_duration`) VALUES ('Normal',40,55,'4-6 Weeks');
INSERT INTO `tblpriority` (`priority`,`dispatch_interval_days`,`arrival_interval_days`,`display_duration`) VALUES ('High',30,45,'3-4 Weeks');
INSERT INTO `tblpriority` (`priority`,`dispatch_interval_days`,`arrival_interval_days`,`display_duration`) VALUES ('Low',45,60,'6-8 Weeks');
INSERT INTO `tblpriority` (`priority`,`dispatch_interval_days`,`arrival_interval_days`,`display_duration`) VALUES ('Very High',25,40,'3 Weeks');
index.php(main file)
<?php
use Cosmo\DAL\Order;
$priority_list_data = new Order();
$priority_list = $priority_list_data->getPriorityList();
$priority_option = '<option value=""></option>';
if ($priority_list != false) {
for ($i = 0; $i < count($priority_list); $i++) {
$priority_option .= '<option value= "' . $priority_list[$i]['priority_id'] . '" >' . $priority_list[$i]['priority'] . '</option>';
}
}
?>
<div class="item text-center">
<blockquote>
<div class="row form-group">
<div class="col-md-2 col-sm-1"></div>
<div class="col-md-8 col-sm-10">
<div class="panel panel-default">
<div class="panel-body">
<span class="pull-left">Priority:</span>
<select class="form-control" id="priority_selected">
<?php echo $priority_option; ?>
</select>
<div class="small" id="priority_duration"></div>
</div>
</div>
</div>
<div class="col-md-2 col-sm-1">
</div>
</div>
<div class="row form-group">
<div class="col-md-2 col-sm-1"></div>
<div class="col-md-4 col-sm-5">
<div class="panel panel-default">
<div class="panel-heading">Estimated Dispatch Date:</div>
<div class="panel-body" id="dispatch_date">
<h3></h3>
</div>
</div>
</div>
<div class="col-md-4 col-sm-5">
<div class="panel panel-default">
<div class="panel-heading">Estimated Date of Arrival:</div>
<div class="panel-body" id="arrival_date">
<h3></h3>
</div>
</div>
</div>
<div class="col-md-2 col-sm-1"></div>
</div>
</blockquote>
</div>
<script>
$(document).ready(function () {
$("#priority_selected").change(function () {
var id = $(this).find(":selected").val();
var dataString = 'priority_id=' + id;
$.ajax({
url: '_getprioritydata.php',
dataType: "json",
data: dataString,
cache: false,
success: function (resultData) {
if (resultData['msg'] == 'Success') {
$("#priority_duration").html(resultData.display_duration);
$("#arrival_date").html(resultData.arrival_interval_dates);
$("#dispatch_date").html(resultData.dispatch_interval_dates);
} else if (resultData['msg'] == 'Failed') {
$("#priority_duration").html('');
$("#arrival_date").html('');
$("#dispatch_date").html('');
} else {
$("#priority_duration").html('');
$("#arrival_date").html('');
$("#dispatch_date").html('');
}
}
});
})
});
</script>
Order.php(class file)
<?php
namespace Cosmo\DAL;
Class Order
{
private $db;
public function __construct(){
$config = ConfigSettings::getInstance();
$this->db = DB::getInstance($config->getDatabaseServer(), $config->getDatabaseUsername(), $config->getDatabasePassword(), $config->getDatabaseName());
}
public function getPriorityList(){
$result = $this->db->query("SELECT priority,priority_id FROM tblpriority");
$priority_data = $result->fetchAllArray();
if(count($priority_data)!= 0){
return $priority_data;
}
else{
return false;
}
}
public function getDurationandDates($priority_id)
{
$result = $this->db->query("SELECT display_duration,dispatch_interval_days,arrival_interval_days FROM tblpriority WHERE priority_id='" . $priority_id . "'");
$priorityData = $result->fetchAll();
return $priorityData;
}
}
?>
_getprioritydata.php (json file)
<?php
use Cosmo\DAL\Order;
$response = [];
if (!empty($_REQUEST["priority_id"])) {
$priority_id = $_REQUEST['priority_id'];
$addPriority = new Order();
$priorityData = $addPriority->getDurationandDates($priority_id);
$response['display_duration'] = '';
$response['dispatch_interval_dates'] = '';
$response['arrival_interval_dates'] = '';
if (!empty($priorityData)) {
$curDate = date('d F Y');
$response['msg']= 'Success';
$response['display_duration'] = $priorityData[0]->display_duration;
$response['dispatch_interval_dates'] = date('d F Y', strtotime($curDate. " +{$priorityData[0]->dispatch_interval_days} days"));
$response['arrival_interval_dates'] = date('d F Y', strtotime($curDate. " +{$priorityData[0]->arrival_interval_days} days"));
}
}
else{
$response['msg']= 'Failed';
}
header('Content-Type: application/json');
echo json_encode($response);
exit;
In order to make one of the options selected by default you should include the selected attribute for that specific option:
<option selected="selected">Some option</option>
To clarify, you only need to put the selected attribute on the default option (Replace some condition with what you use to determine the default option):
$priority_list_data = new Order();
$priority_list = $priority_list_data->getPriorityList();
$priority_option = '';
if ($priority_list != false) {
for ($i = 0; $i < count($priority_list); $i++) {
if (<some condition>) {
$is_default = 'selected="selected"';
}
$priority_option .= '<option '. $is_default .' value= "' .
$priority_list[$i]['priority_id'] . '" >' . $priority_list[$i]['priority'] . '</option>';
}
}
I have a project in this i am stuck because i want to search by industry, educational level, Areas of Experience but it does not act in the way i want to do. I have a dropdown list named industry after selecting industry the educational level, Areas of Experience comes in a checkbox. After selecting the box i want to search and display the result. My Search controller is
public function searchProfessionals (Request $request)
{
$industry = $request->input('industry');
$educationLevels = $request->input('educationLevels');
$areasOfExperiences = $request->input('areasOfExperiences');
$startPrice = $request->input('start_price');
$endPrice = $request->input('end_price');
$meetingType = $request->input('meeting_type');
if ($meetingType == 1) {
$type = [1, 1];
} elseif ($meetingType == 2) {
$type = [2, 2];
} elseif ($meetingType === 3) {
$type = [1, 2];
} else {
$type = [1, 2];
}
$userMeetings = array();
$userRoles = array();
$users = array();
$showUsers = array();
$userHourRates = array();
$userIndus = UserIndustry::where('industry_id', $industry)->get();
$userDegrees = UserDegree::where('degree_id', $educationLevels)->get();
$userAreaOfExperiences = UserAreaOfExperience::where('area_of_experience_id', $areasOfExperiences)->get();
if (!empty($userIndus)) {
foreach ($userIndus as $userInd) {
if (!empty($userDegrees)) {
foreach ($userDegrees as $userDegree) {
if (!empty($userAreaOfExperiences)) {
foreach ($userAreaOfExperiences as $userAreaOfExperience) {
$userHourRates[] = UserTime::where('user_id', $userAreaOfExperience->user_id)->whereBetween('hour_rate', [$startPrice, $endPrice])->first();
}
}
$userHourRates[] = UserTime::where('user_id', $userDegree->user_id)->whereBetween('hour_rate', [$startPrice, $endPrice])->first();
}
}
$userHourRates[] = UserTime::where('user_id', $userInd->user_id)->whereBetween('hour_rate', [$startPrice, $endPrice])->first();
}
My blade template is
#extends ('frontends.layouts.app')
#section ('main')
<div id="content-block" class="margin-top-140">
<div class="container-fluid block custom-container">
<h3 class="block-title">Browse Professionals</h3>
<div class="block-subtitle"><span>Connect</span> <span>Learn</span> <span>Inspire</span> <span>Thrive</span> </div>
<div class="row">
{{--<form action="" method="post">--}}
<div class="col-md-2 left-feild">
<div class="margin-bottom-30">
<h3>Search Filters</h3>
</div>
#if(Auth::check() && Auth::user()->user_role->role_id == 1000000)
<div class="be-vidget">
<h3 class="letf-menu-article"> Looking To </h3>
<div class="creative_filds_block">
<div class="radio">
<label><input type="radio" name="lookingTo" onclick="lookingTo(2)"> Seek Advice</label>
</div>
<div class="radio">
<label><input type="radio" name="lookingTo" onclick="lookingTo(3)"> Share Advice</label>
</div>
</div>
</div>
<script>
function lookingTo(e) {
$.ajax({
type: 'POST',
url: '{{ URL::to('looking/to') }}/' + e,
success: function (result) {
$('#browse_professionals').html(result);
}
});
}
</script>
#endif
<div class="be-vidget">
<h3 class="letf-menu-article">Professionals</h3>
<div class="-creative_filds_block">
<div class="fp-panel-wrap">
<a class="toggle-btn active" onclick="open_industry()" href="#" data-target="#ul_industry" id="a_industry">Industry</a>
<ul id="ul_industry" class="fp-panel open" style="overflow:scroll; height:200px;">
#if(!empty($industries))
#foreach($industries as $industry)
<li value="{{ $industry->id }}">{{ (!empty($industry['name'])) ? $industry['name'] : '' }} </li>
#endforeach
#endif
</ul>
<script>
function industry_search(e) {
$.ajax({
type: 'POST',
url: '{{ URL::to('professionals/industry') }}/' + e,
success: function (result) {
$('#education_experience').html(result);
$('#a_industry').attr('class', 'toggle-btn');
$('#ul_industry').css('display', 'none');
$('#education_experience').css('display', 'block');
$('#eduLevel').css('display', 'block');
$('#areaExperience').css('display', 'block');
}
});
}
function open_industry() {
$('#education_experience').css('display', 'block');
$('#education_experience').css('display', 'block');
$('#eduLevel').css('display', 'none');
$('#areaExperience').css('display', 'none');
}
</script>
<div id="education_experience" style="">
<a id="a_education" class="toggle-btn" href="#" data-target="#eduLevel">Education Level</a>
<ul id="eduLevel" class="no-link fp-panel" style="overflow:scroll; height:200px;">
#if(!empty($degrees))
#foreach($degrees as $degree)
<li value="{{ $degree->id }}">{{ (!empty($degree['name'])) ? $degree['name'] : '' }}</a> </li>
#endforeach
#endif
</ul>
<a id="a_experience" class="toggle-btn" href="#" data-target="#areaExperience">Areas of Experience</a>
<ul id="areaExperience" class="no-link fp-panel" style="overflow:scroll; height:200px;">
</ul>
</div>
</div>
</div>
</div>
<div class="be-vidget">
<h3 class="letf-menu-article">Meeting Preferences</h3>
<label>Price</label>
<br> <br>
<input type="hidden" id="price_ranger" class="range-slider" value="23"/>
<label style="margin-top: 30px;">Type</label>
<div class="form-group">
<select class="form-input" id="meeting_type">
<option value="3">All</option>
<option value="1">Phone Meeting</option>
<option value="2">Web Meeting</option>
</select>
</div>
</div>
<button id="search_professionals" type="button" class="btn color-2 size-2 btn-block hover-1">Apply Filter</button>
#if(Session::has('remove_filter'))
<button type="button" class="btn btn-danger size-2 btn-block hover-1">Remove Filter</button>
#endif
<script>
var industry = '';
$('#ul_industry li').click(function() {
industry = $(this).attr('value');
// console.log(industry);
});
$("#search_professionals").click(function () {
var degrees = new Array();
$('input[name="degrees_checkbox"]:checked').each(function() {
degrees.push(this.value);
});
var experiences = new Array();
$('input[name="experiences_checkbox"]:checked').each(function() {
experiences.push(this.value);
});
var price_ranger = $("#price_ranger").val();
var price_ranger_array = price_ranger.split(",");
var start_price = price_ranger_array[0];
var end_price = price_ranger_array[1];
var meeting_type = $("#meeting_type").val();
$.ajax({
'type' : 'post',
'url' : '{{ URL::to('search/professionals') }}',
'data' : {
'industry' : industry,
'educationLevels' : degrees,
'areasOfExperiences' : experiences,
'start_price' : start_price,
'end_price' : end_price,
'meeting_type' : meeting_type
},
'success' : function (result) {
console.log(result);
$('#browse_professionals').html(result);
}
});
});
</script>
</div>
{{--</form>--}}
<div class="col-md-10">
<div id="browse_professionals" class="row _post-container_">
#if (!empty($valid_providers))
#foreach ($valid_providers as $provider)
<div class="category-1 custom-column-5">
<div class="be-post">
<figure class="ratio-4-3 be-img-block-alt">
<div class="ratio-inner" style="background-image: url('{{ !empty($provider->user_detail->avatar) ? URL::to($provider->user_detail->avatar) : '' }}')">
<img src="{{ !empty($provider->user_detail->avatar) ? URL::to($provider->user_detail->avatar) : '' }}" alt="{{ !empty($provider->username) ? URL::to($provider->username) : '' }}">
</div>
</figure>
<div class="be-post-title">{{ (!empty($provider->user_share->share)) ? str_limit($provider->user_share->share, 90) : '' }}</div>
<div class="author-post">
<span>{{ !empty($provider->user_detail->first_name) ? $provider->user_detail->first_name : '' }} {{ !empty($provider->user_detail->last_name) ? $provider->user_detail->last_name : '' }}</span>
</div>
<span>{{ (!empty($provider->user_detail->credentials)) ? str_limit($provider->user_detail->credentials, 25) : '' }}</span>
<div data-value="4" class="static-rating"></div>
<div class="info-block clearfix">
<a class="btn color-1 size-2 hover-1 pull-right" href="{{ !empty($provider->username) ? URL::to($provider->username) : '' }}">Contact</a>
<h3 class="rate"> ${{ (!empty($provider->user_time->hour_rate)) ? $provider->user_time->hour_rate : '' }} /hr</h3>
</div>
</div>
</div>
#endforeach
#endif
</div>
</div>
</div>
</div>
</div>
#endsection
please help me. I am stuck this very badly. Sorry for my bad English
The answer will be
public function searchProfessionals(Request $request)
{
$industry = $request->input('industry');
$educationLevels = $request->input('educationLevels');
$areasOfExperiences = $request->input('areasOfExperiences');
$startPrice = $request->input('start_price');
$endPrice = $request->input('end_price');
$meetingType = $request->input('meeting_type');
$userDetails = array();
$userMeetings = array();
$userRoles = array();
$users = array();
$showUsers = array();
$userHourRates = array();
$userDegrees = array();
$userIndustryArray = array();
$userExperience = array();
$userAr = array();
$data['usersDegress'] = '';
$data['usersExperience'] = '';
$intersect_array = array();
$data['userDetails'] = UserDetail::all();
$data['userTime'] = UserTime::whereBetween('hour_rate',[$startPrice,$endPrice])->get();
$userPriceArray = array();
foreach ($data['userTime'] as $price) {
foreach ($data['userDetails'] as $userDetail) {
if ($price->user_id == $userDetail->user_id) {
$userPriceArray[] = $userDetail;
}
}
}
$newArray = array();
$data['userMeeting'] = UserMeeting::where('meeting_id', $meetingType)->get();
foreach ($userPriceArray as $price) {
foreach ($data['userMeeting'] as $meet) {
if ($price->user_id == $meet->user_id) {
$newArray[] = $price;
}
}
}
if(!empty($industry)) {
$data['userIndustry'] = UserIndustry::where('industry_id',$industry)->get();
foreach ($data['userIndustry'] as $userIn){
foreach ($newArray as $new){
if($new->user_id == $userIn->user_id){
$userIndustryArray[] = $new ;
}
}
}
if(count($educationLevels) >0){
$data['usersDegress'] = UserDegree::whereIn('degree_id',$educationLevels)->get();
foreach ($data['usersDegress'] as $education ){
foreach ($userIndustryArray as $n){
if($n->user_id == $education->user_id){
$userDegrees[] = $n ;
}
}
}
}
if(count($areasOfExperiences) >0){
$data['usersExperience'] = UserAreaOfExperience::whereIn('area_of_experience_id',$areasOfExperiences)->get();
foreach ($data['usersExperience'] as $experience ){
foreach ($userIndustryArray as $ex){
if($ex->user_id == $experience->user_id){
$userExperience[] = $ex ;
}
}
}
}
}else{
$userIndustryArray = $newArray ;
}
if(count($educationLevels)> 0 && count($areasOfExperiences) >0) {
$intersect_array = array_intersect ($userDegrees,$userExperience);
$userIndustryArray =$intersect_array;
}else if(count($educationLevels) == 0 && count($areasOfExperiences) >0) {
$intersect_array = $userExperience;
$userIndustryArray =$intersect_array;
}
else if(count($educationLevels)> 0 && count($areasOfExperiences) == 0) {
$intersect_array = $userDegrees;
$userIndustryArray =$intersect_array;
}else if(count($educationLevels) == 0 && count($areasOfExperiences) == 0) {
$userIndustryArray =$userIndustryArray;
}
$string = '' ;
foreach ($userIndustryArray as $item){
$userRatingShow = Review::where('provider_id',$item->user_id)->avg('rating');
if(empty($userRatingShow)){
$userRatingShow = 0;
}
$avatar = '';
$name = '';
$user = User::find($item->user_id) ;
if(!empty($user)){
$name = $user->username ;
}
if(!empty($item->avatar )){
$avatar = url($item->avatar);
}else{
}
$userTime= UserTime::where('user_id',$item->user_id)->orderby('id','desc')->first();
if(!empty($userTime)){
$userTimeShow = $userTime->hour_rate ;
}
$bio = '';
$user_share = UserShare::where('user_id',$item->user_id)->orderby('id','desc')->first();
if(!empty($user_share)) {
$bio =str_limit($user_share->share,85);
}
$string .= '<div class="category-1 custom-column-5">
<div class="be-post">
<figure class="ratio-4-3 be-img-block-alt">
<div class="ratio-inner" style="background-image: url(' . $avatar . ')">
<img src="' . $avatar . '" alt="omg">
</div>
</figure>
<div class="be-post-title">' . $bio . '</div>
<div class="author-post">
<span>
<a href="' . url($name) . '">' .
$item->first_name . ' ' . $item->last_name . '
</a>
</span>
</div>
<span>' . $item->credentials . '</span>
</div>
<div data-value="' . $userRatingShow . '" class="static-rating"></div>
<div class="info-block clearfix">
<a class="btn color-1 size-2 hover-1 pull-right" href="' . url($name) . '">Contact</a>
<h3 class="rate">$' . $userTimeShow . '/hr</h3>
</div>
</div>
</div>
';
}
if(!empty($string)) {
return response($string);
}else{
echo '<div class="text-center margin-top-140"><h2>Sorry, no members meet your criteria.</h2></div>';
echo '<div class="text-center margin-top-50"><h2>Please revise your search.</h2></div>';
}
}