jquery php ajax username check function - javascript

So i'm usually pretty good at figuring out these types of problems but this one has got me completely stumped as have been trying to fix for about 6 hours now.
i have a web form which contains a username check using jquery script and a php script. it was working fine when i first wrote the code and now has completely stopped working(no idea why). The php script is a pretty standard mysqli query which returns the numrows and then i either echo 1 or 0 to the page depending on if a result was found. this script works fine and have tested it independently and echos 1 if no result was found and 0 if a result was found.
in the jquery script i have a min value check and a no value check which both work fine. Then my ajax call and i receive the result with success:function(data). this also has been tested independently by printing the result(data) on screen and prints a 1 on screen when there is no record and a 0 on screen when a record if found so i know everything is working fine with the sent data and im getting the results back i expect.
so my only thing left is there must be a problem with my if statement and how it is dealing with the returned data as it always skips to the else even when the condition is met. The only way for the if statement to work is when i set the variable myself and run the script. The long story short is everything works fine except for the final if statement where it always jumps to the else no matter what and says the username is available even when i know its not.
Im testing on xampp. Could this be an issue too?
Any ideas? Thanks in advance!!!
Here is the code: javascript
$(document).ready(function(){
//the min chars for username
var usermin_chars = 6;
//result texts
var checking_html = 'Checking...';
//when button is clicked
$('#username').blur(function(){
var usernameVal = $("#username").val();
if (usernameVal == '') {
$("#username_result").html('<span class="error">Please enter a username!</span>');
$('#username').removeClass();
$('#username').addClass("form_error");
}
//run the character number check
else if($('#username').val().length < usermin_chars){
//if it's bellow the minimum show characters_error text '
$('#username_result').html('<span class="error">Username must contain at least 6 characters!</span>');
$('#username').removeClass();
$('#username').addClass("form_error");
}else{
//get the username
var username = $('#username').val();
$.ajax({
type:"post",
url:"checkUsername.php",
data:"username="+username,
success:function(data){
if(data==0){$("#usename_result").html("Username already in use! Please choose another username.");
$('#username').removeClass();
$('#username').addClass("form_error");
}
else{$("#username_result").html("Username available");
$('#username_result').html('<span class="ok"><img src="../images/imgs/available.png" width="20" height="20" margin-left="5" alt="tick"></span>');
$('#username').removeClass();
$('#username').addClass("form_ok");
}
}
});
}
});
});

ok so i found the answer. as the site is near completion i had gone through all the pages and made sure every page had a title for SEO including the checkUser page. the page title was being sent through with the data and confusing the if statement. when i was testing the fuction if i placed (data) in a span it only showed the 0 or 1 but looking at it in firebug it showed the response as the 0 or 1 plus the page title. Thanks for those who had a look at it.

Related

Check AJAX response is set

I've built an online multiple choice quiz, where the user clicks on the desired answer of each question, and a $.post AJAX request is sent to the server for further processing.
For all questions except for the last one, the server script simply exit;s...
For the last question in particular, the server responds with the valid answers he/she gave (an echo $valid; and exit;s). Keep in mind that $valid may also be 0, if he/she didn't give any correct answers...
So, in the AJAX response function I have this
success: function(response) {
$(this).addClass('chosen').removeClass('loading-gif');
if (response !== null) {
countdown(response);
}
}
where countdown() prints a Thank you, you gave x out y valid answers message on the screen, does a live countdown effect, and then redirects to another page...
The problem is that no matter what I tried for the if check, it always shows the thank you message, even from the first answer... So I tried if (response !== null), if (typeof(response) !== 'undefined') and still I get the message... What I didn't try is if (response) because 0 evaluates to false, so in the case the user ends the test with 0 valid answers, the message won't show up...
Am I missing something? Why is this happening?

How do I make my password prompt only show up once when I open up my website instead of every time I reload the page or revisit it

Can I set a time limit (for example in 8 hours you have to retype the password)?
Here's my very simple javascript:
<SCRIPT language="JavaScript">
<!--hide
var password;
var pass1="x10Kz4iz4ZvEB2wgUBA5otc1";
var pass2="x10Kz4iz4ZvEB2wgUBA5otc1";
var pass3="x10Kz4iz4ZvEB2wgUBA5otc1"
password=prompt('Please enter your password to view this page!',' ');
if (password==pass1 || password==pass2 || password==pass3)
alert('Password Correct! Click OK to enter!');
else
{
alert('Uh oh try again');
window.location="#";
}
//-->
</SCRIPT>
I have this under the head tag of my HTML text.
Thank you :)
This is not really a secure way of protecting your website because anyone can look at the source code of a page and see the Javascript along with the passwords you wrote there.
However, for learning purposes, you might want to learn about setting and getting cookies (How do I create and read a value from cookie?). You can store the time the user logged in, and next time check if it has been eight hours (just compare the time and date of last login to current login time and date).
Also, to get the current time, you should read up on the Javascript Date() function.

JQuery $.post only works sometimes

