Search in mysql by Javascript - javascript

Good morning , I'm trying to do a check if the cpf entered already exists in the database , I'm using laravel , someone could help me in this function please ?
In my controller I seek and I list all cpfs in bank :
$cpfduplicado = UsuarioEsic::lists('doc', 'id')->all();
foreach ($cpfduplicado as $cpf)
if ($cpf == $request->cpf)
$cpf = 'verdadeiro';
// return redirect('/Esic/CadastroFisica');
return redirect('/Esic/Sucesso');
I'm not sure how to make a function in javascript to get this data and set a custom browser validity , I did something like this:
$(function cpfdupli(input) {
$('.btnCadastroo').on('click', function (json){
if (json.cpf === 'verdadeiro'){
document.getElementById('cpff');
input.setCustomValidity('Cpf já existe.');
} else {
input.setCustomValidity('');
}
});
});
I am beginner in the field and do not really know how to do this work, I just wanted the cpf existed already setasse one CustomValidity in the browser and not let him continue with the registration , if anyone can help me or give me other ways of how solve this I would be very grateful!
PS: Any questions about the code will be available to provide.

ok i will attempt to try and do what your looking for:
Say the html input is something like:
<input type="text" value="" id="cpff" />
Then we have some js to get the details within the above input box, the below does this on each lette typed into the input so its constantly checking as the user types then giving a visual reposnse as the user types so they now if its taken or not as typing:
$('input#cpff').on('keyup', function(evt){
//-- get for value on keyup
var inputValue = this.value;
//-- call to the controller to check
$.ajax({
url : '/check/cpff/',
type: 'POST',
data {cpffValue : inputValue},
success : function(res){
console.log(res);
if(res === 'succcess'){
//-- output a tick icon to let the user know all is ok so far
} else {
//-- output an red x to sai no its been used
}
},
error : function(msg, x){
console.log(msg);
}
})
});
So for each letter typed in the input box the code sends the value to the route /check/cpff and then this returns a boolean / string back to see if its ok or not, hopefully your still with me?
Route:
Route::post('/check/cpff', ['uses' => 'ControllerName#checkCPFF']);
Controller
Class ControllerName extends Controller {
public function checkCPFF(Request $request){
//-- get the ajax data variable -- cpffValue
$formValue = $request->get('cpffValue');
//-- lets chec to see if we have an entry with those values
$doesItExsist = ModelName::where('field_name',$formValue);
//-- if we have a result from the DB then return not allowed
return ($doesItExsist) ? 'not-allowed' : 'allowed'
}
}
SO the above controller takes the data value that the form submits, then checks the required db table and does a search for that value, if it cannot then the user has a valid entry if there is a value found then the user must change their entry etc
its a bit crude and i have nothing to test this with etc so might / will need better working / writing to work as such, you can always change the js to do the same on submitting the form instead etc,
here is a link to test out the input section. to veiw the result open the console up so you can see the values being typed. Example of keyup
i hope it gives your a sort of starting base for help...

Related

Odoo 12 : How to pop up a message when "Save" button is clicked on sale.order model?

It has been 3 hours that I'm stuck.
I want to show up a pop up (a non-blocking one) when my condition is meet (_some field is equal something) while the user click the button "Save"on form view of record on sale.order model (only).The pop up should be triggered after the Save button peformed its default action because I need to check if the condition is meet in database.
I find here how to get a model.Models from javascript in Odoo.
I also find that I need to override the o_form_button_edit to make my change, but I don't know how to do that and I don't know if it has effect to other model because others use it.
this.$buttons.on('click', '.o_form_button_edit', this._onEdit.bind(this));
I wonder if my method is good to do that? If not can you suggest another one?
Can you help me? Thank you very much.
PS : I need a pop up because the user can Accept his change or Discard it when saving the record. If discard, I need to re-open o_form_button_edit if not, we do nothing because we already call the write method.
Here is a code snippet doing what you want:
var FormController = require('web.FormController');
var ExtendFormController = FormController.include({
saveRecord: function () {
var res = this._super.apply(this, arguments);
if(this.modelName == 'project.task'){
var self = this;
res.then(function(changedFields){
console.log(changedFields);
console.log(self.modelName);
self.do_notify('title', 'message');
// you can call a method on the server like this
self._rpc({
model: self.modelName,
method: 'search_read',
fields: ['name'],
context: self.context,
}).then(function(result){
console.log('rpc result');
console.log(result);
})
});
}
return res;
}
});
A screenshot just after I clicked Save:
You also need to inherit the createRecord() method the same way.
A few notes:
the first console log line saying: ["name"] is the value of changedFields (I only changed the name of the task before hitting Save)
I was working on the project.task object but you can change that to sale.order :)
The official documentation is very helpful

