UPDATED form validation error in javascript - javascript

from the coding below, if some data are wrong, it will alert false. it works fine if the confirmed pw is not same as the password. however, if the loginID checking seems gotta some problems. it alert true789 false false123 false456 respectively. why the consequence is not false123 false456 false789 false? because of the delay from json? how to solve it?
var result = "true";
$('#test').click(function(){
validation();
alert(result);
});
function validation(){
result = "true";
var loginID = $("#loginID").val();
var role = $("#role").text();
// check Login Name
if (loginID == "" || loginID == null){
$('#errorID').empty();
$('#errorID').append(
'<h6>' + "The Login Name cannot be empty" + '</h6>'
);
$("#errorID").show();
result="false";
} else {
$.ajax({
type: "GET",
dataType: "jsonp",
jsonpCallback: "jsoncallback",
data: {
ID: loginID,
role: role
},
url: "http://mydomain.com/checkID.php?jsoncallback=?",
success: function(data){
if (data[0].data.user_name!=""){
result="false";
alert(result+"123");
$('#errorID').empty();
$('#errorID').append(
'<h6>' + "The Login Name " + data[0].data.user_name +
" is used." + '</h6>'
);
$("#errorID").show();
alert(result+"456");
}
},
error: function(jqXHR, textStatus, errorThrown){
alert("Request failed: " + textStatus + errorThrown);
result="false";
}
}); //end of ajax
}
alert(result+"789");
return result;
} // end of #validation

the ajax call is done asynchronous. it enters the ajax() function then carries on and when the result will eventually come the alerts or whatever you have in the event handlers will trigger.
You can add a async : false to your ajax call that will change how things run. The 789 alert will only run after the ajax call is done and responded.
Also, if your ajax call is made to your domain then you don't need the jsonpCallback and if the headers of the response are application/json then you should remove dataType as well and leave it to jQuery to handle it correctly

Related

jQuery 1.8 ajax call returns null although post response has value

I'm having problems with the return value of a jQuery ajax call. I can debug the whole thing server side and I know everything is working correctly and the return value is properly being calculated. I can look under the NET tab in FireBug and see that the response is:
{"d":false}
But when I test the value in the Success function of the ajax call, msg is NULL. Why?
Here's the ajax call:
function GetStateCertifiable(areaID) {
$.ajax({
url: "../WebServices/AoP.asmx/GetStateCertifiable",
data: '{"AreaID":"' + areaID + '"}',
dataType: 'json',
success: function (msg) {
alert(msg); // for debugging
if (msg)
$("#isCertified").slideDown("fast");
else
$("#isCertified").slideUp("fast");
},
error: function (msg) {
alert("An error occured. \nStatus: " + result.status
+ "\nStatus Text: " + result.statusText
+ "\nError Result: " + result);
},
complete: function () {
}
});
};
Other, similarly structured client-side calls work fine. This is a same-domain request.
try changing the name of the variable to something other than msg. I think that might be a message box or something similar. Try
function GetStateCertifiable(areaID) {
$.ajax({
url: "../WebServices/AoP.asmx/GetStateCertifiable",
data: '{"AreaID":"' + areaID + '"}',
dataType: 'json',
success: function (result) {
alert(result); // for debugging
if (result)
$("#isCertified").slideDown("fast");
else
$("#isCertified").slideUp("fast");
},
error: function (result) {
alert("An error occured. \nStatus: " + result.status
+ "\nStatus Text: " + result.statusText
+ "\nError Result: " + result);
},
complete: function () {
}
});
};
It turns out the problem was that my web service (../WebServices/AoP.asmx/GetStateCertifiable) returned a bool and from the post response, I know that was properly sent back to the client. Ajax, however, didn't like that. Once I changed the web service to return the strings "true" or "false", everything worked.
Does jQuery ajax only work for strings or is there something I should have done to prepare the msg object to receive a bool?

jQuery order of events - unable to figure out proper solution

I'm trying to create an if/else statement within my jQuery code that changes the ajax URL and success function that gets fired off:
if($($this.context).find('img').hasClass('scheduler-img')) {
url = window.location.origin + "/recipes/" + planned_recipe_id +'/update_recipe'
} else {
url = window.location.origin + "/recipes/" + recipe_id +'/make_recipe'
success = successfulRecipeAdd(closest_date, image_url, recipe_id);
}
$.ajax({
url: url,
method: 'GET',
dataType: 'json',
data: {
planned_for: planned_for,
meal_type: meal_type
},
success: (function() {
success
}),
error: (function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
})
});
I'm using this for a jQuery draggable and sortable table, so when I'm dragging and dropping the first item, it doesn't work because it tries creating the 'success' variable with an empty dataset. However, it does work for every subsequent drag/drop after.
function successfulRecipeAdd(closest_date, image_url, recipe_id) {
$.get( window.location.origin + "/recipes/get_recipes", function(data) {
console.log(data);
var planned_recipe_id = $(data).last()[0][0].id;
$(closest_date).append("<img src='"+image_url+"'class='scheduler-img col-md-12' id='"+ recipe_id +"' data-planned-id='"+planned_recipe_id+"'>");
});
}
I'm having a lot of trouble figuring out a way to write this that would allow me to create variables within the if/else statement, then fire off the ajax call using variables, rather than having two ajax calls within the if/else statement.

