I'm using mySQL, javascript and php. I have a form in my website to register new users into it. It's connected to a users table in my mySQL where it saves the users data.
The thing is I can't apply the javascript constraints to the field forms unless I have event.preventDefault();, it will just connect to my php page no matter what and save the data into my table.
But if I use the event.preventDefault(); it will apply the constraints but when I fill it correctly and click register it won't save anything, just creates an empty user in mysql table.
How can I solve this?
var constraints = {
email: {
email: true,
presence: true,
},
Telefone: {
presence:true,
format: {
pattern: "[+0-9]+",
message: "apenas pode conter números [0-9]"
}
},
pwd: {
presence: true,
length: {
minimum: 5
}
},
cpwd: {
presence: true,
equality: {
attribute: "pwd",
message: "as passwords não coincidem"
}
}
}
$("#validationForm").submit(function(event){
event.preventDefault();
$("#error").html("");
console.log(event);
var errors = validate($("#validationForm"), constraints);
if (errors) {
$("#submited").html("");
for (var key in errors) {
$("#error").append(errors[key] + "<br />");
$("#" + key).css("border","1px red solid");
}
}else {
// $("#submited").html("Form Submited");
// redirect to php
window.location.href="registar.php";
}
});
That's because you are manually redirecting to your PHP page.
Instead of this line:
window.location.href="registar.php";
You should rather
document.getElementById("form_to_submit").submit();
Related
I have some functionality that automatically sends an email response when a case is created via someone submitting an email that gets sent to a NetSuite case profile email address. The trouble comes when attempting to set a proper reply-to email address. So far the attempts at creating one don't allow for a successful response directly back into the case record. At first undeliverable messages were being returned until I found an error made in the structure of the address. Now, however, the messages don't appear to make it back to the case records. This is the structure being used:
cases.AAAAA.BBBBB_CCCCC_DDDDD.EEEEE#AAAAA.email.netsuite.com
// AAAAA is the account number
// BBBBB is the internal ID of the case record
// CCCCC is the internal ID of the message record
// DDDDD is the internal ID of the customer record on the case
// EEEEE is a hexadecimal value of unknown sourcing or meaning
I'm thinking maybe part of the problem is that the message record ID is the ID of the message that was sent out from the case, and with what I've been doing it's the ID of the message record saved from the initial incoming email that generated the case in the first place. This leads me to believe that I can't just use the email.send() API with setting a reply-to email address, but I don't see another way to send out the email. Is there anything that I'm missing?
You do not use the email.send() function if you intend on having the customer be able to reply to a Support Case.
Instead, you need to create a Case record (or load an existing one) and then send your email message through that Case record.
Upload the following example script to your File Cabinet and create a Suitelet script, deploy it, and run it. You'll see a simple form that allows you to send out an email via a Case record.
EXAMPLE SCREENSHOT:
CODE:
/**
* #NApiVersion 2.x
* #NScriptType Suitelet
*/
define(['N/ui/serverWidget', 'N/ui/message', 'N/record', 'N/url', 'N/email'], function (serverWidget, message, record, url, email) {
function onRequest(context) {
var form = serverWidget.createForm({
title: 'Send Email via Support Case'
});
form.addField({
id: 'custom_customer',
label: 'Customer',
type: serverWidget.FieldType.SELECT,
source: record.Type.CUSTOMER
});
form.addField({
id: 'custom_email',
label: 'Email Address (not required)',
type: serverWidget.FieldType.TEXT
});
form.addField({
id: 'custom_messagesubject',
label: 'Message Subject',
type: serverWidget.FieldType.TEXT
});
form.addField({
id: 'custom_messagebody',
label: 'Message Body',
type: serverWidget.FieldType.RICHTEXT
});
form.addSubmitButton({
label: 'Send Email'
});
if (context.request.method === 'POST') {
var customerId = context.request.parameters['custom_customer'];
var customerEmail = context.request.parameters['custom_email'];
var messageSubject = context.request.parameters['custom_messagesubject'];
var messageBody = context.request.parameters['custom_messagebody'];
try {
var caseId = 0;
var errorMsg = '';
var caseRec = record.create({
type: record.Type.SUPPORT_CASE
});
caseRec.setValue({
fieldId: 'company',
value: customerId
});
// You can specify an email address to overide the customer's default
// Useful if you need to use an "Anonymous Customer" record and set the outgoing email address to the correct one
if (customerEmail != '') {
caseRec.setValue({
fieldId: 'email',
value: customerEmail
});
}
caseRec.setValue({
fieldId: 'title',
value: messageSubject
});
caseRec.setValue({
fieldId: 'emailform',
value: true
});
caseRec.setValue({
fieldId: 'outgoingmessage',
value: messageBody
});
caseId = caseRec.save({
ignoreMandatoryFields: true
});
} catch (e) {
errorMsg = JSON.stringify(e);
}
if (caseId > 0 && errorMsg == '') {
var caseUrl = url.resolveRecord({
recordType: record.Type.SUPPORT_CASE,
recordId: caseId
});
form.addPageInitMessage({
message: 'Email sent successfully. <a target="_blank" href="' + caseUrl + '">Open Support Case</a>',
title: "Success!",
type: message.Type.CONFIRMATION
});
} else {
form.addPageInitMessage({
message: "Error occurred while sending case message: " + errorMsg,
title: "Failed",
type: message.Type.ERROR
});
}
}
context.response.writePage(form);
}
return {
onRequest: onRequest
};
});
Using the relatedRecords.activityId will automatically send the email with case reply to address.
email.send({
author: me.id,
recipients: you.id,
subject: 'New Case',
body: emailBody,
// attachments: [fileObj],
relatedRecords: {
activityId: thisCase.id
}
});
this is the context of the problem:
I have a DB that contains users, and every user when signs in for the first time to the website recive a verification code sent to their email to prove that he's the owner of the mail used to signing in. This code is then crypted and saved to DB too, as a user attribute.
I'm trying to use SweetAlert2 to say in the first alert
"user, check the mail we sent to mail#mail.com to confirm your account"
and in the second alert to show a textbox for input where the user inserts the verification code and, if this the same as the one in DB then active your account, otherwise display another SweetAlert2 error saying that the codes don't match.
I'm not sure if I understood SweetAlert2 correctly, i'm new to web programming, however, here's the code I tried to do:
[edit, don't know why it doesn't display the first "if (status)... as a code]
if (status) {
Swal.queue([{
title: 'Registration success!',
confirmButtonText: 'Ok',
text: $("#firstname").val() + ', check the mail we sent to ' + $("#email").val() + ' to confirm your account',
'type': 'success'
}])
Swal.insertQueueStep({
title: 'Insert the confermation code we sent you via-mail',
input: 'text'
}).then((result) => {
if (result) {
const answer = result.value;
//check
} else {
Swal.insertQueueStep({
title: 'Codes don\'t match',
'type': 'error'
})
}
})
}
doesn't work. Anyone can help me? Thanks!
Does this work for you?
Swal.fire({
title: "Insert the confermation code we sent you via-mail",
input: "text",
}).then((result) => {
// get DatabaseCode
if (result == DatabaseCode) {
//code matched database code
const answer = result.value;
} else {
Swal.fire({
title: "Codes don't match",
icon: "error",
});
}
});
Or this
Swal.fire({
text:
"user, check the mail we sent to mail#mail.com to confirm your account",
icon: "question",
}).then(() => {
Swal.fire({
title: "Insert the confermation code we sent you via-mail",
input: "text",
}).then((result) => {
// get DatabaseCode
if (result == DatabaseCode) {
//code matched database code
const answer = result.value;
} else {
Swal.fire({
title: "Codes don't match",
icon: "error",
});
}
});
});
I want to implement a follow system between users.
For that, I want to display all of the 250 users of my app, then add a checkmark button next to the ones I already follow, and an empty button next to the ones I do not follow.
var usersRef = firebase.database().ref(‘/users’);
var followingRef = firebase.database().ref(‘/followingByUser’);
var displayedUsers = [];
// I loop through all users of my app
usersRef.once('value', users => {
users.forEach(user => {
// For each user, I check if I already follow him or not
followingRef.child(myUid).child(user.key).once('value', follow => {
if (follow.val()) {
// I do follow this user, follow button is on
displayedUsers.push({
name: user.val().name,
following: true
});
} else {
// I do not follow this user, follow button is off
displayedUsers.push({
name: user.val().name,
following: false
});
}
})
})
})
When doing that, I often (not always) get the following error: "Error: Firebase Database (4.1.3) INTERNAL ASSERT FAILED: sendRequest call when we're not connected not allowed."
Eventually, all the data is fetched, but after 10 seconds instead of 1 (without the error).
I do not believe it is an internet connection issue, as I have a very fast and stable wifi.
Is it a bad practice to nest queries like that?
If not, why do I get this error?
My data is structured as below:
users: {
userId1: {
name: User 1,
email: email#exemple.com,
avatar: url.com
},
userId2: {
name: User 2,
email: email#exemple.com,
avatar: url.com
},
...
}
followByUser: {
userId1: {
userId2: true,
userId10: true,
userId223: true
},
userId2: {
userId23: true,
userId100: true,
userId203: true
},
...
}
Your current database structure allows you to efficiently look up who each user is following. As you've found out it does not allow you to look who a user is follow by. If you also want to allow an efficient lookup of the latter, you should add additional data to your model:
followedByUser: {
userId2: {
userId1: true,
}
userId10: {
userId1: true,
},
userId223: {
userId1: true,
},
...
}
This is a quite common pattern in Firebase and other NoSQL databases: you often expand your data model to allow the use-cases that your app needs.
Also see my explanation on modeling many-to-many relations and the AskFirebase video on the same topic.
I've been successful in modifying the default classes and the negative class values to make sure that my ember-validations appear the way I want them to on load. Now, I'm diving into ember-validations. One of the validator routines I'm having little success with is the match: property. Here's the code from my controller:
userLoginPass: {
presence: { message: " password required" },
match: { property: { "userRegPassConfirm" } }
},
userRegPassConfirm: {
presence: { message: " confirm password required" },
match: { property: { "userLoginPass" } }
},
However, neither field barks on mis-match between them. Something is missing. Anyone had experience with this?
Here's the doc that's giving me problems: https://github.com/lcoq/ember-validations#match
Many Sincere Thanks!
Turns out the answer is a two part process which includes making sure the confirmation field is labelled whateverConfirmation in addition to the confirmation property like so:
password: {
confirmation: true,
presence: {
message: ' password required'
}
},
passwordConfirmation: {
presence: {
message: ' please confirm password'
}
}
as seen on the ember-validations documentation page:
https://github.com/dockyard/ember-validations#confirmation
You should define the validations object on your controller (or model) as follows:
validations: {
userLoginPass: {
confirmation: {
message: 'Your message here.'
}
}
}
And then put an {{input userLoginConfirmation}} within your template.
I have a form that collects some personal information from the end user and triggers some JS validation functions. For simplistic examples lets just say the form has first name, last name, and email address.
Now once the form is filled out and submitted, if I go back to it my browser pre-populates the form like you would expect. The problem is when I go to submit (without changing any fields or tabbing through them) the plugin does not go back and validate those fields (if they have been pre-populated.
I am not sure WHY it is not validating the pre-populated fields. And I am not sure how to get it to. Does anyone have any ideas? I am running the latest version of jQuery and the validate plugin (http://jqueryvalidation.org/).
Sample code:
$(document).ready(function() {
var rules = {
FirstName: 'required',
LastName: 'required',
EmailAddress: {
required: true,
customEmail: true,
checkAccountExists: true
}
};
//And field specific (and even validation type specific) error messages
var messages = {
FirstName: 'Your first name is required.',
LastName: 'Your last name is required.',
EmailAddress: {
required: 'Your email address is required.',
customEmail: 'You must enter a valid email address.',
checkAccountExists: 'We already have an account with that email address. Please login.'
}
};
$('#applicationForm').validate({
//debug: true,
rules: rules,
messages: messages,
errorElement: 'span'
});
});
jQuery.validator.addMethod('customEmail', function(value, element) {
return this.optional(element) || /[A-z0-9._%-+]{1,}#[A-z0-9._%-]{1,}\.[A-z0-9._%-]{1,}/.test(value);
}, 'Invalid email address entered.');
jQuery.validator.addMethod('checkAccountExists', function(value, element) {
if (this.optional(element)) {
return true;
}
var url = $(element).attr('checkEmailUrl');
$.ajax({
type: 'GET',
data: {EmailAddress: value, check: true},
dataType: 'json',
url: url,
success: function(response) {
var dataArray = jQuery.parseJSON(response);
//If it exists then trigger the popup
if (dataArray.result == 'EXISTS') {
kclHelpers.showEmailExistsModal(value);
}
}
});
return true; //If it exists the popup will handle it. We are just using this to trigger it
}, 'An account under the specified email address already exists. Please sign in.');
A simple solution that I employ is just to trigger the blur event already bound to elements you want to validate. You can check the value of each element to determine if they should be validated which prevents this operation from triggering them before the user has interacted.
$(window).load(function() {
//pre-highlight fields with values
$('input[type=text], input[type=email], input[type=url], input[type=password], select').filter(function() {
return $.trim($(this).val()) != '';
}).blur();
});