How to detect Event Listeners and their actions on input fields

I have purchased a booking plugin (wordpress) to add to a site.
https://wpamelia.com/
I cannot show the site I am working on, but here a demo from plugin developers
https://sports.wpamelia.com/#book
Once you have chosen your date and time, you end up on a form with input fields.
I was able to pre-fill this form with data that I could pass via the URL.
My URL would look something like this: https://sports.wpamelia.com/?first=Jim&last=Tester&email=something%40something.com&phone=0222222222#book
But here is the problem:
Even though I managed to use jQuery to pre-fill the input fields of the form, as soon as I click confirm the fields' content is erased and the error "Please enter... " appears for each of them.
So again:
STEP 1: I open the booking page with an URL containing data in the query string
STEP 2: Using jQuery, I manage to pre-fill the form that appears after having chosen date and time (first name, last name ...)
STEP 3: I click "Confirm"
RESULT: all the fields are empty and for each one the error message "Please enter first name" (etc..) appears
I've messaged the plugin developers. Only answer was that there is indeed no functionality to take the data from the Query String into the form fields yet.
MY QUESTIONS:
1) How could I find out, with chrome inspector or other tools, why exactly the content I pre-fill into the form is ignored?
---> I've tried things like getEventListeners in the chrome inpector's console, but I don't really see how to get information out of that
2) Would anyone know what the issue is and/or how I could bypass it?
---> there is a lot of javascript from the plugin developers behind that and something is expecting manual entering of the data into the fields...
---> but even when trying to fake manual entering with things like $(this).trigger("change").val(function(i,val){return 'aaaa';}); this didn't solve the problem....
(If anyone is interested, I can post later my javascript/jQuery functionality to get the form fields pre-filled with data from Query String... interesting code as you have to wait until the fields appear for jQuery to recognise them..)
Thanks so much for any help!
cheers
Admino
#Admino - this may not be the best solution and I know this is an old question so you may not need it now but after not finding a better one it at least worked for me.
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
function valueOutput(element) {
element.dispatchEvent(new Event('input'));
}
jQuery(function() {
jQuery(document).on('change', 'input', function(e) {
valueOutput(e.target);
});
// you may want to perform more validations here if needed
// just checking here if email is present (but not checking for valid email address)
var fname = getUrlVars()["first"];
var lname = getUrlVars()["last"];
var email = getUrlVars()["email"];
var phone = getUrlVars()["phone"];
var custom1 = getUrlVars()["custom1"]; // you know this field label is Order Number
if (email.length > 0) {
// run an interval until the elements are present on the page (form displayed)
var checkInputs = setInterval(function() {
if (jQuery('.amelia-app-booking label[for="customer.email"]').length > 0) {
var em = jQuery('.amelia-app-booking label[for="customer.email"]').closest('.el-form-item').find('.el-input__inner');
// this checks to see if an Amelia customer is already present
if (em.val() == '') {
em.prop('value', email).val(email).trigger('change');
jQuery('.amelia-app-booking label[for="customer.firstName"]').closest('.el-form-item').find('.el-input__inner').prop('value', fname).val(fname).trigger('change');
jQuery('.amelia-app-booking label[for="customer.lastName"]').closest('.el-form-item').find('.el-input__inner').prop('value', lame).val(lame).trigger('change');
jQuery('.amelia-app-booking label[for="customer.phone"]').closest('.el-form-item').find('.el-input-group__prepend').siblings('.el-input__inner').prop('value', phone).val(phone).trigger('change');
}
// for custom fields I check the label text to find the correct input
if (custom1 != '') {
jQuery('.amelia-app-booking label:contains("Order Number")').closest('.el-form-item').find('.el-input__inner').prop('value', custom1).val(custom1).trigger('change');
}
// form info is updated so clear the interval
clearInterval(checkInputs);
}
}, 500);
}
});
You may want to try a different method than url params to sync this info so it's not so public in the url string. This code may not need both the prop and val jquery setters but I just left them for you to try. Hope it helps (and to others I'm open to a better solution)!