Jquery ajax call throws empty JS exception?

This function works on one page but not another. I've added all sorts of logging to try to find the error, but cannot. The output of this code on the broken page is:
[13:59:56.427] "here"
[13:59:56.428] "beforesend: /admin/test.html?server=eferbelly&port=24466&username=akilandy&password=vkjvkc9776A"
[13:59:56.428] "fileName=undefined"
[13:59:56.428] "lineNumber=undefined"
[13:59:56.428] "columnNumber=undefined"
[13:59:56.428] "here6"
That tells me it's getting into the exception handler, completely skipping my ajax() call, but it's not telling me the exception.
function test(server, port, username, password, spanId) {
spanId = "#" + spanId;
$(spanId).html("<img src='/images/ajax-small.gif'/>");
console.log("here");
try {
$.ajax({
dataType: "json",
type: "GET",
url: "/admin/test.html?server=" + server + "&port=" + port + "&username=" + username + "&password=" + password,
success: function(json){
console.log("here2");
if (json.httpStatus == "200") {
// Change the image to show success
$(spanId).html("<img src='/images/accept.png' title='success'/>");
}
else {
console.log("here7");
// Change the image to show failure
$(spanId).html("<span style='color:#b22222;'>" + json.httpStatus +"</span> <img style='vertical-align: middle;' src='/images/cancel.png' title='placeholder'/>");
}
console.log("here8");
$(spanId).tooltip({ content: json.msg});
},
// Display the URL
beforeSend: function(b,c,d) {console.log("beforesend: " + c.url);},
error: function(b,c,d) {console.log("here5");}
});
}
catch(e) {
console.log(e);
for (var i in e)
console.log(i + "=" + i[e]);
}
console.log("here6");
}
What could I do further to debug this?
UPDATE: Output of code on a working page
Here's the output of the exact same code but on the page where it is working:
[15:01:20.158] "here"
[15:01:20.159] "beforesend: /admin/test.html?server=eferbelly&port=24466&username=akilandy&password=vkjvkc9776A"
[15:01:20.159] "here6"
[15:01:21.661] GET https://localhost/images/accept.png [HTTP/1.1 200 OK 2ms]
[15:01:21.599] "here2"
[15:01:21.600] "here8"
So it obviously gets through the ajax call with flying colors. No errors, nothing. How can I find the problem on the page where it doesn't work?

Function called by jQuery Form Plugin's beforeSubmit not returning value

