How to change a javascript function's parameter from callback function - javascript

I have an HTML input element generated by the server and it looks like this:
HERE IS THE SERVER SIDE
"<input id='" + cRoadList.getRoadListNumber() + ",start_km' style='' type=\"text\" value='"+ cRoadList.getStartKm() + "' onkeypress='handleRoadListDataUpdate(\""+cRoadList.getStartKm()+"\")'
As you see the attrbutes of the input element are generated dynamically but that is not the case so let's simplify it by putting some static data like this:
"<input id='myID' style='' type=\"text\" value='100' onkeypress='handleRoadListDataUpdate(\"100\")'
The most important part of this HTML input element is the onkeypress event which calls the function handleRoadListDataUpdate
HERE IS THE CLIENT PART
function handleRoadListDataUpdate(oValue) // The function accpets the old value of the *input* element
{
var event = handleRoadListDataUpdate.caller.arguments[0] || window.event ;
var keyPressed = event.keyCode;
if(keyPressed == 13)
{
var roadListNumber = event.target.id.split(",")[0];
var inputId = event.target.id.split(",")[1];
var nValue = event.target.value;
if(nValue != oValue)
{
var userAction = confirm("Are you sure you want to change this value?\nPrevious value: " + oValue + "\nNew value: " + nValue);
if(userAction == true)
{
var url = "/GBS/RoadListController";
var params = "type=updateRoadList&roadListNumber=" + roadListNumber + "&updateData="+inputId + "&newValue="+ nValue;
dhtmlxAjax.post(url,params,function(loader)
{
var xmlDoc = loader.xmlDoc.responseXML;
var sqlResponse = xmlDoc.documentElement.getElementsByTagName("response");
var result = sqlResponse[0].getAttribute("value");
if(result == "sql_error")
{
alert("The operation could not be completed because of an network error!");
event.target.value = oValue;
}
else if(result == "sql_success")
{
alert("The operation completed successfully!");
//Change the parameter oValue of the parent function
}
});
}
else
{
event.target.value = oValue;
}
}
}
}
Basically this function is about updating (using ajax) the database with the new value the user enters inside the input element and press key Enter. If the parameter oValue is different than the parameter in the input element an ajax request is made so the database can be updated with the new value.
When the operation completes we have the new value in the input element (which is entered by the user) but the problem is that if he press Enter again the function get executed AGAIN because its parameter oValue is not changed with the new value.
So my very question is:
How to change the handleRoadListDataUpdate() function's parameter oValue to become the same as nValue so if the user press Enter by accident the function does not execute the ajax part again?
P.S.
Please no jQuery code! Only pure javaScript!

Related

Reg Ex doesnt validate if i use # along with other characters or number

