AngularJS ngKeyUp function the value is undefined - javascript

html
<input class="input--style" type="email" name="email" ng-model="attempt.email" ng-keyup="check(attempt.email)" value="">
angularjs
$scope.check = function(text){
console.log(text);
$http({
method: 'POST',
url: '/api/user/check/',
data: {'email': $scope.attempt.email},
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
}).success(function(data, status, headers, config) {
console.log(data);
$scope.user.emailvalid = data.email;
});
}
This input is inside a modal and when the modal fires the angular above is inside that modals controller, it works as expected but when I start typing in the input field the console.log(text); outputs undefined
$scope.attempt = {} this is before my angular script above and I'm just curious as to why this isn't working.

Do you really want to make a call to the server every time that the user presses a key? Wouldn't you prefer to have a debounce of at least ~200ms?
Try doing this instead:
<input class="input--style" type="email" name="email"
ng-model="attempt.email" ng-model-options="{ debounce: 200 }"
ng-change="check(attempt.email)" >
Update:
I forgot to answer your original question: you are using an input type="email", so unless it's a valid email angular will set the model to undefined. Therefore, angular is actually doing you a favor, because you probably don't want to make that call to the server unless the model contains a valid email address, right? So, just change your 'check' function so that it first checks if the value is undefined , and if it is don't make the call to the server and set $scope.user.emailvalid to false.

Related

ajax succes triggered even if the form is false

I can't figure it out, i have a form submitted by ajax and the ajax code always return false even if the form values doesn't meet the requirement.
Also the function that should happend in the form action php file when the form is correct doesn't happend so it doesnt matter if i fill in the required fields or not, or if i fill them right or wrong the ajax will call it success and the php action wont work{even if the form is correct!}
Form :
<form method="POST" onsubmit="return loginSubmit(this)">
<input type="text" name="username" placeholder="username"></br>
<input type="password" name="password" placeholder="password"></br>
<button type="submit" name="submit">login</button>
</form>
Function :
function loginSubmit(element){
var values = $(element).serialize();
$.ajax({
type: 'post',
url: 'assets/login.inc.php',
data: values,
success: function(data){
alert('success');
}
});
return false;
}
Form Action{php} :
it's kind of long and i dont want this post to look like a mess so i'm just writing the way i pull the data from the form, the php code works fine when i submit the form without ajax.
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
The jQuery success callback doesn't do what you think it does. It is triggered if the HTTP call is successful and received a normal 'OK' response.
You need to parse the data parameter within the callback to determine what your PHP code returned.
From the jQuery documentation for the 'Ajax' method call:
A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object.
Ref: http://api.jquery.com/jquery.ajax/
Ok i got it, in the php file i checked if the form was submitted which seems not true if you submit it trough ajax. Thanks

Validate a simple HTML form via JSON answere

