Ajax call from dropdown select - javascript

I am trying to make an Ajax request to the page specified in the drop down menu. I have successfully used most of my script code in binding a mouse click to table rows, but it does not work in this case when I try it here. I get ReferenceError: fnsuccess is not defined. I did not get this ReferenceError when I used most of this script to bind a mouse click.
<script type="text/javascript">
function isValid(frm){
$("#courseinfo").hide();
$("#frm").validate();
var four04 = $("#frm :selected").val();
console.log('Testing console');
if (four04 == "404")
{
console.log("404");
var txt = ($(this).text());
$.ajax({url:"404.json", data:{coursename:txt}, type:"GET", dataType:"json",
success:fnsuccess, error:fnerror});
function fnsuccess(serverReply) {
if (serverReply && serverReply.info) {
$("#infohere").text(serverReply.info);
$("#courseinfo").show();
} else
fnerror();
}
function fnerror() {
alert("Error occurred");
$("#courseinfo").hide();
}
}
else
{
console.log("else 404");
}
}
</script>
Course -->
Rating
404 error
403 error
Fix:
<script>
function isValid(frm){
$("#otherPageContent").hide();
$("#frm").validate();
var dropDownSelected = $("#frm :selected").val();
if (dropDownSelected == "404")
{
var txt = ($(this).text());
$.ajax({url:"404_error.json",
data:{coursename:txt},
type:"GET",
dataType:"json",
success:fnsuccess,
error: function(xhr, status, error){
$("#infohere").text(
"The requested page was: 404_error.json" +
". The error number returned was: " + xhr.status +
". The error message was: " + error);
$("#otherPageContent").show();
}
}); // end of ajax
} // end of if 404
function fnsuccess(serverReply) {
if (serverReply && serverReply.info) {
$("#infohere").text(serverReply.info);
$("#otherPageContent").show();
}
}
return false; // pause message on screen
}
</script>

define function fnsuccess(serverReply) and fnerror outside isValid function

Related

Typewriter look from a text file