The beforeSubmit function in my jQuery Form plugin needs to check whether the selected file already exists on the server. Here's that relevant code:
$('#frmSermonUpload').ajaxForm({
beforeSubmit: function() {
// Reset errors and clear messages
ClearForm(false);
var formValid = true,
fileExists = CheckFileExists();
console.log('beforeSubmit fileExists: ' + fileExists);
if (fileExists === 'true') {
$('#uploadedFile').addClass('inputError');
$('#fileErrorMsg').append(' A file with that name already exists on the server.');
formValid = false;
} else {
if (!ValidateUploadForm()) {
formValid = false;
}
}
console.log('formValid: ' + formValid);
if (!formValid) {
return false;
}
},
...
Here's the CheckFileExists() function:
function CheckFileExists() {
var fileName = $('#uploadedFile').val().replace(/C:\\fakepath\\/i, ''),
dataString;
dataString = 'checkFileExists=' + fileName;
console.log('fileName: ' + fileName);
console.log('dataString: ' + dataString);
$.ajax({
type: 'POST',
url: '../scripts/sermonUpload.php',
data: dataString,
success: function(serverResult) {
console.log('serverResult: ' + serverResult);
if (serverResult === 'existsTrue') {
return 'true';
} else {
return 'false';
}
},
error: function(xhr, status, error) {
alert('An error occurred while attempting to determine if the selected file exists. Please try again.);
}
});
//console.log('Current value of returnResult: ' + returnResult);
//return returnResult;
}
As you can see I'm using console output to check what's going on. In the CheckFileExists() function, fileName and dataString are being reported correctly. On the PHP side, I know that the POST data is getting there due to some logging I've got going on there.
Here's the PHP code that uses the POST data:
if (isset($_POST['checkFileExists']) && $_POST['checkFileExists'] !== '') {
$log->lwrite('**Checking if file exists.**');
$fileToCheck = $targetPath . $_POST['checkFileExists'];
$log->lwrite('file_exists: ' . file_exists($fileToCheck));
if (file_exists($fileToCheck)) {
echo 'existsTrue';
} else {
echo 'existsFalse';
}
}
What's happening is, in the console, the line console.log('beforeSubmit fileExists: ' + fileExists); is returning "undefined" (beforeSubmit fileExists: undefined).
Here's all of the console output for an upload where the file already exists, so the beforeSubmit should be stopped:
fileName: 042913sermon.mp3
dataString; checkFileExists=042913sermon.mp3
beforeSubmit fileExists: undefined
formValid: true
serverResult: existsTrue
It must be significant that the serverResult line is displaying after everything else. Does that have to do with how long the ajax call takes? If so, is there a way to delay the rest of the script until the ajax call is done executing?
UPDATE
As aorlando pointed out, the order of the console output signified that I needed to add async: false to my $.ajax call. After doing so, the console output was correct, but the function CheckFileExists() is still getting reported as undefined in beforeSubmit.
Ok. Now the problem is the scope of return.
If you use "async: false" you can return in this way (not so elegant)
var returnValue='';
$.ajax({
type: 'POST',
url: '../scripts/sermonUpload.php',
data: dataString,
async: false,
success: function(serverResult) {
console.log('serverResult: ' + serverResult);
if (serverResult === 'existsTrue') {
returnValue = 'true';
} else {
returnValue= 'false';
}
},
error: function(xhr, status, error) {
alert('An error occurred while attempting to determine if the selected file exists. Please try again.);
}
});
return returnValue;
You must declare a var returnValue out of the scope of the ajax call. Inside the ajax function you can modify the value of returnValue;
This is a solution which use closure, a quite complex javascript feature. Further read something about scope of a variable in javascript: What is the scope of variables in JavaScript?
This is not a very nice solution; is better if you call a function inside "success" function of ajax call as my previous example.
That's all folks!
You are using an AJAX async call.
Your method CheckFileExists()n return a value before the ajax call complete.
So the simplest solutions is to use:
$.ajax({
type: 'POST',
url: '../scripts/sermonUpload.php',
data: dataString,
async: false ...
if you want to use async call (the default as you can see: http://api.jquery.com/jQuery.ajax/
you must call (for ex.) a postcall function in the success function of the ajax call:
success: function(serverResult) {
console.log('serverResult: ' + serverResult);
if (serverResult === 'existsTrue') {
postFn('true');
} else {
postFn('false');
}
}, ...
Be carefull with the scope of the postFn
funcion postFn(_result){
console.log(_result);
}
I hope to be clear.
That's all folks!

Updating jQuery Item during Ajax call

I am making an ajax call to send out a couple of emails when the user clicks a button. I am trying to update a "Please wait..." div before and after the call with the status, as well as report any errors. The problem... is that the div doesn't actually update until the ajax call is complete.
If I comment out the ajax call the status update works fine, but fails if the ajax call takes place. My Windows programming experience tells me the div needs to be refreshed, but I'm not sure how this is done, or if this is the right method.
For example:
$("#msgEmail").show();
$("#msgEmail").html("Preparing to send");
$.ajax({ blah blah blah...
Any pointers in the right direction will be much appreciated!
On nnnnnn's suggestion I started testing on other browsers. The problem occurs on Chrome and Safari, but works as expected on Firefox and SeaMonkey. It sure looks like he's right about this. Now I just need to figure out to implement setTimeout() in this scenario.
Update: Code:
.click(function() {
$('#myTable :checkbox:checked').each(function() {
sId = $(this).attr('cid');
sName = $(this).attr('cname');
ret = true;
$("#msgImage").slideDown();
sUpdate = 'Sending alerts to class: '+ sName;
$("#msgEmail").slideDown();
$("#msgEmail").html(sUpdate);
sSubject = "Notificatiom";
sMessage = $('#message').val();
sData= "cid="+sId+'&sname='+sName+'&subject='+sSubject+'&message='+encodeURIComponent(sMessage);
$.ajax({
url: 'dostuff.php',
data: sData,
dataType: 'text',
type: 'POST',
async: false,
success: function (msg)
{
if(msg >= '1')
{
ret = true;
}
}
});
if(ret)
$("#msgEmail").html('Finished sending alerts');
$("#msgImage").slideUp();
ret = false;
return false;
})
Place your ajax call in the callback for 'slideDown'. Set the message before calling 'slideDown'. This will ensure your message is updated before the ajax call is sent.'
sUpdate = 'Sending alerts to class: ' + sName;
$("#msgEmail").html(sUpdate);
$("#msgEmail").slideDown(function() {
sSubject = "Notificatiom";
sMessage = $('#message').val();
sData = "cid=" + sId + '&sname=' + sName + '&subject=' + sSubject + '&message=' + encodeURIComponent(sMessage);
$.ajax({
url: 'dostuff.php',
data: sData,
dataType: 'text',
type: 'POST',
async: false,
success: function(msg) {
if (msg >= '1') {
ret = true;
}
}
});
});
I ll get you an on hw this stuff is going to be
$(document).ready(function(){
$.ajax({
url :'YOur url',
.....
.....
ajaxSend :function(){
$('#yourdiv').html('please wait...');
}
success:function(msg){
if (msg >= '1') {
$('#yourdiv').html('validated');
}
}
});
}):

Categories

Resources