How do I pass JavaScript variables to PHP in yii2? - javascript

I am developing a recriment software and in Yii2 framework application form I want to check if applicant has already applied for same job using 'passport no', my form looks like
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'cnic')->textInput(['type' => 'number']) ?>
<?= Html::submitButton('Save and Continue', ['class' => 'btn btn-success']) ?>
<?php ActiveForm::end(); ?>
and I am unable to get the cnic value in php. my Javascript code is.
$('#applications-cnic').change(function(){
var data = $(this).val();
var validation = <?= $model->checkCNIC($postid, '<script>data</script>'?>. <?= ) ?>;
alert(validation);
if (validation == 'data_exist') {
alert("You have already applied for this job, use your tracking ID to check your applicaiton or contact HR");
}
});
it is not working and I am unable to pass this value I get from javascript to my php function.
public function checkCNIC($value , $cnic)
{
$query= Applications::find()
->where(['post_id' => $value])
->andWhere(['cnic' => $cnic])
->all();
if ($query) {
return 'data_exist';
}
else
return 'no_data';
}

Ajax is the recommended solution. You can still use javascript inside php using document.writeln
'<script>document.writeln(data)</script>`

Related

Yii2: How to get default form name?

I have a view with a simple form:
<?php $form = ActiveForm::begin(); ?>
...
<?php ActiveForm::end(); ?>
I need to know the default name of the form. I tried using JavaScript, jQuery or even PHP but I don't know ho to get it.
if the active form is created by gii by default Yii2 don't assign name but assign id tipically
id="w0"
If you need you could assign values using options
$form = ActiveForm::begin([
'id' => 'your-id-form',
'options' => ['class' => 'form-horizontal', 'name' => 'your-name],
]) ?>
http://www.yiiframework.com/doc-2.0/yii-bootstrap-activeform.html
http://www.yiiframework.com/doc-2.0/guide-input-forms.html
In jquery you can do this
$('form').prop('id');

How to change files so that when you click on the "load more" button the browser dynamically adds the following entries from the database in the list

How to change files so that when you click on the "load more" button the browser dynamically adds the following entries from the database in the list
index.php
<?php
include('pdo.php');
include('item.php');
include('loadMore.php');
?>
<div id="container">
<?php foreach ($items as $item): ?>
<div class="single-item" data-id="<?= $item->id ?>">
<?= $item->show() ?>
</div>
<?php endforeach; ?>
</div>
<button id="loadMore">Загрузить ещё...</button>
<script src="/jquery-1.11.3.min.js"></script>
<script src="/script.js"></script>
item.php
<?php
class Item
{
public $id;
public $text;
function __construct($id = null, $text = null)
{
$this->id = $id;
$this->text = $text;
}
public function show()
{
return $this->text;
}
}
loadmore.php
<?php
$offset = 0;
$limit = 10;
$statement = $pdo->prepare('SELECT * FROM credit LIMIT ?, ?');
$statement->bindValue(1, $offset, PDO::PARAM_INT);
$statement->bindValue(2, $limit, PDO::PARAM_INT);
$statement->execute();
$data = $statement->fetchAll();
$items = [];
foreach ($data as $item)
{
$items[] = new Item($item['id'], $item['tel']);
}
pdo.php
<?php
$host = '127.0.0.1';
$db = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);
script.js
function getMoreItems() {
var url = "/loadMore.php";
var data = {
//
};
$.ajax({
url: url,
data: data,
type: 'get',
success: function (res) {
//
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//
}
});
}
How to change files so that when you click on the "load more" button the browser dynamically adds the following entries from the database in the list
I think 2 hours and I can not understand.
Help.(
I understand your confusion, I believe you're wondering why your php code in index.php doesn't work properly after you call loadMore.php using ajax.
There's one distinction you need to understand to be capable of developing for the web. The difference between server-side and client-side code.
PHP is a server-side programming language, which means that it only executes on the server. Your server returns html, or json, or text, or anything to the browser and once the response arrives at the browser, you can forget about php code.
Javascript on the other hand is a client side programming language (at least in your case) It executes on the browser.
You basically have two options:
To send back some json and loop over it using jQuery, which is the preferable choice, but I fear it requires more work.
Send back html and append it to your page, first create a file called async.php
<?php
include('pdo.php');
include('item.php');
include('loadMore.php');
?>
<?php foreach ($items as $item): ?>
<div class="single-item" data-id="<?= $item->id ?>">
<?= $item->show() ?>
</div>
<?php endforeach; ?>
in your js add to your success callback
$.ajax({
url: url,
data: data,
type: 'get',
success: function (res) {
$('#container').append(res);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//
}
});
don't forget var url = "async.php";
First you need to attach the buttons onclick="" attribute with the ajax-method.
<button ... onclick="getMoreItems">...</button>
Second, your loadmore.php need to require_once the files it depends on:
require_once('pdo.php');
require_once('item.php');
Third, separate your logic for querying the database to a function in the pdo.php file you can call with the limits as parameters, i.e.
function getData($offset = 0, $limit = 10){
//logic
}
You should also always try to use require_once or include_once to be sure files aren't loaded several times.
Now you can call the function getData(...) from index.php before the container div to load up the initial data, remove the include to loadmore.php from index.php, and in loadmore.php write the logic to use the parameters sent from the webpage to get the next chunk of data.
The data:... in your ajax needs to pass along the "page" it wants to get, perhaps simply a counter as to how many times you have loaded more. In the loadmore.php script you then just multiply the page by the limit to get the offset.
Return the data as JSON to the ajax, parse the JSON so you can build a new div for each item, then add each div to the container-div using javascript.
Im not going in detail on all topics here, but you at least will know what tutorials to search for on google :)

