php jQuery autocomplete not working fine in laravel - javascript

I've been working to add autocomplete to my Location text field, the problem is when I type any word on it, it always display all the result.
This is my javascript:
<script type="text/javascript">
$(function(){
$("#Location").autocomplete({
source: "{{ route('search.autocomplete') }}",
minLength: 3,
select: function(event, ui){
$("#Location").val(ui.item.value);
}
});
});
</script>
This is the route.php
Route::get('search/autocomplete', ['uses' => 'SearchController#autocomplete', 'as' => 'search.autocomplete']);
This is the searchController
public function autocomplete(Request $request){
$term = $request->get('Location');
$provinces = DB::table('provinces')->where('ProvinceName', 'LIKE', '%'. $term .'%')
->orderBy('ProvinceName', 'desc')
->get();
$results = [];
foreach ($provinces as $province) {
$results[] = ['id' => $province->id, 'value' => $province->ProvinceName];
}
return response()->json($results);
}
and this is the search.blade.php
<div class="form-group col-md-4">
Location: {!!Form::text('Location', Request::get('Location'), ['class' => 'form-control', 'placeholder' => 'What is your location?', 'id' => 'Location', 'style' => 'width: 250px;'])!!}
</div>

Okay I solve my problem, I change
route.php
Route::get('search/autocomplete', 'SearchController#autocomplete');
SearchController
if ($request->ajax()) {
$term = Input::get('term');
$results = array();
$queries = DB::table('provinces')
->where('ProvinceName', 'LIKE', '%'.$term.'%')
->take(5)->get();
foreach ($queries as $query)
{
$results[] = [ 'id' => $query->id, 'value' => $query->ProvinceName ];
}
return Response::json($results);
}
and my Javascript
<script type="text/javascript">
$(function()
{
$( "#Location" ).autocomplete({
source: "{{ url('search/autocomplete') }}",
minLength: 3,
select: function(event, ui) {
$('#Location').val(ui.item.value);
}
});
});
</script>

An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]
The label property is displayed in the suggestion menu. The value will be inserted into the input element when a user selects an item. If just one property is specified, it will be used for both, e.g., if you provide only value properties, the value will also be used as the label.
Change
$results[] = ['id' => $province->id, 'value' => $province->ProvinceName];
to
$results[] = ['value' => $province->id, 'label' => $province->ProvinceName];
And
$("#Location").val(ui.item.value);
To
$("#Location").val(ui.item.label);
Use id in frontend as
ui.item.value

Related

php - Display Events with Form Submit (FullCalendar)

