i´m not getting run my application, i select the city then i need that the dropdown show the NEIGHBORHOODS associated with the city....
this is my getNeighborhoods:
public function pegarBairros ($cidades = null) {
$this->layout = 'json';
$result = array();
debug($_REQUEST['cidade']);
if (in_array($_REQUEST['cidade'], array_keys($this->cidades))) {
$bairros = $this->Cep->find('list', array('fields' => array('id', 'bairro'), 'conditions' => array('uf_sigla' => 'sp', 'cidade' => $this->cidades[$_REQUEST['cidade']]), 'order' => 'bairro', 'group' => 'bairro'));
sort($bairros);
foreach ($bairros as $id => $bairro)
if (!empty($bairro)) $result[$id] = $bairro;
} else $result[] = 'error';
$this->set('data', $result);
}
and this is my ajax:
$('#ImovelCidade').change(function(e) {
$('#ImovelBairro').html($('<option />').val('').text('Carregando...'));
$.getJSON(
"<?php echo Router::url(array('controller' => 'pages', 'action' => 'pegarBairros')) ?>",
{ "cidade" : $(this).val() },
function (data) {
$('#ImovelBairro').html($('<option />').val('').text('Selecione'));
$.each(data, function (chave, valor) {
$('#ImovelBairro').append($('<option />').val(chave).text(valor));
} );
}
);
});
this ajax call the function getNeigh...
this is my select city:
echo $this->Form->input('cidade', array('label' => 'Cidade', 'empty' => 'Selecione uma cidade', 'options' => $Cidades));
my before filter that received city:
public function beforeFilter() {
$this->loadModel('Cidade');
$this->cidade = $this->Cidade->find('list', array ('fields' => array('id','nome')));
$this->set('Cidades',$this->cidade);
Related
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.
I am trying to call a API URL using AJAX. I need to validate the response and update the DB, SO I need to return it to the controller.
Is there any way to do that. Here is my view, JS and controller code.
Here is my View Code where I have a separate URL for validation, which is the API URL
View
<?php $form = ActiveForm::begin([
'action' => ['users/renderstep3'],
'validationUrl' => 'API URL',
'options' => [
'class' => 'comment-form'
]
]); ?>
<?= $form->field($paymentmodel, 'customerId')->hiddenInput(['value'=> $userid])->label(false) ?>
<?= $form->field($paymentmodel, 'owner')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
JS
jQuery(document).ready(function($) {
$('body').on('submit', '.comment-form', function(event) {
event.preventDefault(); // stopping submitting
var data = $(this).serializeArray();
data.splice(0,1);
var result = {};
for ( i=0 ; i < data.length ; i++)
{
key = data[i].name.replace("UserPaymentDetails[", "").slice(0,-1);
result[key] = data[i].value;
}
var url = $(this).attr('validationUrl');
$.ajax({
url: url,
type: 'post',
dataType: 'json',
data: JSON.stringify(result)
})
.done(function(response) {
return response;
})
.fail(function() {
console.log("error");
});
});
});
Controller Action
public function actionRenderstep3()
{
$model = new Users();
$detailsmodel = new UserDetails();
$paymentmodel = new UserPaymentDetails();
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$data = Yii::$app->request->post();
print_r($data) ; exit;
}
if ($paymentmodel->load(Yii::$app->request->post()) && $paymentmodel->validate())
{
$paymentmodel->Status = 0;
$paymentmodel->save();
return $this->redirect(['index']);
}
return $this->render('renderstep3', [
'model' => $model,
'detailsmodel' => $detailsmodel,
'paymentmodel' => $paymentmodel,
]); }
Thanks in advance!!
In your controller, you have to change the action like this in order to validate using Ajax. I have edited my answer. Please note that you can delete your custom js code in order to use like this.
// ... The View file
<?php
$form = ActiveForm::begin([
'action' => ['users/renderstep3'],
'enableAjaxValidation' => true,
'validationUrl' => 'API URL',
'options' => [
'class' => 'comment-form'
]
]);
?>
<?= $form->field($paymentmodel, 'customerId')->hiddenInput(['value'=> $userid])->label(false) ?>
<?= $form->field($paymentmodel, 'owner')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
// ... Controller
public function actionRenderstep3()
{
$model = new Users();
$detailsmodel = new UserDetails();
$paymentmodel = new UserPaymentDetails();
if (Yii::$app->request->isAjax && $paymentmodel->load(Yii::$app->request->post())) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
if ($paymentmodel->load(Yii::$app->request->post())) {
$paymentmodel->Status = 0;
$paymentmodel->save(false); // Validate false, because we did the validation before
return $this->redirect(['index']);
}
return $this->render('renderstep3', [
'model' => $model,
'detailsmodel' => $detailsmodel,
'paymentmodel' => $paymentmodel,
]);
}
You can find more information here
https://www.yiiframework.com/doc/guide/2.0/en/input-validation
<?php
$form = ActiveForm::begin([
'action' => ['users/renderstep3'],
'validationUrl' => 'API URL',//ajax validation hit to validationUrl if provide other wise validationUrl is action Url
'options' => [
'class' => 'comment-form'
]
]);
?>
and change some code in js
the below code calls befor form submit
$('body').on('beforeSubmit', '.comment-form', function(event)
In controller
In case of single model validation
if ($paymentmodel->load(Yii::$app->request->post())) {
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return yii\widgets\ActiveForm::validate($model);
}
$paymentmodel->Status = 0;
if ($paymentmodel->save(false)) {
return $this->redirect(['index']);
}
}
In case of multiple model validation
if ($model->load(Yii::$app->request->post())) {
$detailsmodel->load(Yii::$app->request->post());
$paymentmodel->load(Yii::$app->request->post());
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$return = yii\widgets\ActiveForm::validate($model);
$return = \yii\helpers\ArrayHelper::merge(yii\widgets\ActiveForm::validate($detailsmodel), $return);
$return = \yii\helpers\ArrayHelper::merge(yii\widgets\ActiveForm::validate($paymentmodel), $return);
return $return;
}
//here is data saving or logic
}
I have problem with my laravel project, when validator false return back function run well on localhost, but on the server it return to root url , somebody may help me figure it out?
My controller like this:
public function update(Request $request, $id)
{
if ($request->isMethod('get'))
return view('employees.form_edit', ['user' => User::find($id)]);
else {
$rules = [
'name' => 'required',
'full_name' => 'required',
'id_number' => 'required',
'date_of_birth' => 'required',
'avatar' => 'mimes:jpeg,jpg,png,gif|max:2048'
];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
;
}
$user = User::find($id);
$user->name = $request->name;
$user->position = $request->position;
$user->full_name = $request->full_name;
$user->id_number = $request->id_number;
$user->date_of_birth = $request->date_of_birth;
$user->status = $request->status;
$img_current = 'upload/avatar/' .$request->input('img_current');
if (!empty($request->file('avatar'))) {
$file_name = $request->file('avatar')->getClientOriginalName();
$user->image = $file_name;
$request->file('avatar')->move('upload/avatar/',$file_name);
if (File::exists($img_current)) {
File::delete($img_current);
}
}else{
echo "no file";
}
$user->save();
return redirect('listEmployees');
}
}
My route:
Route::group(['prefix' => 'listEmployees'], function () {
Route::match(['get', 'post'], 'update/{id}', 'EmployeesController#update');
});
Try this code I have
CONTROLLER
public function update(Request $request, $id)
{
if ($request->isMethod('get'))
return view('employees.form_edit', ['user' => User::find($id)]);
else {
$_data = $request->validate([
'name' => ['required'].
'full_name' => ['required'],
'id_number' => ['required'],
'date_of_birth' => ['required'],
'avatar' => ['mimes:jpeg,jpg,png,gif', 'max:2048'],
'position' => ['nullable'],
'status' => ['nullable']
])
$img_current = 'upload/avatar/' .$request->input('img_current');
if (!empty($request->file('avatar'))) {
$file_name = $request->file('avatar')->getClientOriginalName();
$data['image'] = $file_name;
$request->file('avatar')->move('upload/avatar/',$file_name);
if (File::exists($img_current)) {
File::delete($img_current);
}
}else{
echo "no file";
}
$user = User::find($id);
$user->update($_data);
return redirect('listEmployees');
}
}
VIEW
#if ($errors->any())
<div class="alert alert-warning">
#foreach ($errors->all() as $error)
{{$error}} <br>
#endforeach
</div>
#endif
Before you go further with this problem you need to clean up your code a little bit.
First of all you dont need to check the request->method if you have already made the route "Route::update" (laravel takes care of it).
Second: use laravel form-request and make your controller much more cleaner and readable(php artisan make:request ModelNameRequest)
Third: you dont need to redirect user to manually if you want to redirect to back(), again laravel takes care of it, it will redirect back() if the validator fails with and array of $errors.
any ways this is the code that may work:
public function update(Request $request, $id)
{
$rules = [
'name' => 'required',
'full_name' => 'required',
'id_number' => 'required',
'date_of_birth' => 'required',
'avatar' => 'mimes:jpeg,jpg,png,gif|max:2048'
];
// if the validation failes, laravel redirects back with a collection of $errors
$this->validate($request->all(), $rules);
// you probably want to use User::create($request->only('input1', 'input2', ...);
$user = User::find($id);
$user->name = $request->name;
$user->position = $request->position;
$user->full_name = $request->full_name;
$user->id_number = $request->id_number;
$user->date_of_birth = $request->date_of_birth;
$user->status = $request->status;
$img_current = 'upload/avatar/' .$request->input('img_current');
// use a good package for storing your files like Mediable to make it easy.
if (!empty($request->file('avatar'))) {
$file_name = $request->file('avatar')->getClientOriginalName();
$user->image = $file_name;
$request->file('avatar')->move('upload/avatar/',$file_name);
if (File::exists($img_current)) {
File::delete($img_current);
}
}else{
//TODO: you should not echo some thing here, you should use session()->flash()
session()->flash('message', 'You did not select any file.');
}
$user->save();
return redirect('listEmployees');
}
i solve this problem by change redirect function to
return redirect()->action(
'EmployeesController#update', ['id' => $id]
)
thank all guy
I have been trying to make an autocomplete script for the whole day but I can't seem to figure it out.
<form method="POST">
<input type="number" id="firstfield">
<input type="text" id="text_first">
<input type="text" id="text_sec">
<input type="text" id="text_third">
</form>
This is my html.
what I am trying to do is to use ajax to autocomplete the first field
like this:
and when there are 9 numbers in the first input it fills the other inputs as well with the correct linked data
the script on the ajax.php sends a mysqli_query to the server and asks for all the
data(table: fields || rows: number, first, sec, third)
https://github.com/ivaynberg/select2
PHP Integration Example:
<?php
/* add your db connector in bootstrap.php */
require 'bootstrap.php';
/*
$('#categories').select2({
placeholder: 'Search for a category',
ajax: {
url: "/ajax/select2_sample.php",
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
term: term, //search term
page_limit: 10 // page size
};
},
results: function (data, page) {
return { results: data.results };
}
},
initSelection: function(element, callback) {
return $.getJSON("/ajax/select2_sample.php?id=" + (element.val()), null, function(data) {
return callback(data);
});
}
});
*/
$row = array();
$return_arr = array();
$row_array = array();
if((isset($_GET['term']) && strlen($_GET['term']) > 0) || (isset($_GET['id']) && is_numeric($_GET['id'])))
{
if(isset($_GET['term']))
{
$getVar = $db->real_escape_string($_GET['term']);
$whereClause = " label LIKE '%" . $getVar ."%' ";
}
elseif(isset($_GET['id']))
{
$whereClause = " categoryId = $getVar ";
}
/* limit with page_limit get */
$limit = intval($_GET['page_limit']);
$sql = "SELECT id, text FROM mytable WHERE $whereClause ORDER BY text LIMIT $limit";
/** #var $result MySQLi_result */
$result = $db->query($sql);
if($result->num_rows > 0)
{
while($row = $result->fetch_array())
{
$row_array['id'] = $row['id'];
$row_array['text'] = utf8_encode($row['text']);
array_push($return_arr,$row_array);
}
}
}
else
{
$row_array['id'] = 0;
$row_array['text'] = utf8_encode('Start Typing....');
array_push($return_arr,$row_array);
}
$ret = array();
/* this is the return for a single result needed by select2 for initSelection */
if(isset($_GET['id']))
{
$ret = $row_array;
}
/* this is the return for a multiple results needed by select2
* Your results in select2 options needs to be data.result
*/
else
{
$ret['results'] = $return_arr;
}
echo json_encode($ret);
$db->close();
Legacy Version:
In my example i'm using an old Yii project, but you can easily edit it to your demands.
The request encodes in JSON. (You don't need yii for this tho)
public function actionSearchUser($query) {
$this->check();
if ($query === '' || strlen($query) < 3) {
echo CJSON::encode(array('id' => -1));
} else {
$users = User::model()->findAll(array('order' => 'userID',
'condition' => 'username LIKE :username',
'limit' => '5',
'params' => array(':username' => $query . '%')
));
$data = array();
foreach ($users as $user) {
$data[] = array(
'id' => $user->userID,
'text' => $user->username,
);
}
echo CJSON::encode($data);
}
Yii::app()->end();
}
Using this in the View:
$this->widget('ext.ESelect2.ESelect2', array(
'name' => 'userID',
'options' => array(
'minimumInputLength' => '3',
'width' => '348px',
'placeholder' => 'Select Person',
'ajax' => array(
'url' => Yii::app()->controller->createUrl('API/searchUser'),
'dataType' => 'json',
'data' => 'js:function(term, page) { return {q: term }; }',
'results' => 'js:function(data) { return {results: data}; }',
),
),
));
The following Script is taken from the official documentation, may be easier to adopt to:
$("#e6").select2({
placeholder: {title: "Search for a movie", id: ""},
minimumInputLength: 1,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json",
dataType: 'jsonp',
data: function (term, page) {
return {
q: term, // search term
page_limit: 10,
apikey: "ju6z9mjyajq2djue3gbvv26t" // please do not use so this example keeps working
};
},
results: function (data, page) { // parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to alter remote JSON data
return {results: data.movies};
}
},
formatResult: movieFormatResult, // omitted for brevity, see the source of this page
formatSelection: movieFormatSelection // omitted for brevity, see the source of this page
});
This may be found here: http://ivaynberg.github.io/select2/select-2.1.html
You can optain a copy of select2 on the github repository above.
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() {