I've a field called employee_name and depending on this field value I want to autofill another field employee_id. I've searched and I found this answer and tried implementing this on my form but I'm getting Error in ajax request. The jquery code in my form is
$('#emp').focusout(function() {
empName = this.value;
if ( empName != '' || empName != null ) {
$('#depcustomer-employee_name').val(empName);
}
$.ajax({
url: '".yii\helpers\Url::toRoute("deposit/employeeid")."',
dataType: 'json',
method: 'GET',
data: {name: $(this).val()},
success: function (data, textStatus, jqXHR) {
$('#depcustomer-employee_id').val(data.id);
},
beforeSend: function (xhr) {
alert('loading!');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('An error occured!');
alert('Error in ajax request');
}
});
});
My Controller name is Deposit and my controller code is
public function actionEmployeeid($name){
$model= app\modules\settings\models\DepEmployee::findOne(['employee_name'=>$name]);
return \yii\helpers\Json::encode([
'id'=>$model->employee_id
]);
What could be the possible reason that my ajax code is not working?
My form is quite big. Here's the part of the employee field entry
<div class="row">
<div class="col-md-6">
<?= $form->field($model, 'employee_id')->textInput(['maxlength' => true]) ?>
</div>
<div class="col-md-6">
<label for='emp'>Employee Name</label>
<?= Html::activeHiddenInput($model, 'employee_name')?>
<?php
echo AutoComplete::widget([
'name' => 'employee_name',
'id' => 'emp',
'clientOptions' => [
'source' => $dataEmp,
'autoFill'=>true,
'minLength'=>'2',
'select' => new JsExpression("function( event, ui ) {
$('#depcustomer-name').val(ui.item.id);
}")
],
]);
?>
</div>
</div>
According to your autocomplete data you already have employee_id. So no need to make ajax request to get employee id.
DepEmployee Model
public static function getEmpData()
{
$dataEmp = DepEmployee::find()
->select(['employee_name as value', 'employee_name as label','employee_id as id'])
->asArray()
->all();
return $dataEmp;
}
_form
<?= AutoComplete::widget([
'name' => 'employee_name',
'id' => 'emp',
'clientOptions' => [
'source' => DepEmployee::getEmpData(),
'autoFill'=>true,
'minLength'=>'2',
'select' => new JsExpression("function( event, ui ) {
$('#depcustomer-name').val(ui.item.id);
$('#depcustomer-employee_id').val(ui.item.id);
}")
],
]);?>
What i should do if i was at your place:
Here the view:
<?= $form->field($model, 'employeeName')->textInput([
// I use onfocusout instead of focusout
'onfocusout' => '
$.post("generateemployeeid?name="+$(this).val(), function(data) {
$("#employee_id_container").html(data);
});
',
]) ?>
<div id="employee_id_container"></div> // <- I will autofill here
Now here is the function who will fill the ID input: (should be in your controller)
public function actionGenerateemployeeid($name) {
$employeeModel = DepEmployee::find()
->where(['employee_name' => $name])
->one();
if($employeeModel !== NULL) {
echo 'Employee ID: <input type="text" name="EmployeeID" value="'.$employeeModel->employee_id.'" readonly><br>';
}
else {
// error 404
}
}
Resume: the jquery function take the employee name and send to the controller who will look for the employee ID in the database. Then send an input text with default value (employee ID) as response and load this input in the form.
Related
I am trying to query the WP Database but I am receiving an error of Call to a member function get_results() on null. I believe I need to somehow register wpdb but despite reading through multiple similar questions I can't piece together what needs to be done. Any help is greatly appreciated as I am new and learning Wordpress and Ajax.
My JS file is called zip-search-popup.js
(function($) {
$(document).ready(function() {
$('.zip-bar-button').click(function(event) {
event.preventDefault();
submittedZip = $("#zipcode-bar-input").val();
$.ajax({
//need an automatic URL so that this doesn't need to be updated
url: from_php.ajax_url,
type: "GET",
data: {
action : 'zip_search',
submittedZip : submittedZip,
},
success: function (response) {
console.log(response);
alert("working");
}
})
$('.zip-search-popup-con').fadeToggle(350);
})
$('.zip-search-dismiss').click(function() {
$('.zip-search-popup-con').toggle();
})
})
})(jQuery);
I have registered my scripts in functions.php and have my SQL query function within here as well.
add_action('wp_enqueue_scripts', 'hyix_enqueue_custom_js');
function hyix_enqueue_custom_js() {
//enqueue zip-search-popup.js
wp_enqueue_script('zip-search-popup', get_stylesheet_directory_uri().'/js/zip-search-popup.js', array('jquery'), false, true);
wp_localize_script('zip-search-popup', 'from_php', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
//hook zip-search-popup function into ajax
add_action( 'wp_ajax_zip_search', 'ajax_zip_search' );
//same hook for users not logged in
add_action( 'wp_ajax_nopriv_zip_search', 'ajax_zip_search' );
//query for pulling in shipping data
function ajax_zip_search() {
$submitted_zip = $_REQUEST['submittedZip'];
global $wpdb;
// The SQL query
$response = $wpdb-> get_results("SELECT {$wpdb->prefix}woocommerce_shipping_zones.zone_name ".
"FROM {$wpdb->prefix}woocommerce_shipping_zone_locations ".
"INNER JOIN {$wpdb->prefix}woocommerce_shipping_zones ".
"ON {$wpdb->prefix}woocommerce_shipping_zone_locations.zone_id = {$wpdb->prefix}woocommerce_shipping_zones.zone_id ".
"WHERE location_code = '$submittedZip' ");
$response = array(
'request' => $_REQUEST,
'zip' => $submitted_zip,
'test' => 'is ok',
);
wp_send_json( $response );
// echo $response;
die();
}
You should use the Wordpress-Way to use AJAX
All Ajax-Request will be recieved by wp-admin/admin-ajax.php which fires the Ajax-Hooks which run your PHP-Code. The Ajax-Hook depends from the action-parameter in your Ajax-Request.
With wp_localize_script() you can provide some data from PHP to Javascript, i.e. the ajax_url.
Place this code in your functions.php. This include the code that handles your Ajax-Request.
add_action('wp_enqueue_scripts', 'hyix_enqueue_custom_js');
function hyix_enqueue_custom_js() {
//enqueue zip-search-popup.js
wp_enqueue_script('zip-search-popup', get_stylesheet_directory_uri().'/js/zip-search-popup.js', array('jquery'), false, true);
wp_localize_script('zip-search-popup', 'from_php', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_ajax_zip_search', 'ajax_zip_search' );
add_action( 'wp_ajax_nopriv_zip_search', 'ajax_zip_search' );
function ajax_zip_search() {
$submitted_zip = $_REQUEST['submittedZip'];
// do some zip search
$response = array(
'request' => $_REQUEST,
'zip' => $submitted_zip,
'test' => 'is ok',
'foo' => 'bar'
);
wp_send_json( $response );
}
Now you can use the ajax_url provided by wp_localize_script(). Don't forget to send an action-parameter:
$.ajax({
url: from_php.ajax_url,
type: "GET",
data: {
action: 'zip_search',
submittedZip: submittedZip
},
success: function (response) {
console.log(response);
alert('it works');
}
});
This is my code:
[
'attribute' => 'status',
'value' => function ($model) {
return Html::dropDownList('status', ['10' => 'Active', '20' => 'Deactive']);
},
],
I just want dropdown in status column. If record is active or deactive it will be selected.
You need to use 'format' => 'raw' for the column options and your definition for the dropDownList() is wrong you need to have the selection string as the second parameter and the dropdown options as the third parameter. Change your code to below:
[
'attribute' => 'status',
'format' => 'raw',
'value' => function ($model) {
return Html::dropDownList('status', $model->status, ['10' => 'Active', '20' => 'Deactive']);
},
],
EDIT
You didnt had in the initial requirements that you waned to update the status too when the drop down is changed. You can bind ajax call to the drop-down.
Add the following javascript on top of your view where you are initializing the GridView.
NOTE: Change the url:'controller/update-status?id'+id in the ajax call to the relative controller where you want to update the status for the row, but dont remove the id
$js = <<<JS
$(document).on('ready pjax:success',function(){
$(".switch-status").on('change',function(){
var data={};
data[$(this).attr("name")]=$(this).val();
var id=$(this).closest("tr").data('key');
$.ajax({
method:'post',
url:'/controller/update-status?id='+id,
data:data,
success:function(data){
if(!data.success){
alert(data.message);
}else{
alert("Status updated.");
}
},
error:function(jqXHR, textStatus, errorThrown ){
alert(errorThrown);
}
});
});
});
JS;
$this->registerJs($js, yii\web\View::POS_END);
Then inside your GridView column for status change the dropdown to the following
return Html::dropDownList(Html::getInputName($model, 'active'), $model->active, [10 => 'Active', 20 => 'Deactive'], ['class' => 'switch-status']);
And the go to your controller and add the action code for updating the status
Note: Change the Model in the first line $model = Model::findOne($id); name with the respective model you are using.
public function actionUpdateStatus($id) {
$model = Affiliate::findOne($id);
$app = Yii::$app;
$request = $app->request;
if($request->IsAjax && $request->isPost) {
Yii::$app->response->format = Response::FORMAT_JSON;
if($model->load($request->post()) && $model->save()) {
return ['success' => true];
} else {
return [
'success' => false,
'message' => implode('<br />', ArrayHelper::getColumn($model->errors, '0'))
];
}
}
}
Use content property to render HTML elements. For example:
[
'attribute' => 'status',
'content' => function ($model) {
return Html::dropDownList('status', $model->status, ['10' => 'Active', '20' => 'Deactive']);
},
],
I am new in Yii framework, so I don't have much idea in it.
My question is, I want to get details of the company which is selected in a search box.
Code in my frontend/companies.php
<?= Html::SubmitButton( 'Get info', [ 'class' => 'btn btn-success' , 'id' =>'getinfo']) ?>
Here's my select2 widget code:-
$typeahead = Select2::widget([
'id' => 'front_companies_select',
'name' => 'state_10',
'data' => $companyNameList,
'options' => [
'placeholder' => 'Select ...',
'sigle' => true
],
]);
My js code:-
$("#getinfo").click(function(){
var obj = $("#front_companies_select option:selected").val();
console.log(obj);
});
If you want to get only company name you can try this.
$("#getinfo").click(function(){
var company_id = $("#front_companies_select option:selected").val();
console.log(company_id);
var companyName = $("#front_companies_select option:selected").text();
console.log(companyName); //here you can get company name
});
Or If you want to get whole company details then you have to call ajax like this.
$("#getinfo").click(function(){
var company_id = $("#front_companies_select option:selected").val();
$.ajax({
type: "POST",
url:"YOUR_URL/YOUR_FUNCTION_TO_GET_COMPANY_DETAILS",
data: {company_id:company_id},
dataType:'json',
async: false,
success: function (data)
{
console.log(data); //here you can get all the company details in object
}
});
});
**hello
i want to submit my form value with ajax
i have a modal in my view file
in modal i built a custom form to submit my data to a action**
<?php
use yii\bootstrap\Modal;
use yii\helpers\Html;
use yii\helpers\Url;
Modal::begin([
'header' => 'روز تخمینی برای اتمام پروژه انتخاب کنید',
'id' => 'modal-accept',
'size' => 'modal-sm',
'clientOptions' => [
'backdrop' => 'static',
'keyboard' => false,
],
]);
?>
<div id="modal-content">
<form method="post" action="<?= Url::to(['admin/site-developer/accept-task'])?>" id="modal_form">
<?php
echo jDate\DatePicker::widget([
'name' => 'datepicker',
'id' => 'estimate',
]);
?>
<?= Html::submitButton('submit',['class' => 'btn btn-sm btn-success']) ?>
</form>
</div>
<?php
Modal::end();
?>
for submit my value and get the result i used this function ,,, but when i click submit no ajax call will perform nothing will happening why i cant see any network activity in my browser inspect ...
$('#modal_form').on('beforeSubmit', function(e) {
var form = $(this);
var formData = form.serialize();
$.ajax({
url: form.attr("action"),
type: form.attr("method"),
data: formData,
success: function (data) {
console.log("successfull");
},
error: function () {
alert("Something went wrong");
}
});
}).on('submit', function(e){
e.preventDefault();
});
any suggestion?
You don't need to use before submsision, this is the problem
$('#modal_form').on('submit', function(e){
e.preventDefault();
var form = $(this);
var formData = form.serialize();
$.ajax({
url: form.attr("action"),
type: form.attr("method"),
data: formData,
success: function (data) {
console.log("successfull");
},
error: function () {
alert("Something went wrong");
}
});
return false;
});
When enableClientValidation is set to true, then yii2-pjax widget does not fire ajax. Only when enableClientValidation is set to false, pjax works here. Is there any way to have active form client side and ajax validations on each field ( by yii ) as well as pjax on submit button ( by pjax )
<?php Pjax::begin(['id'=> 'new-comment','enablePushState' => false]); ?>
<?php $form = ActiveForm::begin([
'id' => $model->formName(),
'options' => ['data-pjax' => "1"] ,
'action' => ['site/signup'],
'enableClientValidation' => true,
]);
?>
<?= Html::submitButton('REGISTER', ['class' => 'btn btn-primary', 'name' => 'signup-button', 'id'=>'register-btn']) ?>
</div>
<?php ActiveForm::end(); ?>
<?php Pjax::end(); ?
I had to remove Pjax calls in PHP around Active form since clientValidation would fail otherwise.
<?php $form = ActiveForm::begin([
"id"=>"CreateForm",
'enableClientValidation' => true,
//'enableAjaxValidation' => true,
'validationUrl'=>['site/form-validate'],
"options" => ["enctype" =>"multipart/form-data"]
]
); ?>
enableAjaxValidation can be made true as well above
Currently I have clientValidation as true without Pjax which is validating based on validationUrl. Submit button of form is handled externally in javascript that will firstly call same validationUrl and update error fields using updateMessages method of yii activeform. If no errors, then business logic is done in different action than validationUrl action
$.ajax({
url : encodeURI(baseUri + "site/form-validate"),
data : $("#CreateForm").serialize(),
dataType : 'json',
type : 'POST',
beforeSend : function(xhr, settings) {
$this.attr("disabled","disabled");
Pace.stop();
Pace.bar.render();
},
success : function(data) {
$('#CreateForm').yiiActiveForm("updateMessages", data);
if($("form#CreateForm").find('.has-error').length == 0) {
$.ajax({
url : encodeURI(baseUri + "site/form"),
data : $("#CreateForm").serialize(),
dataType : 'json',
type : 'POST',
beforeSend : function(xhr, settings) {
},
success : function(data) {
console.log(data);
},
error : function(data) {
},
complete : function() {
$this.removeAttr("disabled");
Pace.stop();
},
});
} else {
$this.removeAttr("disabled");
Pace.stop();
}
},
error : function(data) {
},
complete : function() {
},
});
Controller -
public function actionFormValidate() {
$model = new CreateForm();
if(Yii::$app->request->isAjax && $model->load($_POST))
{
Yii::$app->response->format = 'json';
return \yii\widgets\ActiveForm::validate($model);
}
}