Capturing and processing data as soon as it is entered

Looking for your suggestion on a good way to handle the below.
Need a fast input form for a receive scan webform app. This will be collecting barcodes scanned off of packages one right after another.
the scans will be coming in from a bluetooth scanner into a input field.
after the scan the scanner will insert a CR.
At that point I just want to capture the data and pass it onto a controller for processing, clear the field and return control immediately back to the webpage for the next scan.
The biggest two problems are:
Speed – it has to be fast as they are doing real time scanning.
Keeping the input field the focus all the time so that when they
scan they are not in some other field on the screen. They will start off in the input field, I just need to make sure they go right back to it after each scan automatically.
Any thoughts on how you would best handle?
Here is my HTML:
<input type="text"
id="barcode"
name="barcode"
value=""
onchange="location.href='#Url.Action("scanned", "receiveScan")?barcode=' + $('#barcode').val()"><br>
And this is the controller action:
public ActionResult scanned(string barcode)
{
//code to process goes here
return Ok();
}
Afterwards it resets the webpage to a blank page.
Instead what I need to do is just blank the input field and put the focus back to it.
I do have it working by modifying the controller to be:
public ActionResult scanned(string barcode)
{
var test = barcode;
//code to process goes here
return RedirectToAction("receiveScan", "home");
}
But it has been pointed out that reposting the entire page is not a good idea.
I will try one of the solutions below as soon as I can get back to it.
Thanks for the help, here is the code that worked --
$('#textArea1').val('Scans - ');
$(function () {
$("#barcode").on("change", function (e) {
// get the current value
var barcode = $('#barcode').val();
// if there's no text, ignore the event
if (!barcode) {
return;
}
// clear the textbox
$("#barcode").val("");
// var holdit = $('#textArea1').val();
$('#textArea1').val($('#textArea1').val() +' '+ barcode);
// post the data using AJAX
$.post('#Url.Action("scanned", "receiveScan")?barcode=' + barcode);
});
})
Instead of performing a full postback, you should be using an AJAX call to ensure that the page is not completely reloaded.
Here's an example of how you could do this (untested, might have typos):
<input type="text" id="barcode" name="barcode"/>
$(function()
{
$("#barcode").on("change", function (e)
{
// get the current value
var barcode = $('#barcode').val();
// if there's no text, ignore the event
if (!barcode)
{
return;
}
// clear the textbox
$("#barcode").val("");
// post the data using AJAX
$.post('#Url.Action("scanned", "receiveScan")?barcode=' + barcode);
});
Note that this assumes that the device will actually paste the entire data at once. If you find that the event is firing too often, you will need to implement some throttling around the change event.

is there a way to stop a form from processing based on true or false using java script

/*--------------------SUBMIT FORM -------------------*/
//Validate Form Fields
function FormValidation()
{
// validation fails if the input is blank
var verdba =document.getElementById('verdba').value;
if(verdba.value == "") {
alert("Error: VERDBA FIRST!");
verdba.focus();
return false;
}
// validation was successful
return true;
processForm();
}
function processForm() {
// window.alert("processForm Reached"); // (Stub)
// Collect Values from the Form
// First section and verification
var callback = document.getElementById('callback').value;
var verdba = document.getElementById('verdba').value;
var comments = document.getElementById('comments').value;
// Concatenate the Page Content
var pageBody = " CB#:"+callback+" "+verdba+comments;
pageBody += "";
window.clipboardData.setData('Text',pageBody);
//Hides table on submit
$("#forms").hide();
$(".myClass").hide();
//Copies pagebody to clipboard
var content = clipboardData.getData("Text");
document.forms["test"].elements["clipboard"].value = content;
}
// Hides table with clear button
function cleartable(){
$("#forms").hide();
$(".myClass").hide();
}
I have included a very bare bones example in a fiddle.
I noticed on the fiddle that it doesn't fully work but in the HTA I have it does work. What it does is collects input fields and option fields by id, concatenates them into what I call a note. It also copies the clipboard data to a text area.
What I want is to be able to click submit and have it collect the form data and check to see if two fields were used or not.
So in the phone number field I need to be sure a phone number is entered ( does not really matter to me if it checks that its a certain amount of digits or that it is digits at all as long as it isnt blank) and next check to see if the option box was selected, either yes or no, again not blank.
Upon discovering one or both were left blank or not selected I would like the process to stop and notify the user that it needs to be done. I would like it to give them a chance to fix it and then resubmit.
The problem I am having is that I can't get both to happen.
I have it where it collects the data and checks for the data, but the problem I ran into is that it doesnt care if its blank and you click ok, it still submits the request anyway and then clears the forms.
I just cant seem to figure out how to get both things working in one swing.
I hope someone can shed some light on this as it has been bugging me for days with endless online research and failed attempts.
https://jsfiddle.net/joshrt24/roqjoyhr/1/
At the end of your function FormValidation(),
// validation was successful
return true;
processForm();
}
You have put return true, before your function has chance to call the processForm, return will immediately exit your function.
Fix, just call processForm() first.
// validation was successful
processForm();
return true;
}