I have the following function:
function Login() {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
$.post("Login.php", {
username: username,
password:password
}, function(data) {
console.log(data);
});
}
The issue that I'm having is that the function only runs sometimes. I had checked to see if it were a case that JQuery wasn't loaded upon the function running but it was. It doesn't really matter what text I input it simply works only sometimes. I think it has something to do with the $.post function.
Please see the following snaps of Chrome DevTools:
Sometimes it will do the above and the function will stop/end at line 67.
And other times it will go all the way through & work.
The above image shows me using the same input as the image before but this time the function stops/ends at line 67.
What could be causing this? I don't think it has anything to do with the variables themselves. The function is called when a button is clicked.
Update!
I'm seeing this error in the console. The page is also reloading so maybe before the post request could go through the web page would reload but I don't know how to solve this.
I've found the answer. There were two errors:
An issue with the html encoding as it relates to the password field.
There is a password_verify() function within the login.php file that takes a while to run which causes the post to fail.

Node/Javascript Redirect Not Working?

I have built a form to add some dummy data to a Mongo collection for testing purposes. The function to add the data seems to be working ok in that the data is being added ok, but, for some reason, the redirect command at the end of the function is not doing its thing. The data comes from a bog standard HTML form. Here is the code for adding the data:
router.post('/addacc',function(req,res){
var sljEdate = "";
var pljEdate = "";
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/stc';
MongoClient.connect(url,function(err,db){
if(err){
console.log("Connection Error");
}else{
console.log("connected to mongo");
var collection = db.collection('account');
var query = {accountID: req.body.acc_id,companyName: req.body.acc_name,companyEmail:req.body.acc_email,companyPhone:req.body.acc_phone,companyPostCode:req.body.acc_postcode,
photographers: {phtID:"",phtName:"",phtPhone:"",phtEmail:"",phtLoc:"",preferredContact:"",lastJob:"",pljEpoch:pljEdate,phtNotes:""},
schools: {schoolID:"",schoolName:"",schoolPhone:"",schoolEmail:"",schoolPostCode:"",lastJob:"",sljEpoch:sljEdate,notes:""}};
collection.insert(query,function(err,result){
if(err){
console.log("Error inserting Account record",err);
}else{
console.log("Data Insert Success");
res.redirect("/forms");
}
db.close();
});
}
});
});
I added lines to log to the console in a few places so that I could check progress and they all fire, including the final 'Data Insert Success' one. The res.redirect which follows it, however, does nothing. In the browser the URL remains as '/addacc', though the node console shows a subsequent GET for the '/forms' URL.
I've tried a few variations for the redirect, using e.g. res.send("test") just to try and output something, also a res.render function, but none of them seem to work.
I'm pretty sure that I have missed something simple, but I've been staring at the code for too long and I can't see anything wrong with it. In fact, I've had nearly identical code working lots of times. The only thing I'm doing differently this time is that I'm inserting into a Mongo collection which includes embedded documents, but the data insert is not the problem as the data gets in fine.
Help please!
Ok, it seems that the Node problem above was a bit of a red herring. The redirect is actually working ok (MrWillihog's comment above is duly noted for future reference anyway). I thought it must be as all the response codes on the npm console checked out fine. The problem is actually to do with the rendering of the Jade template. Specifically something to do with the the file layout.jade which I use to set out the HTML head. For some reason (yet to be determined) things work fine when calling the /forms page directly in the URL. The file forms.jade starts in the standard way with
extends layout
block content
With the opening BODY tag in layout.jade the page fails to load properly when called from the redirect: the layout.jade file renders (I put an H1 in there to check), but forms.jade doesn't.
I moved the BODY down in to forms.jade (under block.content) and it started working though, interestingly, the URL in the address bar remains as '/accadd'
Again I'm a bit stumped as I have used this pattern quite a few times with no issue. I'm guessing that I've just forgotten something simple. I'll keep digging until I find the answer, but at least now I should be looking in the right place.

Increment the number of times an article has been read

I have a situation where I need to increase the number of time article has been read.
Once someone opens an article it should be reflected in the database by incrementing number of reads by one. Simple.
Sending POST request to the server increments the number of reads by one. The article in question is supplied via URL parameter.
Doing it manually by typing the URL in a browser works as expected. So server side is not at fault.
My problems start with the javascript side of it or rather jquery. I hook the event to the article link. So every time a user clicks on the article link it increments the number of reads like so:
$('#list-articles .article-link').click(function(e){
var oid = $(this).parent().parent().attr('data-oid').toString(); //Get the article id
$.post( "/articles/viewed/" + oid );
});
Now this does not work! Number is not increased.
I don't prevent default action since I need the link to actually open and display the article.
Now if I put an alert right after the post like this:
$('#list-articles .article-link').click(function(e){
var oid = $(this).parent().parent().attr('data-oid').toString(); //Get the article id
$.post( "/articles/viewed/" + oid );
alert(oid);
});
This variant works. After I dismiss the alert window, the number is incremented. Why is this so?? How can I fix this to actually work without the alert event present?
UPDATE
Thank you for helping to solve this. All answers are great and help one way or another. The only variant that works so far is disabling async on ajax call. It would be great if someone could elaborate on why switching the async mode off in ajax fixed it. So the post request in the original was never executed? If I was simply checking too early and the number increase was not visible upon page load, it should be still visible on the next page reload, right? SInce it wasn't updated on the database at all I assume that post was not run at all. Why is this so? I want to understand the issue so I do't get into this problem again. Thanks.
Your problem could be due to $.post being asynchronous and you checking this too soon and try posting synchronously:
$.ajax({
type: 'POST',
url: "/articles/viewed/" + oid,
async:false
});
Prevent default. Wait for the response from the server to say incrementing article reads by 1 was successful, then redirect to the article.
If it works with the alert in place it sounds like a race condition.

Categories