How to pass a PHP variable into a Javascript cookie on submit of form?

I am setting up a custom form to be used in my wordpress site. What I would like to do is grab the AUTO_INCREMENT ID of that submission and pass it into a Javascript cookie when the form is submitted. Currently the ID is working, but because the ID isn't grabbed until after the form is submitted, I'm having trouble figuring out how I can pass the variable into the cookie immediately after the form has been submitted(currently I have to submit the form twice before the cookie with the ID is created, and its 1 number lower than it should be since it's a submission behind).
Here's what I have currently:
<?php
if(isset($_POST["submit"])) {
$name = $_POST['full_name'];
$city = $_POST['city'];
$state = $_POST['state'];
$email = $_POST['email'];
$wpdb->insert(
'reps',
array(
'name' => stripslashes($name),
'city' => stripslashes($city),
'state' => stripslashes($state),
'email' => stripslashes($email)
)
);
$lastid = $wpdb->insert_id;
}
?>
<script>
$('#dealer-form').submit(function() {
var repID = '<?php echo $lastid ?>';
setCookie('ID', repID);
});
</script>
As I mentioned this code works on the second submission(since the variable has no value on the first submission), and the ID is 1 number behind because it is grabbing the ID of the previous submission before reassigning the variable value.
PHP, being a server-side scripting language, is executed before the data is sent to your browser. JavaScript, a client-side scripting language, is executed as soon as the script is encountered by the browser.
Your approach is forgetting this separation between front- and back-end.
To accomplish what you're trying to do, simply output the setCookie call when you've submitted your form in php:
<?php
if(isset($_POST["submit"])) {
$name = $_POST['full_name'];
$city = $_POST['city'];
$state = $_POST['state'];
$email = $_POST['email'];
$wpdb->insert(
'reps',
array(
'name' => stripslashes($name),
'city' => stripslashes($city),
'state' => stripslashes($state),
'email' => stripslashes($email)
)
);
$lastid = $wpdb->insert_id;
printf( '<script>setCookie("ID", %d);</script>', $lastid );
}
?>

Yii value from javascript

i need to get the value of a variable in a javascript function to put it in a textfiled.
Javascripts function:
function obtenerArrendatario(){
arrendatario_id = $.fn.yiiGridView.getSelection('arrendatario');
alert(arrendatario_id);
}
The alert give me the id of the selected row but i need to put the id in the textfield to save/create the form
Gridview
<div class="row">
<?php echo $form->labelEx($model,'zf_arrendatarios_arrendatario_id'); ?>
<?php
$arrendatarios = new ZfArrendatarios;
$this->widget('bootstrap.widgets.TbGridView',
array(
'id'=>'arrendatario',
'selectableRows'=>1,
'selectionChanged'=>'obtenerArrendatario',
'type'=>'striped bordered condensed',
'dataProvider'=>$arrendatarios->search(),
'filter' => $arrendatarios,
'template'=>"{items}\n{pager}",
'columns'=>array(
array('name'=>'arrendatario_id_personal', 'header'=>'DNI',),
array('name'=>'arrendatario_nombre', 'header'=>'Nombre'),
array('name'=>'arrendatario_email', 'header'=>'Email'),
),
));
?>
<?php
echo $form->textfield($model,'zf_arrendatarios_arrendatario_id',array('class'=>'input input_r input_pryk', 'value'=>$arrendatario));
?>
<?php echo $form->error($model,'zf_arrendatarios_arrendatario_id'); ?>
</div>
So i need that id that the function capture to fill my textfield.
I tried
$arrendatario= "<script> document.write(arrrendatario_id) </script>";
But it print me the string not the value.
For your requirement, you can set the textfield value in below js function
function obtenerArrendatario(){
arrendatario_id = $.fn.yiiGridView.getSelection('arrendatario');
$(".input_pryk").val(arrendatario_id );// input_pryk should be class for this text field alone.
}
Then you will get in controller while submitting the form.

cakephp form not submitted correctly after JS added a new field

The View
<?php echo $this->Form->create('Practice');
echo $this->Form->input('title',array('value'=>'test value'));
echo $this->Js->submit('Ajax Submit', array(
'update' => '#left',
'url'=>'/practices/content',
'async' => true,
'method' => 'post',
'dataExpression'=>true,
'data'=> $this->Js->serializeForm(array(
'isForm' => true,
'inline' => true
))
));
?> <?php echo $this->Form->end(); ?>
the form works fine before the Ajax submit. the ajax submit actually return a new form field of the same model. below is the view of which the form is being sent firstly for ajax
echo $this->Form->input('Practice.options',array('value'=>'regex value'));
the new field value is not being submit with the form
I was doing two mistakes first the new ajax returned fields were not inside form tag second I needed to bypass the cakephp security check
function beforeFilter() {
parent::beforeFilter();
$this->Security->blackHoleCallback = 'blackhole';
$this->Security->csrfCheck = false;
$this->Security->validatePost = false;
$this->set('contentLayout', 'admin_dashboard');
}
Make sure that your put at the end of your form
<?php echo $this->Form->end(); ?>
and you unlock the current action for the SecurityComponent

Categories