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?
Related
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.
I want to show some message in span tag after my form gets submitted to the server. The problem is, the text disappears within seconds. Is it because the page is reloaded? Can anyone spot what is wrong with my function?
function placeOrder(form) {
if (validateLength(1, 32, form["bannerMessage"], form["messageError"]) &&
validateZipField(form["zipField"], form["zipError"]) &&
validateEmptyFields(form["dateField"], form["dateError"]) &&
validateEmptyFields(form["nameField"], form["nameError"]) &&
validateEmptyFields(form["phoneField"], form["phoneError"]) &&
validateEmptyFields(form["emailField"], form["emailError"])) {
// Submit the order to the server
form.submit();
document.getElementById("submitSuccess").innerHTML = "Submitted successfully";
} else {
alert("I'm sorry but there is something wrong with the order information.");
}
}
Exactly, you are sending the form to the server who will send back a complete page.
What you should do is have the new page contain the message that the form was successfully sent, or if there was a problem with the form (you do server-side validation, right?) -- give the details of the error.
For usability, it is important to make sure that you keep all of the form-fields you can. (E-Commerce fields are special, but keep everything else.)
I have a fixed-position form that can be scrolled out onto the document and filled out anywhere on the page. If they fail to fill out the form properly, the errors are currently echod out onto the form, which is the intended design for that aspect. What I don't currently know how to do is, if the form is completed and $errors[] is empty, to use jQuery scrollTop() to jump down to the bottom.
Could anyone help me out with this? Current javascript involved is:
$("#A_FORM_submit_button").click(function() {
$("#FORM_A").submit( function () {
$.post(
'ajax/FORM_A_processing.php',
$(this).serialize(),
function(data){
$("#A_errors_").html(data);
}
);
return false;
});
});
The PHP involved is simply
if (!empty($errors)){
// echo errors
} else { // echo success message} <-- would like to jump to div as well
edit-- for clarity: not looking to make the page jump happen in the php file, so much as return a value for the jq $.post function to check and then perform an if/else
I might be jumping the gun here but I believe your design is wrong which is why you are running into this problem.
The ideal way of handling form validation is to validate forms via Javascript and when users enter in their information you immediately show some indicator to ask them to correct it. As long as the validation is incorrect, you should not be accepting a form request or making any AJAX calls.
In the off-chance that they do successfully send the data, you should be doing a validation check via PHP as well which, if failed, would redirect to the original page with the form. From there you could do whatever error handling you want but ideally you would retain the information they entered and indicate why it was wrong (Javascript should catch this but I guess if it gets here the user might have JS off or your validation logic might be wrong)
If I understand correctly, it seems like you are doing your error handling with Javascript (that's fine) but showing the error via PHP. As Hydra IO said don't confuse client-side and server side. Make them handle what they need to handle.
Hope this helps.
#aug described the scenario very clearly.
In code it translates in something like this
$('form').submit(function(){
form_data = $(this).serialize();
if(!validate(form_data))
{
// deal with validation, show error messages
return false;
}
else
{
// Submit form, either via Ajax $.post() or by just returning TRUE
}
});
The validate() function is up to you to work out.
In order to signout from my webapp, I need to call a json to signout (clear all cookies)
logout:->
$.get('/signout.json')
However, I am unsure how I can refresh the page + redirect the web page to the address i want e.g. /#!/signin? after the signout is successful.
if you want to solve it in javascript just use window.location = "yourlinkhere"
I use the same sort of thing to determine if I have to show a push notification.
I also use asp.net and vb.net so not sure if it will help you but you will get a basic idea of what to do :)
//admin is the controller the second is the function.
$.post("/admin/UpdateBrainBattle/
That function will return a json. in this case its about submitting a form. so you check if the form is valid or not.
in the end it shows this:
Return Json(New With {.status = "error"})
or when its good its with .status = "ok"
Then I get the json back on my page.
This is the whole function(including the post function)
$.post("/admin/UpdateBrainBattle/" + sessionId, { questionId: key, startTimeField: startTimeField, startDateField: startDateField },
function(data) {
if (data.status == 'ok'){
parentLi.find('li.onedit').hide();
parentLi.find('li.onview').show();
parentLi.find('div.dateTimeBlock div.view').html(data.value).show();
parentLi.find('div.dateTimeBlock div.edit').hide();
$('.errorBlockSummary').hide();
}
else
{
parentLi.find('span.errorBlock').show();
$('.errorBlockSummary').show();
}
});
This way you can tell your page, if everything was succesful go to this page, otherwise take this action.
Hope this helped you a bit on your way :)
Edit: noted you used a $.get instead, it can work exactly the same way as long as the function you call to has a return value you should be fine.
I'm having a bit of a problem investigating the result from my get in my script. I got the following code to check if a user is still logged in:
$.get("nowhereGet", function(result){
if($(result).find('[id="loginInput"]'))
{
//HTML is in the response then we have been logged out and the user needs to go to
window.location.href = "login";
}
});
Now if the user is logged in Struts will return one html-page in result from my get. If the user has been logged out different page will be returned one with and element id="loginInput"in it.
I thought the above would do the trick but no love. What am I doing wrong?
Is there a better way to do this than to ping the server with a random get? I need a method that performes this check using ajax and any get or post done while logged out will get intercepted and the result will be the login-page instead of the intended page
$('#result').get(......); ???
UPDATE
so the element #result would have what ever the #loginInput has
$('#result').load('login.php #loginInput');
Otherwise look for a json option because the way you are doing it, its kinda messy
Unless you are looking for this
$.get("nowhereGet", function(result){
if(result && $(result).find('#loginInput').length)
{
//HTML is in the response then we have been logged out and the user needs to go to
window.location.href = "login";
}
});
I found an other soloution and with help from Steven Benitez I got it working. Follow the link for more information but in short I let my interceptor do the work instead. If a certain path/action is called the interceptor will return a text stream that I can read from my script.