I want to know how can I validate using Javascript that if user has entered any username at the time of creating an account is already present in database and ask user to type any other username?
Attach listener for blur event for <input /> element.
Using AJAX send request to the server (with field value as parameter)
On the server side check whether given username is already in use or not
Based on server's response display (or not) This username is already in use message
jQuery (I'm too lazy for pure JS) + PHP sample code:
<form ...>
...
<input type="text" name="username" id="input-username" />
<p class="error"></p>
...
$("#input-username").blur(function() {
$.post("/check-username.php", { username: $(this).val() }, function(data) {
if ("0" == data) { /* username in use */
$(this).next("p").text("This username is already in use.</p>");
} else { /* username is fine */
$(this).next("p").empty();
}
});
});
<?php
$username = $_POST['username'];
// check whether given username exists in database
$usernameExists = ...;
echo $usernameExists ? '0' : '1'; // 0 if exists, 1 if not.
The answer is AJAX. If you must validate against a database, you need to make a call to the server. The only way to do that (EDIT: properly) without reloading the page is AJAX. How you implement it will depend upon what javascript libraries you are using, if any, and what your server is like. I suggest you do a little searching and reading on it - this is a pretty common use case.
Personally, I would use a JQuery validation plugin just to make things simple.
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
But in general it would consist of a small AJAX request to a server (ie. JSON object) with the username and do a 'search' in your database and return either true/false after the user hits enter or tab in the textfield (attach an event listener). Then within your callback response alter the DOM elements of your choice to indicate to your users whether the account name is already present in the database or not.
Ajax might not be the only solution, since usernames are generally public. A simple way is to just have an RDF/XML document at some point (which just updates with every new user added) which has a list of all the users on your site that you can easily just traverse with Javascript DOM to see if that user is already in use. You also make them pay computational power, not you, depending on how nice you are it's an advantage or a dis-advantage.
Related
I have html and css code for a basic quiz template. I want to give the user the ability to make their own custom quiz.
Example: I have created my own math quizzes, science quizzes, etc, that the user can take. I am looking for the ability that Users can make their own personal quiz.
You don't append users input to your code. You should have your quiz as a data and let the user update the data by adding their quiz.
The structure of a form looks like this:
<form method = 'post' action='./handleSubmission/'>
<label>Question 1: </label>
<input type='text' class='question' name='question1'>
<label>Answer 1: </label>
<input type='text' class='answer' name='answer2'>
<label>Question 2: </label>
<input type='text' class='question' name='question2'>
<label>Answer 2: </label>
<input type='text' class='answer' name='answer2'>
<button>Submit</button>
</form>
(You can find all the different input types here. You might want another type for multiple choice questions.
When the user clicks on submit, the default behaviour is that the content of the form will be sent as an http request to the action url. if you set post as method, the method will be POST. If you set get as method, the method will be GET.
Now, in order to do something useful with it, there needs to be a server-side script at './handleSubmission/' or whatever url you put in here, that can read the sent data and upload it to some place where you store the data for your quizzes. This can be either a database or a repository containing some files.
I'd go for json files. Because json files can very easily be decoded and used in any web scripting language.
In PHP for example you'd get the content of the form through a special array called $_GET (or $_POST depending on the method).
You'd then have access to 'question1' with $_GET['question1'].
You'd then have to find a way to put that data into a json file.
To use the content of the json files, you can either use a backend script or a frontend script like javascript.
Are you already using a scripting language for the backend such as PHP or Python? Or do you focus on frontend?
If you want to focus on javascript and frontend, this is the alternative:
<form>
//...
<button id='btn-submit'>Submit</button>
</form>
As you can see, i ommited action and method because in this alternative we don't want to send the form to the server. What we'll do is, when the button is clicked, we'll capture the content of the form without refreshing the page, and then send it a Backend-as-a-service like Google Firebase.
const submitButton = document.querySelector('#btn-submit');
submitButton.addEventListener('click', (e) => {
/* important! prevents the default behaviour which is to submit the form */
e.preventDefault();
const data = [];
/* do stuff here to retrieve the data from form like: */
const questionInputs = document.querySelector('.question');
const answerInputs = document.querySelector('.answer');
for(let key in questionInputs){
data[key] = {
question: questionInputs[key].value;
answer: answerInputs[key].value;
}
}
sendToFirebase(data);
});
You'd then have to write the sendToFirebase function.
Firebase requires making an account, starting a project by giving a name etc. Then it gives you the code to put in your app and you can read the documentation about how to upload data to the Realtime Database.
I strongly prefer the first option however. Because i think in this case the Firebase Realtime Database would be a bit cumbersome to use compared to just setting up a small backend script that generates json files.
I am making a registration form using jquery to dynamically update each field as the user enters information, for some reason when I go to compare emails the if statement does not run. any help would be most appreciated.
have a look at this link which shows proper email validation in php. Also then if the mail is valid apply the check if it is already taken or not. I wrote to check if emails exist after because Database query are costly and better not to have query for all bogus data also.
Hope this helps you out
also change
<input type = text id = email>
to
<input type = email id = email>
which is supported in html5
I'm actually running into little problems with my current project. Following case:
I've got a model called "Posting" with relations:
public function subscribers(){
return $this->belongsToMany('User');
}
In my view-file there is a table containing all Postings and also a checkbox for subscribing/unsubscribing with the matching value to the posting-id:
<input class="click" type="checkbox" name="mobileos" value="{{{$posting->id}}}"
#if($posting->subscribers->find(Auth::User()->id))
checked="checked"
#endif
>
Now the thing I want to archive:
A JavaScript is going to watch if the checkbox is checked or not. According to that, the current user subscribes/unsubscribes to the posting. Something like:
$('.click').on('click',function() {
// $posting->find(---$(this).prop('checked')---)->subscribers()->attach(---Auth::user()->id---);
// $posting->find(---$(this).prop('checked')---)->subscribers()->detach(---Auth::user()->id---);
});
Is there any possibility to archieve that or any other ways? I couldn't get my head around this so far.
Cheers,
Chris
If you want to use Ajax to achieve this, you will need a REST endpoint in Laravel for the subscriptions, e.g.:
http://localhost/subscribe/{{userid}}
When this Endpoint is called, the database can be updated. The function could also return a JSON showing, if the saving database in the database successful.
Use this endpoint to make an Ajax Call on click:
var user = {
id: 0 // retrieve the correct ID from wherever it is stored
}
$('.click').on('click',function() {
$.GET('http://localhost/subscribe/' + user.id,
function () { // this is the success callback, that is called, if the Ajax GET did not return any errors
alert('You are subsribed')
});
});
Ideally you won't be using the GET method, but instead use POST and send the user ID as data. Also you would need to retrieve the user ID from session or wherever it is stored.
Take care that as you are using Ajax it can easily be manipulated from the client side. So on the server you should check, if the user ID that was sent is the same as in the Session. Maybe you don't need to send the user id at all, but that depends on how your backend is built.
Just working on a class project and I can't figure out what to do next.
I've got a form that is being validated with JavaScript. It's the usual information, name, cc# email, etc.
Well the only tuts I can find relate to how to get the form to validate in the first place, which I've already accomplished.
Now all I need to do is figure out how to get the information that I've captured to display in the confirmation page. I don't need any server side validation if that helps.
Here's a link to the page so far (http://sulley.dm.ucf.edu/~ph652925/dig3716c/assignment4/dinner.html)
Any pointers or references?
<?php
print_r($_REQUEST);
?>
will print whatever value the PHP callback is getting from your form.
=H=
You could try to use the GET parameters to forward the info:
link.to.new.page.html?param=value¶m2=value2
etc...
It looks like you're using PHP. If you're sure you don't want any validation, of any kind, then the simplest way to output what was on the form (with some degree of control over what it looks like) is by using the POST global variable in PHP:
<?php
$firstname = $_POST['firstName'];
// etc etc for the other fields
?>
You can then output whatever you want by using those variables. The 'name' property for the HTML fields corresponds to what goes inside the square brackets in the PHP code above.
First, I would like to note that if you are using any server side application, you should absolutely validate the input on the server script before doing anything with it. The client side validation is really intended to make it easier for the user to enter the correct information and can be easily hacked or irrelevant if javascript is off... This said, on the client side, you could intercept the submit event, check the different field values. If you have errors, you display error messages, otherwise, you submit the form. example:
if we have this form:
<form action"myActionscript.php" method="GET" id="#myForm">
// form items here
</form>
and then this script (Beware, code not tested)
<script type="text/javascript">
var f = document.getElementById('myForm');
if (f.addEventListener) { // addEventListener doesn't work in ie prior ie9
f.addEventListener('submit', checkForm);
}else{
f.attachEvent('submit', checkForm);
}
function checkForm() {
// Check all input fields logic,
// you could have an errors array and add an error message for each
// error found. Then you would check the length of the error array,
// submit the form is the length is 0 or not submit the form
// and display errors if the length is > 0.
if (errors.length > 0)
{
// iterate through the array, create final error message
// and display it through an alert or by inserting a new
// DOM element with the error message in it.
// [...]
}else{
f.submit();
}
}
</script>
I have to say that the whole thing would be much easier and certainly more cross-platformed if you used a javascript library like jQuery... ;)
I am a real noob when it comes to javascript/ajax, so any help will be very appreciated.
In reference to this question:
Updating a MySql database using PHP via an onClick javascript function
But mainly concerned with the answer left by Phill Sacre. I am wondering if someone could elaborate on how we are(if we can?) passing values/data through his example, using jquery.
The code example left by him is as follows:
function updateScore(answer, correct) {
if (answer == correct) {
$.post('updatescore.php');
}
}
...
<a onclick="updateScore(this, correct)" ...> </a>
Say for example, we are wanting to pass any number of values to the database with php, could someone give me a snippet example of what is required in the javascript function? Or elaborate on what is posted above please?
Thanks again all.
The simplest example I can think of is this. Make your AJAX call in your if block like this:
$.get('updatescore.php', {'score': '222'}, function(d) {
alert('Hello from PHP: ' + d);
});
On your "updatescore.php" script, just do that: update the score. And return a plain text stating wether the update operation was successful or not.
Good luck.
P.S.: You could also use POST instead of GET.
What you would do is on the php server side have a page lets say its update.php. This page will be visited by your javascript in an Ajax request, take the request and put it in a database.
The php might look something like this:
<?php
mysql_connect(...)
mysql_query("INSERT INTO table
(score) VALUES('$_GET["score"]') ")
Your javascript would simply preform an ajax request on update.php and send it the variables as get value "score".
Phil is not passing any values to the script. He's simply sending a request to the script which most likely contains logic to 'update' the score. A savvy person taking his test though could simply look at the HTML source and see the answer by checking to see what the anchor is doing.
To further nitpick about his solution, a set of radio buttons should be used, and within the form, a button or some sort of clickable element should be used to send the values to the server via an ajax request, and the values sent to the server can be analyzed and the status of the answer sent back to the page.
Since you're using jQuery, the code can be made unobtrusive as seen in the following example:
$('#submit_answer').click(function() {
var answer = 'blah' // With blah being the value of the radio button
$.get('updatescore.php',
{'value': answer},
function(d) {
alert('Your answer is: ' + d') // Where d is the string 'incorrect' or 'correct'
}
});
Enjoy.