Good day!
I am working on a small personal project with FullCalendar. So in the code below, I have written a function that displays the events when the user searches for that event when a keyword is entered. (e.g. "meeting")
function load($pdo)
{
try {
if (isset($_POST['search'])) {
//run sql connection and query
$term = $_POST['term'];
$data = array();
$sql = "SELECT * FROM events WHERE keyword LIKE '%$term%'";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
//output events data from db in array using foreach loop
foreach ($result as $row) {
$description = $row['description'];
$sentence = preg_replace('/(.*?[?!.](?=\s|$)).*/', '\\1', $description);
if (($row['allDay'] == '1') == 1) {
$data[] = array(
'id' => $row["id"],
'title' => $row["title"],
'start' => $row["s_date"],
'description' => $sentence,
'end' => $row["e_date"],
'url' => "event.php?id=".$row['id'],
'backgroundColor' => $row['bg_color'],
'borderColor' => $row['brdr_Color'],
'keywords' => $row['keyword'],
'category' => $row['category']
);
} else {
$data[] = array(
'id' => $row["id"],
'title' => $row["title"],
'start' => $row["s_date"],
'description' => $sentence,
'end' => $row["e_date"],
'url' => "event.php?id=".$row['id'],
'backgroundColor' => $row['bg_color'],
'borderColor' => $row['brdr_Color'],
'keywords' => $row['keyword'],
'category' => $row['category']
);
}
}
//echo and convert array to JSON representation
echo json_encode($data);
}
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
}
//execute load function
load($pdo);
The results are echoed in a json_encoded function and are loaded from jQuery.
$(document).ready(function () {
var calendar = $("#calendar").fullCalendar({
displayEventTime: false,
editable: false,
header: {
left: "prev,next today",
center: "title",
right: "listMonth, month,agendaWeek,agendaDay",
},
eventRender: function (event, element, view) {
$(element).tooltip({
title: event.description,
});
},
events: "load.php",
});
});
After submitting the form/hitting the submit button, the events are not returned or displayed. Is there something I'm missing in my code, or am I missing a procedure?
I hope I described my issue to your best of understanding and I hope to learn from this and better improve my code in the future.

Inserting a array of php values into a select options via javascript

I have multiple select elements, and each select form is either a block type or a block content. So in total i have around 10 select elements, 5 of which are block type and 5 are block content. The select options of block content will be determined by what the user select in block type.
I have 3 arrays (property, blogs, message), which have the values needed for block content.
So what i need to do is-
check what the user has selected for block type- which i have done.
Populate the block content with the relevant values- this is where i am having problems.
Here is my javascript code so far
$(".blockTypeWrapper .blockType").change(function() {
var currentBlock = $(this).val();
var blockContent = $(this).parent().siblings('.blockContentWrapper .blockContent');
if (currentBlock == '1') {
var option = document.createElement("option");
var propertyData = <?php echo $properties; ?>;
$.each(propertyData, function() {
options.append(new Option(option.text, option.value));
});
};
if (currentBlock == '2') {
$(this).siblings(".blockContent").addClass("active");
};
if (currentBlock == '3') {
$(this).siblings(".blockContent").addClass("active");
};
});
Ignore the currentBlock == '2' and 3 code, i am just trying to get it working for one first.
If there are any other easier way of achieving this then i'm all ears.
EDIT
echo $this->Form->input('main_block_type',
array(
'options' => array(
1 => 'Property',
2 => 'Blogs',
3 => 'Message'
),
'label' => 'Main Block Type',
'empty' => 'Please Select',
'class' => 'blockType',
'div' => array(
'class' => 'blockTypeWrapper'
)
)
);
echo $this->Form->input('main_block',
array(
'options' => $blogs,
'label' => 'Main Block Content',
'empty' => 'Please Select',
'class' => 'blockContent',
'div' => array(
'class' => 'blockContentWrapper'
)
)
);
Thanks
You can't access Array with echo. You need to access with:
<?php echo json_encode($properties); ?>;
try below code:
if (currentBlock == '1') {
var propertyData = <?php echo json_encode($properties); ?>;
$(".blockContent").empty(); // You can remove all the options by using empty() function.
$.each(propertyData, function (i, item) {
$('.blockContent').append($('<option>', {
value: item.value,
text: item.text
}));
});
}
PHP Array of properties should be like this:
$properties = array(
'item1' => array('text' => 'item1 text', 'value' => 'item 1 value'),
'item2' => array('text' => 'item2 text', 'value' => 'item 2 value'),
'item3' => array('text' => 'item3 text', 'value' => 'item 3 value')
);

Multiple Model on same ActiveForm yii2

have multiple model on same form
I dont want to save data on both model but i just want to display one variable on view file
I have 2 tables
Organiser and Event
Organiser will log in and Create Event
Now there are few fields which are common in both tables
so when logged in user click on Create Event button i want to display address from Organiser table on the form
This is what i have done until now
which may not be the right approach
so let me know if that can be achieved any other simpler way
public function actionCreate()
{
$model = new Event();
$model2 = $this->findModel2(Yii::$app->user->id);
if ($model->load(Yii::$app->request->post())) {
if($_POST['User']['address'] == null)
{
$model->location = $model2->address;
}
else{
$model->location = $_POST['User']['address'];
}
$model->is_active = 1 ;
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'model2' => $model2
]);
}
}
protected function findModel2($id)
{
if (($model2 = User::findOne($id)) !== null) {
return $model2;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
And here is my _form.php code
<?php $form = ActiveForm::begin([
'options' => [
'id' => 'create-event-form'
]
]); ?>
<?= $form->field($model, 'interest_id')->dropDownList(
ArrayHelper::map(Areaintrest::find()->all(),'id','area_intrest'),
['prompt'=> 'Select Event Category']
) ?>
<?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>
<?php
if ($model->isNewRecord){
echo $form->field($model2,'address')->textInput(['class' => 'placepicker form-control'])->label('Location');
}
else
echo $form->field($model,'location')->textInput(['class' => 'placepicker form-control']);
?>
<di"form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-danger' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
Now the problem here seems is that when it comes to saving part throws error saying unknown property address because that field doesnt exists in the database table Event
i just want that data to display it on the location field of my create form
so what should i do here
Here is the table structure
Organiser Event
organiser_id event_id
username organiser_id
clubname title
image location
email
firstname
lastname
address
Error page says something like this
Unknown Property – yii\base\UnknownPropertyException
Getting unknown property: common\models\Event::address
And here is my Event model
class Event extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'event';
}
public function rules()
{
return [
[['organiser_id', 'interest_id', 'title', 'location'], 'required'],
[['organiser_id', 'interest_id'], 'integer'],
[['title', 'location'], 'string', 'max' => 255],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'organiser_id' => 'Organiser ID',
'interest_id' => 'Event Type',
'title' => 'Event Title',
'location' => 'Location'
];
}
public function getOrganiser()
{
return $this->hasOne(User::className(), ['organiser_id' => 'organiser_id']);
}
}
Here is my User model represent Organiser table and model name in frontend model SignUp.php
class SignupForm extends Model
{
public $username;
public $address;
public $password;
public $password_repeat;
public function rules()
{
return [
['username', 'filter', 'filter' => 'trim'],
['username', 'required'],
['address', 'required'],
['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],
['username', 'string', 'min' => 2, 'max' => 255],
[['file'], 'file', 'extensions'=>'jpg, gif, png'],
['password', 'required'],
['password', 'string', 'min' => 6],
['password_repeat', 'compare', 'compareAttribute' => 'password'],
];
}
public function attributeLabels()
{
return [
'password_repeat' => 'Confirm Password',
'address' => 'Address',
'username' => 'Username',
];
}
public function signup()
{
if ($this->validate()) {
$user = new User();
$model = new SignupForm();
$user->address = $this->address;
$user->username = $this->username;
$user->setPassword($this->password);
$user->generateAuthKey();
if ($user->save()) {
return $user;
}
}
return null;
}
}
So i want to display the organiser.address on the Create event form in the field location
Hope you can understand it now
thank you
May be your function should look like
public function actionCreate()
{
$event= new Event();
$user= $this->findModel2(Yii::$app->user->id);
$event->location = $user->address;
if ($event->load(Yii::$app->request->post()) && $event->save()) {//active can set by default validator
return $this->redirect(['view', 'id' => $event->id]);
}
return $this->render('create', [
'event' => $event
]);
}
And in form you show location always. Then you can use it in update and create as well without ifs in view. Hope this will help you.

wordpress custom query - orderby title will not work

I am having a problem getting a custom query to alphabetize. It keeps defaulting to displaying in the order of the date it was posted. Below is my php function.
function json_info2() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
// get values for all three drop-down menus
$status = $_REQUEST['status'];
$industry = $_REQUEST['services'];
$state = $_REQUEST['state'];
// array of values for each of the three drop-downs
$statusAll = array('complete','incomplete');
$industryAll = array('mining','textile','machinery');
$statesAll = array('SC','TX','WA');
// set $statusArray dependent on whether or not "all" is selected in the dropdown menu
if($status == "all") {
$statusArray = array( 'key' => 'status', 'value' => $statusAll, 'compare' => 'IN');
} else {
$statusArray = array( 'key' => 'status', 'value' => $status, 'compare' => '=');
}
if($industry == "all") {
$industryArray = array( 'key' => 'industry', 'value' => $industryAll, 'compare' => 'IN');
} else {
$industryArray = array( 'key' => 'industry', 'value' => $industry, 'compare' => '=');
}
if($state == "all") {
$stateArray = array( 'key' => 'state', 'value' => $statesAll, 'compare' => 'IN');
} else {
$stateArray = array( 'key' => 'state', 'value' => $state, 'compare' => '=');
}
$pages = array(
'post_type' => 'page',
'orderby' => 'title',
'order' => 'ASC',
'paged' => $paged,
'posts_per_page' => 5,
'meta_query' => array(
'relation' => 'AND',
$statusArray,
$industryArray,
$stateArray,
array(
'key' => '_wp_page_template',
'value' => 'template-individual-project.php',
'compare' => '='
)
)
);
// query results by page template
$my_query = new WP_Query($pages);
if($my_query->have_posts()) :
while($my_query->have_posts()) :
$my_query->the_post();
<li>
<?php the_title(); ?>
</li>
<?php
endwhile;endif;
wp_reset_query();
} // end of isset
?>
<?php
die();
}
add_action( 'wp_ajax_json_info2', 'json_info2' );
add_action( 'wp_ajax_nopriv_json_info2', 'json_info2' );
?>
This above function is called by the ajax function that follows:
function do_ajax() {
// Get values from all three dropdown menus
var state = $('#states').val();
var markets = $('#markets').val();
var services = $('#services').val();
$.ajax({
url: ajaxurl,
data: {
'action' : 'json_info2',
'state' : state,
'status' : markets,
'services' : services
},
success:function(moredata) {
// This outputs the result of the ajax request
$('#project-list').html( moredata );
$('#project-list').fadeIn();
}/*,
error: function(errorThrown){
var errorMsg = "No results match your criteria";
$('#project-list').html(errorMsg);
}*/
}); // end of ajax call
} // end of function do_ajax
Is there something simple that I'm missing here? I have a similar custom query on the page when it loads (although that initial load query doesn't have the select menu values as args), and they display in alphabetical order just fine. It's only after the ajax call to filter the list that they are no longer in order.
I have found the issue after googling the problem for quite a while. I read that some of the people who were having this problem found that their theme was using a plugin called Post Types Order. It overrides the ability to set the orderby arg.
I looked at the plugins, and sure enough, Post Types Order was there. Everything I read said that the problem could be solved by unchecking "auto sort" in the settings for the plugin. However, I did that, and orderby still didn't work. I had to completely deactivate the plugin to get orderby title to work.