this is the same question i asked before. sorry but i check all the link provided it doesnt help. and sorry this is the first time i asked question here so was not very clear about how to ask
I am explaining here again with full details:
i have an input text field.
I Use jquery to validate the input date entered by user in this input box.
I pass the data enter as parameter in javascript GET method and pass it to PHP and validate it there with simple REG Ex. It does validate in all account. But if i add # with any test case this validation fails.
my code:
Input field:
<div id="clntFstName" >
<label for="clnt_fst_name">First Name</label>
<input type="text" id="clnt_fst_name" name="clnt_fst_name" onBlur="checkFieldValid(this.value, this);" value=""/>
<div class="msgError"></div>
</div>
If you the function CheckFieldValid is called as the user leaves a field input box.
java script:
function checkFieldValid(value, obj) {
var elem = obj.name;
$('#' + elem).parent().children('.msgError').html('');
var $label = $("label[for='" + obj.id + "']").text();
var $id = obj.id;
$.getJSON("ajax/registerClient.php?action=checkInputFieldValid&varField=" + value + "&lab=" + $label + "&id=" + $id, function(json) {
if (json.status.length > 0) {
$.each(json.status, function() {
if (this['fail'] == 'fail') {
var info = '<div class="warningMsg"> ' + this['message'] + '</div>';
$('#' + elem).parent().children('.msgError').html(info);
$('#' + elem).focus();
$('#' + elem).val("");
}
if (this['success'] == 'success') {
$('#' + elem).parent().children('.msgError').html('this is success');
}
});
if (json.status == 'empty') {
$('#' + elem).parent().children('.msgError').html('this is empty');
}
}
});
}
PHP code:
if($_GET['action'] == 'checkInputFieldValid'){
if(!empty($_GET['varField'])){
// this creates dynamic session variables and add values to it.
$_SESSION[$_GET['id']] = $_GET['varField'];
if(preg_match('/^[a-zA-Z]+$/',$_GET['varField'])){
$txtVar = 'It is a valid '.$_GET['lab'];
array_push($validFieldArray, array('success' => 'success', 'message' => $txtVar));
echo json_encode(array('status' => $validFieldArray));
$errorJScript = 0;
}else{
$txtVar = 'Enter a valid '.$_GET['lab'];
array_push($validFieldArray, array('fail' => 'fail', 'message' => $txtVar));
unset($_SESSION[$_GET['id']]);// unset the session variable to clear when page refresh
echo json_encode(array('status' => $validFieldArray));
$errorJScript = 1;
}
}
}
I dont know where I am wrong? I did all as told by other members May be I am doing something wrong with Java script when I pass the GET request variables? as far as
I think I did exactly what other member told me about PHP part. but may be the data is wrong when i take it from Java script part? As i checked it with other values return from PHP. but when I put # in my input box IT does not make the AJAX call and doesnt return the JSON nor set the session variable. So probably when I pass the varible as GET parameter It doesnt run the AJAX and just doesnt validate so plz tell me how can i pass # as GET parameter so that i correctly validate the fields in my PHP .
Plz help I will loos my job :(
Your $.getJSON call should use encodeURIComponent() to make sure you're not creating the wrong URL:
$.getJSON("ajax/registerClient.php?action=checkInputFieldValid&varField=" +
encodeURIComponent(value) +
"&lab=" +
encodeURIComponent($label) +
"&id=" +
encodeURIComponent($id), function(json) {
If you don't do that, then a # character will be interpreted as signalling the start of the hash field of the URL, and the rest of the URL will be ignored.

Call JS function from code behind C#

I have a function onRowClick called RowClick and is working fine. I am trying to move it to a button and call the function from the code behind. For some reason is not triggering the function.. Anyone knows why and how I can fix this?
aspx.cs
if (e.CommandName == "Addvoucher")
{
GridDataItem item = (GridDataItem)e.Item;
var id = item.GetDataKeyValue("RowID");
ClientScript.RegisterStartupScript(Page.GetType(), "mykey", "RowClick("+id+");", true);
}
aspx
<script>
var popUpObj;
function RowClick(sender, eventArgs) {
var filterId = eventArgs.getDataKeyValue('RowID');
popUpObj = window.open("voucher.aspx?param=" + filterId + "",
"ModalPopUp",
"toolbar=no," +
"scrollbars=no," +
"location=no," +
"statusbar=no," +
"menubar=no," +
"resizable=0," +
"width=530," +
"height=500," +
"left = 450," +
"top=130"
);
popUpObj.focus();
LoadModalDiv();
}
function LoadModalDiv()
{
var bcgDiv = document.getElementById("divBackground");
bcgDiv.style.display="block";
}
function HideModalDiv() {
var bcgDiv = document.getElementById("divBackground");
bcgDiv.style.display = "none";
}
</script>
IN page voucher.aspx
<script type = "text/javascript">
function OnClose() {
if (window.opener != null && !window.opener.closed) {
window.opener.location.reload(); //refreshing parent when popup close
// window.opener.HideModalDiv();
}
//if (window.closed==true) window.open("~/routedoc.aspx");
}
window.onunload = OnClose;
</script>
Change your js function like this
function RowClick(filterId) {
popUpObj = window.open("voucher.aspx?param=" + filterId + "",
"ModalPopUp",
"toolbar=no," +
"scrollbars=no," +
"location=no," +
"statusbar=no," +
"menubar=no," +
"resizable=0," +
"width=530," +
"height=500," +
"left = 450," +
"top=130"
);
popUpObj.focus();
LoadModalDiv();
}
There is no need of this line now var filterId = eventArgs.getDataKeyValue('RowID'); Now you can directly use the parameter filterId in your js function.
Calling JavaScript function on code behind i.e. On Page_Load
ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:FUNCTIONNAME(); ", true);
If you have UpdatePanel there then try like this
ScriptManager.RegisterStartupScript(GetType(), "Javascript", "javascript:FUNCTIONNAME(); ", true);
Because you are calling RowClick() and in your code you are calling the second parameter eventArgs and actually it's an undefined value.
Make sure you pass the correct parameters.
Since you just calling a javscript function then I would recommend to just on the grid row data bound just assign the value to an anchor a tag or a button to just call the javascript.
The problem is you are not passing any arguments for that js function from server side but you are getting data key value in client function as in your edited question pass row id from server side and change the client side function as below,
function RowClick(rowId)
{
// use rowId
popUpObj = window.open("voucher.aspx?param=" + rowId + "",
}

Intercept a dynamic added form submission

Normal form submission intercept can be found. But, my class is different. The form is dynamically added after calling a function. Then, the form submission cannot be captured.
How to capture the form submission like this? Better to use Jquery but altering the dynamic added form attributes is acceptable.
The following is the example.
Here is how I capture the form submission.
$(function() {
$(".formClass").submit(function(e) {
e.preventDefault();
var actionurl = e.currentTarget.action;
alert(actionurl);
});
});
Here is how forms are added after calling the function - eObj.getFormElement()
(function($){
function(eObj) {
var selector = "#abc";
//Call the function to get the form elements
eObj.getFormElement(langObj, function(err, x) {
var elem = "<ul>";
for (var i=0; i<x.length; i++) {
var formId = elementId + "_sform_" + i;
elem = elem + "<li class='product_" + i + "'>"
for (var key in x[i]) {
elem = elem + "<div class='price'>" + curMap[curKey] + x[i][key].price + "</div>";
elem = elem + "<div class='s'><form id='" + formId +"' class='formClass' method='post' action='" + x[i][key].url + "'>"
+ "<input class='s_btn' type='submit' value='" + submitLabel + "'>"
+ "</form></div>";
}
elem = elem + "</li>";
}
elem = elem + "</ul>";
//Append the form to the div after we create the forms
$(selector).append(elem);
});
}})(jQuery);
Since You can't set events for non-existing elements You need to set events for element existing.
In this case you can use document to get the event.
http://jsfiddle.net/h189o3xc/
here is a sample code.
$(document).on("submit",function(e){
if($(e.target).hasClass("formClass")){
e.preventDefault();
console.log("you can catch the event!");
//and do whatever you want.
}
});
set a event for document and whenever any submit event happens, check whether it's your target form or not. then do whatever you want if it's your target form.
EDITED
as #charlietfl mentioned,You can use extra on function's parameter instead of if statement.
the code would be something like..
$(document).on("submit",".formClass",function(e){
e.preventDefault();
console.log("you can catch the event!");
//and do whatever you want.
});
http://jsfiddle.net/h189o3xc/2/

JavaScript setTimeout() not actually executing it's function?

I have a JavaScript function that goes through a list of checked checkboxes and uploads a video file for each checked box. I'm trying to make sure that the videos have been transcoded into a smaller format before I begin the upload process. I use to track the index in the array videos, that have completed the transcode process. I check to be sure that counter is >= id before starting the upload process for a given video. If counter is too low (the file is not yet transcoded) I use setTimout() to call the uploadVideos function again. It never seems to call the uploadVideos function again, because I never see the alert popup a second time.
How can I get this to work?
function uploadVideos(id, videos, selected, boxes) {
var status = document.getElementById('currentUploadStatus');
// need to deal with element an array
var fields = videos[id].split(":", 2);
var playlist = document.getElementById('playlist');
var dataString = 'videoId='+ fields[0] + '&playlist=' + escape(playlist.value);
// need to determine the maxTranscodedId
var counter = document.getElementById('counter');
alert('counter: ' + counter.innerHTML + " id: " + id);
if (counter.innerHTML >= id) {
id++;
status.innerHTML = "<b class='status'>Uploading Bout #" + fields[1] + " (" + id + " of " + videos.length + ")</b>";
$.ajax({
type: "GET",
url: "floUpload.php",
data: dataString,
success: function(txt) {
if (txt != 'Success') {
alert(':' + txt + ':');
}
if (id < videos.length) {
uploadVideos(id, videos, selected, boxes);
} else {
//re-enable the start button
var startButton = document.getElementById('start');
startButton.disabled = false;
status.innerHTML = "<b class='status'>Upload Complete</b>";
alert('Upload Completed');
}
//deselect the checkbox
if (boxes == 1 ) {
document.videos.video.checked = false;
document.videos.video.style.display = 'none';
} else {
document.videos.video[selected[id-1]].checked = false;
document.videos.video[selected[id-1]].style.display = 'none';
}
},
async: true
});
} else {
// timer call myself the same way I was called
status.innerHTML = "<b class='status'>Upload waiting for trancode.</b>";
var t=setTimeout("uploadVideos(id, videos, selected, boxes)",3000);
//var t=setTimeout("alert('waking')",3000);
}
}
This is a common error in JS beginners. setTimeout admits either one of two kinds of first parameter:
a) Text, in which you can put JS code to be evaluated out of scope (so referenced variables may be undefined), not quite helpful.
b) Function, such as the fix I propose for this, is to replace the line:
setTimeout("uploadVideos(id, videos, selected, boxes)",3000);
with:
setTimeout(function(){
uploadVideos(id, videos, selected, boxes);
},3000);
As you can see I'm wrapping the function call inside another anonymous function. Why? simply because I need to pass arguments, and otherwise I'd be just calling it, instead of passing as argument.

Multiple GET requests using JQuery and AJAX

Very new to JQuery AJAX here. I have been looking around for a answer for awhile on this and can't find an answer.
I have a form that users would fill out. Once filled click on submit. This starts an ajax call to an asp page and basically just displays the information that was entered and fades out the user form. A confirm button below that takes the user to another .asp page that puts it into a database and gives them a ticket number.
My issue is that on the second call ( page that does the input ) , I notice in firebug that the get is happening twice. If I try the asp page alone it is only doing the input once so it's not my sql code. If I switch the second .asp page with the first it works fine.
Here is my jquery. I appreciate any comments. Thanks
$('#submit').click(function (event){
event.preventDefault(); // DECLARE EVENT IN THE CLICK FUNCTION
//Get the data from all the fields
var posting = 'no';
var firstname = $('input[name="firstname"]');
var lastname = $('input[name="lastname"]');
var phone = $('input[name="phone"]');
var email = $('input[name="email"]');
var family_size = $('select[name="family_size"]');
var date_3 = $("#date3");
var date_4 = $("#date4");
var book_option = $('input[name=book_option]:radio:checked');
var payment_type = $('input[name=payment_type]:radio:checked');
var comments = $('textarea[name="comments"]');
if (firstname.val()=='') {
firstname.addClass('fn_error');
firstname.focus();
return false;
} else
firstname.removeClass('fn_error');
if (lastname.val()=='') {
lastname.addClass('ln_error');
lastname.focus();
return false;
} else
lastname.removeClass('ln_error');
if (phone.val()=='') {
phone.addClass('fn_error');
phone.focus();
return false;
} else
phone.removeClass('fn_error');
if (email.val()=='') {
email.addClass('ln_error');
email.focus();
return false;
} else
email.removeClass('ln_error');
// TEST FOR VALID EMAIL
var email_pattern=new RegExp("^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$");
var email_result = email_pattern.test(email.val());
if( email_result == true ) {
email.removeClass('fn_error');
}else{
email.addClass('fn_error');
email.focus();
return false;
}
// TEST FOR VALID PHONE NUMBER
var phone_pattern=
new RegExp("^(\\(?\\d\\d\\d\\)?)?( |-|\\.)?\\d\\d\\d( |-|\\.)?\\d{4,4}(( |-|\\.)?[ext\\.]+ ?\\d+)?$");
var phone_result = phone_pattern.test(phone.val());
if( phone_result == true ) {
phone.removeClass('fn_error');
}else{
phone.addClass('fn_error');
phone.focus();
return false;
}
var dataString= 'firstname=' + firstname.val() + '&lastname=' + lastname.val() + '&phone=' + phone.val() + '&email=' + email.val() + '&family_size=' + family_size.val() + '&date3=' + date_3.val() + '&date4=' + date_4.val() + '&book_option=' + book_option.val() + '&payment_type=' + payment_type.val() + '&comments=' + comments.val() + '&posting=' + posting;
//alert(dataString);
$('#ticketform').fadeOut('slow', function() {
$('#testdiv').load('../resources/confirm_ticket.asp', dataString, function() {
$('#generateform').fadeIn('slow');
$('#submit').unbind('click');
});
}); // LOAD CLOSE
}); // SUBMIT CLICK FUNCTION CLOSE
$('#gen').click(function (event){
event.preventDefault(); // DECLARE EVENT IN THE CLICK FUNCTION
var firstname = $('input[name="firstname"]');
var lastname = $('input[name="lastname"]');
var phone = $('input[name="phone"]');
var email = $('input[name="email"]');
var family_size = $('select[name="family_size"]');
var date_3 = $("#date3");
var date_4 = $("#date4");
var book_option = $('input[name=book_option]:radio:checked');
var payment_type = $('input[name=payment_type]:radio:checked');
var comments = $('textarea[name="comments"]');
var dataString= 'firstname=' + firstname.val() + '&lastname=' + lastname.val() + '&phone=' + phone.val() + '&email=' + email.val() + '&family_size=' + family_size.val() + '&date3=' + date_3.val() + '&date4=' + date_4.val() + '&book_option=' + book_option.val() + '&payment_type=' + payment_type.val() + '&comments=' + comments.val();
alert(dataString);
$('#testdiv, #generateform').fadeOut('slow', function() {
$('#message').load('../resources/generate_ticket.asp', function() {
$('#message').fadeIn('slow');
});
}); // LOAD CLOSE
}); // SUBMIT2 CLICK FUNCTION CLOSE
First off, a better way to verify if a field is filled in is to use jQuery $.trim(), it will trim all white space in the beginning and end so if someone enters a bunch of spaces, it will return false still. This is how you would do it:
if ($.trim(firstname.val())) {
firstname.addClass('fn_error');
firstname.focus();
return false;
}
This is a much better way to verify if it is empty, but an even better idea is to use the jQuery Validation plugin, in which you can simple put class="required", class="required email", etc. for each rule (they can also be defined in the javascript if you prefer).
Also, I see that you keep using .load. Did you know a thing called $.get exists? It is a little more powerful way to send a get request and you don't have to load it into an element to make it work (there's also $.post). I used to use .load myself all the time a while back until I discovered $.get and $.post. This is an example with your code:
$.get('../resources/confirm_ticket.asp', dataString, function(data) { // data is what is returned from the request (html, etc.)
$('#generateform').fadeIn('slow');
$('#submit').unbind('click');
});
Anyway, now to your question.
I don't see any problems of why it would be doing that, but it could be a bug with the browser or something (usually not but this happened to me before too and I never found out how to fix it). Have you tried it in other browsers like Google Chrome or Safari?
I got the answer from a forum today. Can't remember where but the answer is....
$('#testdiv, #generateform').fadeOut('slow', function() {
$('#message').load('../resources/generate_ticket.asp', function() {
$('#message').fadeIn('slow');
});
I have 2 selectors in the fadeOut. It was calling the load function twice for each selector. Changed it and now I'm only getting the one GET request. Thanks for the help though all! :) Happy Coding!

Categories

Resources