I´am a UX designer and one of these JS dummie/"HTML coder" guys.
I need help or a hint to validate a simple HTML form via a second request which returns a JSON answere, before the form is send.
I have a really simple HTML form on a landingpage where the user can enter a coupon code:
<form id="tokensubmit" method="GET" action="https://www.xyz/cart.html">
<div class="form-group">
<input type="text" name="tokenCodeAdd" id="tokenCodeAdd" size="25" value="" class="form-control input-lg" placeholder="Please enter Coupon Code">
</div>
<input id="input_id" type="submit" class="btn btn-lg btn-warning btn-block" value="Submit">
</form>
If a user enters his Coupon code and hit the submit button, the code will be added to the action URL (https://www.xyz/cart.html) and the User is redirected to this cart.html page. If the coupon code is correct everything is fine. If not he receives an error message on the cart.html page.
So far so good.
BUT: I want to validate the coupon code without redirecting the user to a new website(cart.html).
The system offers a second URL for this already. A url like:
/checkout/validate.html?tokenCode=12345678
This returns a JSON answere with a status like:
{"error":"Wrong Coupon Code."}
if the Coupon code isnt right.
If it is valid, something like:
{"error":"null"}
returns.
What I am searching for is a simple solution to call the validation URL (validation.html) first on click on the "submit" button, parse the returning JSON, prevent the form from sending if "error" is something else than "null" and print the JSON message ("Wrong Coupon Code.") right above the form input.
If "error" = "null" the forms behavior should not change. It should just open the https://www.xyz/cart.html URL with the tokenCode attached as parameter.
What I´am trying/starting with looks like:
$('#tokensubmit').submit(function(event){
event.preventDefault();
var tokenCheck = $(this).find('input[id="tokenCodeAdd"]').val();
$.ajax({
url: '/checkout/validate.html'+tokenCheck,
type: 'GET',
success: function(data){
var jsonData = $.parseJSON(data);
}
});
});
Its just the beginning, I know. The real parsing part is missing and the error message output if the validation fails, or the redirect if not.
Anyone who could help?
And thx in advanced!
Small hint: The form is placed on a WordPress driven landingpage, so PHP and JQuery is an option.
The code you have for getting the validation is almost correct:
$('#tokensubmit').submit(function(event){
event.preventDefault();
var tokenCheck = $(this).find('input[id="tokenCodeAdd"]').val();
$.ajax({
// either attach the parameter like you are trying to do directly to the url,
// but in this way:
url: '/checkout/validate.html?tokenCode='+tokenCheck,
// or give the URL parameter(s) as data object to jQuery:
data: {
tokenCode: tokenCheck
}
type: 'GET',
// if you specify the dataType you want to receive as json,
// jQuery will parse it for you already
dataType: 'json',
success: function(data){
// now you can check the data for error or not, for example like:
if(data.error == null){
// do something (most likely REALLY submit the form now?)
}else{
alert('tokenCode invalid');
}
}
});
});
With jquery you can send through a data parameter and it will work out how to place it in the URL:
$.ajax({
url: '/checkout/validate.html',
type: 'GET',
data: {"tokenCode": tokenCheck}
success: function(data){
var jsonData = $.parseJSON(data);
}
});
I would also advise not doing an Ajax request at all if tokenCheck is empty.
Wouldn 't it be easier to check the coupon code when the user leaves the input field? First the example while submitting the whole form.
$('#tokensubmit').on('submit', function(event) {
event.preventDefault();
var validationSuccess = false;
$.ajax({
url : '/checkout/validate.html',
type : 'GET',
data : { tokenCode : $('#tokeninput').val() }
success : function(response) {
var data = $.parseJSON(response);
if (data.error === null) {
validationSuccess = true;
}
}
if (validationSuccess === true) {
$('#tokensubmit').off('submit').submit();
}
});
So what we 've done here? The submit event listener is nearly the same you 've done. We prevent the default submitting of the form and do an ajax request for validation the input value. If the request returns no error as response, we simply unbind the submit event listener from the form and submit the form again.
In my opinion it would be better to work with the blur event listener on the input field. In combination you could use the HTML5 Constraint Validation API. So you don 't have to submit the form and the ajax request would be done on blurring the input field. I think that would be the better user experience.
So here 's the blur event listener:
<input type="text" name="the-input-field" id="the-input-field" value="" required>
$('#the-input-field').on('blur', function(event) {
var element = this;
$.ajax({
url : '/checkout/validate.html',
type : 'GET',
data : { tokenCode : element.val() }
success : function(response) {
var data = $.parseJSON(response);
if (data.error !== null) {
element.setCustomValidity('Your input is invalid!');
// place some error message elsewhere in the markup
} else {
element.setCustomValidity('');
}
}
});
});
First we placed the required Attribute in the input element. It marks the input element as required. So if it 's empty you could not submit the form. Then we placed the blur event listener, which is doing the ajax request. If the response is false, we place a custom error via setCustomValidity. It is a native HTML5 Constraint Validation API function. If the custom error on the input element is set, you could not submit the form. If the user enters another token the request is done again on leaving the input element. If the token is valid, the custom error message will be removed and the form can be submitted.

put recaptcha response into a knockout js observable

I am using google recaptcha and what I am trying to do is put the response into a observable and then send it to the backend server. I am trying but I am failing. Here are the codes.
<div class="form-group">
<div class="col-sm-8">
<div class="g-recaptcha" data-sitekey="############"></div>
</div>
</div>
Next piece of code is in the js file with knockout
self.recaptchaCode = ko.observable($('.g-recaptcha-response').val()); // Does not work
Here is the ajax sending to the backend
$.ajax({
type: 'POST',
url: BASEURL + 'index.php/login/loginUsingAjax/' + auth,
contentType: 'application/json; charset=utf-8',
data: ko.toJSON({
email : self.eMail(),
password : self.passWord(),
recaptcha : self.recaptchaCode()
})
})
I guess I am not getting the right way to get the response into the observable
This line:
self.recaptchaCode = ko.observable($('.g-recaptcha-response').val());
Sets the observable with the value your element holds at the time the observable is created. When you request the observable's value (self.recaptchaCode()), it is not re-evaluated; you receive a cached response.
This means your code will only work if the element's value is available at the time you instantiate your viewmodel. Knockout cannot magically watch a non data-bound DOM element.
I'd suggest creating a method instead of an observable:
self.getRecaptchaCode = function() {
return $('.g-recaptcha-response').val();
};
Better would be to create a value binding on the element, but I'm not sure if you have access to the .g part of the DOM... In that case, you could use a "real" knockout approach:
<input data-bind="value: recaptchaCode">
With self.recaptchaCode = ko.observable() in your viewmodel.

Determining duplicate values before a form is submitted

Say I have an online form, and I want to figure out whether a user is entering an email that's already in use by the system. Can I tell the system to check the field against the database as soon as the user moves their cursor / selection away from the field? Could anyone point me in the right direction if this is actually possible?
You could attach a listener to the text field using jQuery's blur event, like so:
$('#MyEmailField').blur(function() {
// jQuery AJAX Call here, $.ajax(...)
})
For this You need to call ajax when user writing an email id means on blur event as below :
$('#yourfieldID').blur(function() {
var val = $(this).val();
$.ajax({
type: 'POST',
url: 'your url',
data: {email: val},
success: function (data) {
// check for response
});
}
});
});
Now In file which you called in ajax url, Your need to check data which is exist in database or not and according to that you need to send response and check it in sucess part of ajax call.
I hope you will get it.
Yes, it is possible using an AJAX call on the "onblur" event of Javascript (or "focusout" method of jQuery)
You could use something like this, in the HTML:
<input type="email" name="myinput" />
And the JS:
$( "input" ).focusout(function() {
var usr_email = $(this).value;
$.ajax({
method: "GET",
url: "some.php",
data: { email: usr_email }
}).done(function( response ) {
if(response == "taken"){
$("input").borderColor = "red";
}
});
}
You can check for email's availability through an Ajax call in database on text change or blur event of email textbox. Then notify the user accordingly.
As soon as user moves out of email field, say tab or mouse click, you need to trigger a function to make a Ajax call to your server. The triggering function would be onBlur of email field. Then check If user email exits, get back Ajax response to notify the user.

Changing an Angular ng-model with jQuery

I'm writing a Google Chrome extension which will interact directly with an AngularJS app.
Data is passed into Chrome's localstorage (chrome.storage.local) in one page, and then retrieved when the user loads my app's page.
The Angular is basically just a form with ng-models attached, like so:
<input id="q1" ng-model="inputName" >
<input id="q2" ng-model="inputTitle" >
<input id="q3" ng-model="inputAge" >
<button ng-click='submit()' >
The submit() function saves the ng-model values to my database to be retrieved later.
There are similar questions here which use older versions of AngularJS and I cannot get to work with Angular 1.2+ (I'm on Angular 1.2.2).
I've tried:
$('#q1').val(obj.title).trigger('input');
I've also tried:
$('#q1').val(obj.title);
angular.element($('#q1')).triggerHandler('input');
Neither work, in fact the latter makes no value change occur at all. What's the fix?
EDIT: Here's the Angular function being called on click, if there's something I can do in here to force ng-model to check the html input's value (that was set by jQuery in the Google Chrome extension) then that could be a solution:
$scope.submit = function(){
var theEvent = {
inputTitle: $scope.inputTitle,
inputName: $scope.inputName,
inputAge: $scope.inputAge
};
$rootScope.existing = theEvent;
$http({
url: '/api/saveToMongo/newEvent',
method: "POST",
data: theEvent
}).
success(function(data, status, headers, config) {
$cookies.oldSession = data;
$location.path('/collect');
}).
error(function(data, status, headers, config) {
console.log("There was an error submitting!");
});
};
All of these are returning null when I submit to my database, although if I type in the values manually then they work fine.

Categories