yii cgridview update depending on dropdownlist

I'm newbie with Yii.
I have a CGridview with a cutom dataprovider which takes a parameter $select:
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'beneficiary-grid',
'dataProvider' => $model->searchForVoucherAssignment($select),
'filter' => $model,
'columns' => array(
'id',
'registration_code',
'ar_name',
'en_name',
'family_member',
'main_income_source',
'combine_household',
array( 'class'=>'CCheckBoxColumn', 'value'=>'$data->id', 'selectableRows'=> '2', 'header' => 'check',
),
),
));
That parameter $select takes its values from dropdownlist:
$data = CHtml::listData(Distribution::model()->findAll(array("condition"=>"status_id = 2")), 'id', 'code');
$select = key($data);
echo CHtml::dropDownList(
'distribution_id',
$select, // selected item from the $data
$data,
array(
)
);
So I defined a script to update the CGridview depending on the value of dropdownlist
Yii::app()->clientScript->registerScript('sel_status', "
$('#selStatus').change(function() {
$.fn.yiiGridView.update('beneficiary-grid', {
data: $(this).serialize()
});
return false;
});
");
My model:
public function searchForVoucherAssignment ($distribution_id = 0) {
$criteria = new CDbCriteria;
if ($distribution_id != 0) {
$criteria->condition = "Custom Query...!!";
}
$criteria->compare('id', $this->id);
//Custom Criteria
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
'pagination' => array(
'pageSize' => 20,
),
));
}
The problem is that the CGridview isn't changing where a value of the dropdownlist changed...
I think you have selected the wrong Id for the change event. The Id should be
$('#distribution_id').change(function() {

Categories

Resources