Angular JS form running only first time

I am at the very beginning with my Angular learning and I implemented this form:
http://codepen.io/jgrecule/pen/WxgqqO
What it is supposed to do is very basic: it consumes Flickr public JSONP feed as per Flicker specs https://www.flickr.com/services/feeds/docs/photos_public/ and renders the retrieved pictures thumbnails
The form I implemented has a submit button as well as a reset one. My problems I am trying too find solutions in the order of their importance are:
The very first time when you typing tags everything works but when u try to submit the request again by either adding a new tag or an user Id or anything it no longer works. I can see this warning in the logs but I have no idea what is causing it WARNING: Tried to load angular more than once.
The reset only works for the thumbnails but not for the other controls in my page
I would like to find a way to show an error message when the user pushes on the search flicker button and both tags and user ids input fields are empty. I tried to implement a custom directive but it was no way to get it working.
Thank you in advance for your inputs.
You are loading Angular more than once.
Your resetForm function doesn't reset the form at all. It just calls $setValidity on two of the form elements. It looks like it does try and reset the form in another part of your code with
document.getElementById("searchCriteriaTags").innerHTML = "";
document.getElementById("searchCriteriaIds").innerHTML = "";
document.getElementById("images").innerHTML = "";
which means you are modifying the DOM directly, about which see point 4.
You can add a simple check as to whether $scope.form.tags === '' and so the same for the other fields in your form.
Having addressed your 3 points, I'm afraid to say your code has bigger problems. You are modifying the DOM directly all over the place and you have a lot of duplicate code, plus lots of very complex conditionals.
EDIT 1 in response to OP's comment:
The Angular way of clearing form fields would be to simply clear the scope objects that the form fields are bound to. In other words it is as simple as doing something like:
$scope.tags = [] // for arrays
$scope.name = '' // for strings
Because the form fields are bound to these scope variables through the ng-model directive, changing the variables will also change the form fields.
Setting an error message when two fields are empty you can do like this:
$scope.checkFields = function(field1, field2) {
var oneEmpty = field1 === '';
var twoEmpty = field2 === '';
if (oneEmpty && twoEmpty) {
// call the failure message here
}
}
EDIT 2 in response comments:
Firstly good to see that your code is looking a lot cleaner. Secondly, the reason it fails is because in your search function you set the search fields to null, eg searchCriteria.tags = null;. You should set them to empty strings instead: searchCriteria.tags = '';.
I don't know what the purpose of checkFields is so I don't know where you want to place it. If you want to show an error message if the fields are empty then I'd say have checkFields() return a boolean and use ng-show to display the error div if checkFields() === false.
HTML:
<div ng-show="checkFields() === false">Fields can't be empty</div>
JS:
$scope.checkFields = function(field1, field2) {
var oneEmpty = field1 === '';
var twoEmpty = field2 === '';
return (oneEmpty || twoEmpty);
}

Categories

Resources