I'm a really new Javascript person who for the first time is trying to write (rather than copy) code for a page. Simply put, I wish to read a text file then display the characters one at a time in a div already created. The 'get' corks fine and the data variable receives the string, however, I get a 'Line 1' input past error from the browser when this executes. Probably 10 things wrong with how I am going about it, but any direction welcome.
enter code here
<div id='textelement' style="width:400px; height:200px ;overflow:auto"></div>
<script type="text/javascript">
$.get("Comments.txt", function (data)
{
var displaytxt = "";
displaytxt = data;
function nextchar ()
{
if (displaytxt.length > 0)
{
$('#textelement').append(displaytxt.substr(0, 1));
displaytxt = displaytxt.substr(1);
setTimeout(nextchar, 70);
}
}
}
</script>
For one thing you did not escape your function properly.
<script type="text/javascript">
$.get("Comments.txt", function (data)
{
var displaytxt = "";
displaytxt = data;
function nextchar ()
{
if (displaytxt.length > 0)
{
$('#textelement').append(displaytxt.substr(0, 1));
displaytxt = displaytxt.substr(1);
setTimeout(nextchar, 70);
}
}
}).fail(function (xhr, status, error) {
alert(error);
});
</script>
After looking at this a while I found that:
1. I never called my function 'nextchar' therefore it never ran. Silly me.
2. setTimeout needs a strange syntax using the function() {} in order to pass parameters. Why is this?
The code below now works for me.
greg
<script type="text/javascript">
function nextchar(displaytxt) {
if (displaytxt.length > 0) {
$('#textelement').append(displaytxt.substring(0, 1));
displaytxt = displaytxt.substr(1);
setTimeout(function () { nextchar(displaytxt); }, 70);
}
}
$.get("PatientComments.txt", function (data) {
var displaytxt = "";
displaytxt = data;
alert(displaytxt);
nextchar(displaytxt);
}).fail(function (xhr, status, error) {
alert(error);
});
</script>

Javascript data check will always return true

this is my java script, where I am checking if data comes do some thing else do something
function translateData() {
var word = $('#word').val();
var lang = $('#lang').val();
$("#result").html("loading...");
$.post("translateAdmin.action", {
word : word,lang:lang
}, function(data) {
if (data.length > 0) {
$().toastmessage('showSuccessToast', "Translation Done");
//alert("Translation Done");
}
else {
$().toastmessage('showErrorToast', "Translation Not Done");
// alert("Unable to translate");
}
But, it will never go to else, even if it does not return any data in text area, it shows exception in my action class but it give an success message.

Prevent JQuery to continue when catch an Error

When document ready i have set
$.ajaxSetup({
"error": function (XMLHttpRequest, textStatus, errorThrown) {
if(XMLHttpRequest.status == 403) {
display_modal( 'Please login to continue.', 'Session in closed.');
//XMLHttpRequest.abort();
}
}
});
to prevent ajax request from unauthenticated users.
but in a specific view, when a POST/GET request is made I have
var posting = $.post(
post_url,
$("#" + form).serialize(),
function(data) {
packet = data;
},
'json'
);
posting.done(function() {
form_post_response_function(e, packet);
});
posting.fail(function() {
var packet = {};
packet.data = {};
packet.data.type = "Ajax Post Fail";
packet.status = -200;
packet.statusMessage = "ERROR";
form_post_response_function(e, packet);
});
I was expecting to posting.fail(function() { and getting.fail(function() { not be called. But they are, so all the flow goes and it ends with another modal overlaping the 403 message.
How can I avoid this without raw $.ajax ? How stop JQuery flow at the error catch?
FINAL code
posting.fail(function(jqXHR, textStatus, errorThrown) {
if(jqXHR.status != 403) {
var packet = {};
packet.data = {};
packet.data.type = "Ajax Post Fail";
packet.status = -200;
packet.statusMessage = "ERROR";
form_post_response_function(e, packet);
} else {
// event also can be accessed here
$(get_target(e)).button('reset');
}
});
and it stop gently. looks good.
Throw an exception to stop the execution of further code.
For example: throw "stop execution here";
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw
See que Question for all the details
This is the final code
posting.fail(function(jqXHR, textStatus, errorThrown) {
if(jqXHR.status != 403) {
var packet = {};
packet.data = {};
packet.data.type = "Ajax Post Fail";
packet.status = -200;
packet.statusMessage = "ERROR";
form_post_response_function(e, packet);
} else {
// event also can be accessed here
$(get_target(e)).button('reset');
}
});

How to stop execution when form validation in javascript

I have two questions from the coding below.
First, now i would like to perform validation before submission. How can I stop submission if some errors are detected from the validation function? Is it simply return false after each of the error msg? however, it seems still check all fields instead of stopping after getting one error.
Second, i would like to insert the data via php. Everytime, it can successfully add the data to the database, however, it always alert "Error: error". I dunno where does the error come from...
$(document).ready(function()
{
$('#test').click(function(){
validation();
});
function validation(){
var loginID=$("#loginID").val();
if (loginID=="" || loginID==null)
{
$('#errorID').empty();
$('#errorID').append(
'<h6>' + "The Login Name cannot be empty" + '</h6>');
$("#errorID").show();
}
else
{
}
// check pw
$("#errorPW").hide();
if ($("#loginPW").val()=="" || $("#loginPW").val()==null)
{
$('#errorPW').empty();
$('#errorPW').append(
'<h6>' + "The Login Password cannot be empty" + '</h6>');
$("#errorPW").show();
}
else
{
}
//return false;
} // end of #validation
$('form').submit(function(){
validation();
$.ajax({
type: 'POST',
data:
{
loginID: $("#loginID").val(),
// some data here
},
url: 'http://mydomain.com/reg.php',
success: function(data){
alert('successfully.');
},
error: function(jqXHR, textStatus){
alert("Error: " + textStatus);
}
});
return false;
});
});
you can use return false.It will stop the execution
<form onSubmit="validatdeForm();"></form>
function validatdeForm()
{
//here return true if validation passed otherwise return false
}
or
if (loginID=="" || loginID==null)
{
$('#errorID').empty();
$('#errorID').append(
'<h6>' + "The Login Name cannot be empty" + '</h6>');
$("#errorID").show();
return false;
}
if ($("#loginPW").val()=="" || $("#loginPW").val()==null)
{
$('#errorPW').empty();
$('#errorPW').append(
'<h6>' + "The Login Password cannot be empty" + '</h6>');
$("#errorPW").show();
return false;
}
it should be something like below. return false stop execution of script when error is there.
function validation(){
var loginID=$("#loginID").val();
if (loginID=="" || loginID==null)
{
$('#errorID').empty();
$('#errorID').append(
'<h6>' + "The Login Name cannot be empty" + '</h6>');
$("#errorID").show();
return false;
}
else
{
return true;
}
// check pw
$("#errorPW").hide();
if ($("#loginPW").val()=="" || $("#loginPW").val()==null)
{
$('#errorPW').empty();
$('#errorPW').append(
'<h6>' + "The Login Password cannot be empty" + '</h6>');
$("#errorPW").show();
return false;
}
else
{
return true;
}
return true;
} // end of #validation
Design your validation function as below,
function validation()
{
var isValid = true;
if(field validation fail)
{
isValid = false;
}
else if(field validation fail)
{
isValid = false;
}
return isValid;
}
basic idea behind code is to returning false whenever your validation fails.
To make a proper form validation, I will suggest you go about doing it in a more organized way. It is easier to debug. Try this:
var validation = {
// Checking your login ID
'loginID' : function() {
// Login ID validation code here...
// If a validation fails set validation.errors = true;
// Additionally you can have a validation.idError that contains
// some error message for an id error.
},
// Checking your password
'loginPW' : function() {
// Password validation code here...
// If a validation fails set validation.errors = true;
// As with id, you can have a validation.pwError that contains
// some error message for a password error.
},
'sendRequest' : function () {
if(!validation.errors) {
// Code for whatever you want to do at form submit.
}
}
};
$('#test').click(function(){
validation.errors = false;
validation.loginID();
validation.loginPW();
validation.sendRequest();
return false;
});
function validateimage() { if($("#photo").val() !== '' ) {
var extensions = new Array("jpg","jpeg","gif","png","bmp");
var image_file = document.form_useradd.photo.value;
var image_length = document.form_useradd.photo.value.length;
var pos = image_file.lastIndexOf('.') + 1;
var ext = image_file.substring(pos, image_length);
var final_ext = ext.toLowerCase();
for (i = 0; i < extensions.length; i++)
{
if(extensions[i] == final_ext)
{
return true;
}
}
alert(" Upload an image file with one of the following extensions: "+ extensions.join(', ') +".");
//$("#error-innertxt_photo").show().fadeOut(5000);
//$("#error-innertxt_photo").html('Enter valid file type');
//$("#photo").focus();
return false;
}

XMLRequest ResponseText is blank

I've got a JavaScript function that I want to report an alert message to the users if it successfully updates the database, or if it has an error.
In the main X.JSP file I have:
function startRequest(pChange)
{
//alert("startRequest");
createXmlHttpRequest();
//alert("sending message");
//var u1=document.f1.user.value;
//alert("Running startRequest for: " + pChange.id);
//xmlHttp.open("GET","updateEntry.jsp&pID=pChange.id&pStatus=pChange.status&pAddress=pChange.address&pDate=pChange.date&pNotes=pChange.note&pAssigned=pChange.assigned" ,true)
xmlHttp.open("GET","updateEntry.jsp?pID=" + pChange.id + "&pAddress=" +pChange.address + "&pStatus=" + pChange.status +"&pNote=" + pChange.notes +"&pAssigned=" +pChange.assigned ,true)
//alert(xmlHttp.responseText);
xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.send(null);
}
function handleStateChange()
{
//alert("handleStateChange");
var message = xmlHttp.responseText;
alert("Return Code:" + message);
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
//alert("test2");
//alert("recieved Message");
var message = xmlHttp.responseText;
alert(message);
}
}
else
{
alert("Error loading page"+ xmlHttp.status +
":"+xmlHttp.statusText);
}
}
I then run a method in updateEntry.jsp that does a number of things, but of interest is this section:
if(nId.equals("NMI")||nId.equals("MI")||nId.equals("NI")||nId.equals("SA")||nId.equals("S"))
{
org.hibernate.Query query2 = session2.createQuery("update Leads set Status = :nstatus where Id = :nid");
query2.setParameter("nid", nId);
query2.setParameter("nstatus", nstatus);
query2.executeUpdate();
out.println("Update successfully with: " + nstatus);
// Actual contact insertion will happen at this step
session2.flush();
session2.close();
}
else
{
out.println("Status must be: NMI, MI, NI, SA or S");
}
My understanding is that this should only create a single alert, if the function completes successfully. Instead it creates like 9 alerts all of which are blank. What am I doing wrong? I'm seeing both the "Return Code: " message and a blank " " message, (two different sections of code) but both output blank message variables.
If the readystate is not 4, it does not mean it is an error. Ajax has multiple states that inform the clientside about what is happening. Your code says that those connection states are all errors.
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
//alert("test2");
//alert("recieved Message");
var message = xmlHttp.responseText;
alert(message);
} <-- your else should most likely be up here
}
else <-- this is incorrect
{
alert("Error loading page"+ xmlHttp.status +
":"+xmlHttp.statusText);
}
Read the document at MDN - Ajax Getting Started

Categories

Resources