I've created action onClick in GridView and it redirects me to an action in controller.
Code in Index.php:
},
'rowOptions' => function ($model, $key, $index, $grid) {
return ['id' => $model['id'], 'onclick' => 'var myid=this.id; var enteredValue = prompt("Please enter a number");
window.location.href = "index.php?r=patientservices%2Fpassing" + "&id=myid, " + enteredValue; '];
},
In my Controller code:
public function actionPassing($id,$price)
{
$ser= $this->findModel($id);
$model = new Receipts();
$countclinic=Receipts::find()
->where(['patient_services_id'=>$id])
->count();
if ($countclinic== 0) {
$model->patient_id=$ser->patient_id;
$model->price=$price; // the price that i need to pass
$model->doctor_id=$ser->doctor_id;
$model->patient_services_id=$ser->id;
$model->reg_date=DATE('y-m-d h:m:s');
$model->description='دفعة تحت الحساب';
$model->userin = \Yii::$app->user->identity->id ;
$model->save();
$models = $this->findModel($id);
$models->state=2;
$models->save();
JS Code :
$this->registerJs("
$('.custom_button').on('click', function() {
alert(id);
var enteredValue = prompt('Please enter a number');
if (enteredValue != null) {
window.location.href = 'index.php?r=patientservices%2Fpassing' + '&id=, ' + enteredValue;
}
});
");
What I need is:
When the user clicks on the Row in GridView a prompt text appears for the user and the number inserted in the prompt text is passed with the ID to controller to use it there but the js code pass the id as a character not like number
$model->price=$ser->price;
Here's how you can do it:
Instead of using link, use # as a link since you don't want to redirect user just yet.
After user clicks on button, you want to "summon" a prompt. This can be achieved by JavaScript/jQuery only.
Inside the JavaScript/jQuery code you can insert PHP code, too, and form an URL.
For example (in GridView):
'buttons' => [
'passing' => function () {
return Html::a('Content', '#', [
'class' => 'btn btn-primary custom_button',
'title' => 'تسجيل القيمة كـ إيصال',
]);
},
],
Then at the end of file:
$this->registerJs("
$('.custom_button').on('click', function() {
var enteredValue = prompt('Please enter a number');
if (enteredValue != null) {
window.location.href = '".$url."' + '&id= ' + enteredValue;
}
});
");
Worth to note I have included a class custom_button since we want to know if the button user clicked is the correct one, not any.
Related
I am creating a form that asks for email and password and validates it. If it has any error, it pops on the same line. Below is my javascript code for it. When I fill the form and hit submit, the values get reset. Moreover, I do not see anything in the console. I tried using a random code console.log('Hanee') to test my code but nothing gets generated in the console tab. Could anyone tell me what's the issue here?
Also, here's the link to my login form: http://www2.cs.uregina.ca/~hsb833/215a/login.html
document.getElementById("login-form").addEventListener("submit",validateLogin,false);
function validateLogin(event){
var elements = event.currentTarget;
var emailValue = elements[0].value;
var passValue = elements[1].value;
checkEmail(emailValue);
checkPass(passValue);
}
function checkEmail(emailValue){
var regex_email = /^[/w]+#[a-zA-Z]+?\.[a-zA-Z]{2,3}$/;
var index = emailValue.search(regex_email);
var errorEmail = document.getElementById("errorEmail");
var valid = true;
console.log('Hanee');
if(index != 0){
errorEmail.style.display = 'inline';
}
}
function checkPass(passValue){
var password = document.getElementById("password");
var regex_pass = /[\w]+\S/;
var index = passValue.search(regex_pass);
if(passValue.length < 6){
console.log('password is invalid. Minimum length is 6');
errorPassLen.style.display = 'inline';
}
if(index != 0){
console.log('password is invalid. Please make sure there is no spaces in between');
errorPassFormat.style.display = 'inline';
}
}
form is refreshed after being submitted by default. To prevent that, use event.preventDefault(); in your validateLogin
Here is an example of a form with a username and password, maybe it will suit you and you can customize it for your needs
async function tebeFxhr() {
let logfil = 1;
let sotebe= false;
let tes =(logt) => {
return /^[a-zA-Z0-9]+$/ui.test(logt);
}
tes(gtebe)==true ? logfil++ : alert('Login cannot contain characters or spaces')
let textrf =(rutext) => {
return /[а-я]/i.test(rutext);
}
textrf(stebe)==true ? alert('The password cannot contain Cyrillic characters') : logfil++;
stebe.length < 8 ? alert('Password is very short') : logfil++;
stebe===ftebe ? logfil++ : alert('Enter the password 2 times so that they match')
if (logfil === 5){
const data = {data_0:gtebe, data_1:stebe, data_2:ftebe};
const response = await fetch("/form", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then((response) => {
return response.text();
})
.then((sotebe) => {
console.log(sotebe)
if(sotebe==='error-1'){
console.log('error-1')
}
else{
sotebe =='' ? location.replace("../") : alert(sotebe)
}
});
}
}
When submit event is triggered, all values are sent to server and get reset. If you want to prevent this, use event.preventDefault(); inside the event handling function validateLogin(event). Then, the values are not going to be reset!
Still If you want your values to be empty after submission, try below.
elements.forEach(e => e.value = '');
I have an AJAX request which serializes form data and sends it to a database. When teh data is serialised, I see it renders the full text inout, but when it stores it in the database, it only saves the first letter of every word?
For example it will serialize this to be sent:
splashText=Silver Glaze
but the database will save if there is none line:
S
if there are multiple rows in the submitted table data is captured in the database as follows:
row 1 would = S
row 2 would = i
Where as I'm trying to get it as follows:
row 1 would = Silver Glaze
row 2 would = Next option selected in the row and so on...
The serialised data POSTed is as follows (with 2 rows):
job_ref=3123&job_desciption=321&sil_cost=1&sil_cost_price=2.00&sub_total=119.75&item_name%5B%5D=1&item_quantity%5B%5D=1&item_unit%5B%5D=1&item_glass%5B%5D=110&item_splash%5B%5D=20&item_colour%5B%5D=-&item_HQuan%5B%5D=1&item_HDiam%5B%5D=2.25&item_CQuan%5B%5D=1&item_Total%5B%5D=56.25&item_cil_row%5B%5D=0.000001&item_name%5B%5D=1&item_quantity%5B%5D=1&item_unit%5B%5D=1&item_glass%5B%5D=110&item_splash%5B%5D=20&item_colour%5B%5D=-&item_HQuan%5B%5D=1&item_HDiam%5B%5D=7.5&item_CQuan%5B%5D=1&item_Total%5B%5D=61.50&item_cil_row%5B%5D=0.000001&glassText=6mm Toughened Extra Clear6mm Toughened Extra Clear&splashText=Rainbow SparkleRainbow Sparkle&holeText=22mm27mm
The code to serialise the form:
var form_data = $(this).serialize() + '&glassText=' + $('.item_glass').children("option").filter(":selected").text() + '&splashText=' + $('.item_splash').children("option").filter(":selected").text() + '&holeText=' + $('.item_HDiam').children("option").filter(":selected").text();
The + is for getting the text value of the input instead of the value. I think this may be the problem but im not sure how to fix it?
PHP Post:
for($count = 0; $count < count($_POST["item_name"]); $count++)
{
$query = "INSERT INTO tbl_order_items
(order_id, item_name, item_quantity, item_unit,item_glass, item_splash, item_HQuan,item_HDiam,item_CQuan,item_colour,item_total,user_id)
VALUES (:order_id, :item_name, :item_quantity, :item_unit,:item_glass,:item_splash,:item_HQuan,:item_HDiam,:item_CQuan,:item_colour,:item_total,:user_id)";
$statement = $connect->prepare($query);
$statement->execute(
array(
':order_id' => $order_id,
':item_name' => $_POST["item_name"][$count],
':item_quantity' => $_POST["item_quantity"][$count],
':item_unit' => $_POST["item_unit"][$count],
':item_glass' => $_POST["glassText"][$count],
':item_splash' => $_POST["splashText"][$count],
':item_HQuan' => $_POST["item_HQuan"][$count],
':item_HDiam' => $_POST["holeText"][$count],
':item_CQuan' => $_POST["item_CQuan"][$count],
':item_colour' => $_POST["item_colour"][$count],
':item_total' => $_POST["item_Total"][$count],
':user_id' => $user_id
)
);
}
$result = $statement->fetchAll();
if(isset($result))
{
echo 'ok';
}
}
It is a dynamic table being saved. Thats what the count is.
To put context on the dynamic table here is a screenshot:
:
Because you don't provide the html code, so I assume the 'Review Quote' button is the submit button. So, try this:
change from
var form_data = $(this).serialize() + '&glassText=' + $('.item_glass').children("option").filter(":selected").text() + '&splashText=' + $('.item_splash').children("option").filter(":selected").text() + '&holeText=' + $('.item_HDiam').children("option").filter(":selected").text()
To:
var glassText = '';
$('.item_glass').each(function(){
glassText+='&glassText[]='+$(this).find(":selected").text().replace(' ','+');
});
var splashText = '';
$('.item_splash').each(function(){
splashText+='&splashText[]='+$(this).find(":selected").text().replace(' ','+');
});
var holeText = '';
$('.item_HDiam').each(function(){
holeText+='&holeText[]='+$(this).find(":selected").text().replace(' ','+');
});
var form_data = $(this).serialize() + glassText + splashText + holeText;
If my URL is any of these type:
domain.com/page.html?refer=whatsapp
domain.com/page.html#whatsapp
Then I want to show a dialogue that shows "You have been referred from Whatsapp".
And if the url is accessed without the whatsapp part, then it must not show the dialoge box.
What I have tried is:
<script type="text/javascript">
var url = window.location.href;
if (url.search("#wa") >= 0) {
//found it, now do something
}
alert("Good Afternoon");
} else {
null //if not just do nothing
}
</script>
But no luck.
It helps you
var url = window.location.href;
// For example. In real app remove it
url = 'http://website.com/page.html#whatsapp';
// Search our #ID
var source = url.substring(url.lastIndexOf('#') + 1);
// For salutation text
var salutation = null;
// Iterate variants
switch ( source ) {
case 'whatsapp' : salutation = 'You have been referred from Whatsapp'; break;
default : salutation = 'unknown website';
}
alert ( salutation );
I'm working on a website.
I have index.html page with div container and I load all the other pages into this div.
I have window.onhashchange function that refreshes the page on url change and loads corresponding html file into that div
I have javascript/ajax contact form.
Problem:
When I click "submit" I expect success or error message to change class and appear under my form. However, "submit" button adds "?" to my URL and, consequently, my page refreshes and all the elements load with default classes.
Question: How can I prevent my "submit" button from adding "?" to my URL? Or am I doing it all wrong?
Codes are shown below:
submit function in my .js file:
$(".form-horizontal").submit(function (e) {
e.preventDefault();
var fname = $("#first-name").val();
var lname = $("#last-name").val();
var email = $("#email").val();
var subject = $("#subject").val();
var message = $("#message").val();
var dataString = 'fname=' + fname + 'lname=' + lname + '&email=' + email + '&subject=' + subject + '&message=' + message;
function isValidEmail(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
if (isValidEmail(email) && (message.length > 1) && (fname.length > 1)) {
$.ajax({
type: "POST",
url: "sendmail.php",
data: dataString,
success: function () {
$('.contact-success').fadeIn(1000);
$('.contact-error').fadeOut(500);
}
});
} else {
$('.contact-error').fadeIn(1000);
$('.contact-success').fadeOut(500);
}
return false;
});
php file:
<?php
// Email Submit
// Note: filter_var() requires PHP >= 5.2.0
if ( isset($_POST['email']) && isset($_POST['fname']) && isset($_POST['lname']) && isset($_POST['subject']) && isset($_POST['message']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) {
// detect & prevent header injections
$test = "/(content-type|bcc:|cc:|to:)/i";
foreach ( $_POST as $key => $val ) {
if ( preg_match( $test, $val ) ) {
exit;
}
}
//
mail( "email#domain.com", $_POST['subject'], $_POST['message'], "From:" . $_POST['email'] );
}
?>
Update:
Thank you very much for suggestions in the comments!
Errors that I get on submit. I also get them on some of my pages.
I checked, it is wrapped in $(document).ready(function().
Form does have class <form class="form-horizontal" role="form">.
In case I won't be able to figure it out, I guess I'll just create separate "Thank you for submitting your message" page. Kind of workaround ))
does element exist when code is run? - need to think more about it! I'll check!
So i am creating a simple form that checks whether or not the value that the user is inputting exists or not in my DB using jQuery. Everything up until now is working so far however i find myself stuck at this next part.
To easily explain i will just show an example of what i am trying to achieve.
For this example i will be "weeden"
weeden has an ID of 255 in the company table of my database.
If the user types in "weeden" into the client field
To the right of the client field (on the web form), the text "weeden is unavailable" will appear
what i would like to have happen instead is this: "ID 255 is unavailable"
Here is the relevant code.
HTML FORM
<form action="addrecord.php" method="post" autocomplete="off"/>
<div class="form-field">
<label for="client">Client: </label>
<input type="text" name="client" id="client" class="check-exists" data-type="client" placeholder="#">
<span class="check-exists-feedback" data-type="client"></span>
</div>
jQuery Function
$.fn.existsChecker = function(){
return this.each(function(){
var interval;
$(this).on('keyup', function(){
var self = $(this),
selfType = self.data('type'),
selfValue,
feedback = $('.check-exists-feedback[data-type=' + selfType + ']');
if(interval === undefined){
interval = setInterval(function(){
if(selfValue !== self.val()){
selfValue = self.val();
if(selfValue.length >= 1){
$.ajax({
url: 'check.php',
type: 'get',
dataType: 'json',
data: {
type: selfType,
value: selfValue
},
success: function(data){
if(data.exists !== undefined){
if (data.exists === true){
feedback.text(selfValue + ' is already taken.');
}else {
feedback.text(selfValue + ' is available');
}
}
},
error: function(){
}
});
}
}
}, 1000);
}
});
});
};
Check.php
$db= new PDO('mysql:host=host;dbname=mydb', 'user', 'pass');
if(isset($_GET['type'], $_GET['value'])){
$type = strtolower(trim($_GET['type']));
$value= trim($_GET['value']);
$output = array('exists' => false);
if(in_array($type,
array('client')
)
){
switch($type){
case 'client':
$check = $db->prepare("
SELECT COUNT(*) AS count
FROM company
WHERE name = :value
");
break;
$check->execute(array('value'=> $value));
$output['exists'] = $check->fetchObject()->count ? true: false;
echo json_encode($output);
Any help/suggestions would be greatly appreciated. I consider myself a beginner, this is my first time working on a web project.
Just to clarify ahead of time, there are many other input fields on the same webform such as: email, date, first, last, etc.
I hope my question was clear enough. Thank you
You have to change your Query to something like this:
$check = $db->prepare("
SELECT id, COUNT(*) AS count
FROM company
WHERE name = :value
");
I assume that your primary key field on the company-table is named id.
And finally store the id in the output-Array
$result = $check->fetchObject();
$output['exists'] = $result->count ? true: false;
$output['id'] = $result->id;
Then you can output the id like so:
if (data.exists === true){
feedback.text('ID ' + data.id + ' is unavailable');
}
You can handle everything in query
$db= new PDO('mysql:host=host;dbname=mydb', 'user', 'pass');
if(isset($_GET['type'], $_GET['value'])){
$type = strtolower(trim($_GET['type']));
$value= trim($_GET['value']);
$output = array('exists' => false);
if(in_array($type,array('client'))){
switch($type){
case 'client':
$check = $db->prepare("
SELECT (CASE WHEN(COUNT(id)>0) THEN id ELSE FALSE END) AS count
FROM company WHERE name = :value ");
break;
}
$check->execute(array('value'=> $value));
$output['exists'] = $check->fetchObject()->count ? true: false;
echo json_encode($output);
}
In Ajax success
if(data.exists !== undefined){
if (!data.exists){
feedback.text(selfValue + ' is already taken.');
}else {
feedback.text(selfValue + ' is already taken.');
}
}