Link to home
Start Free TrialLog in
Avatar of triplebd69
triplebd69

asked on

Call JavaScript From Code Behind

I need to play audio (either mp3 or wav).  I have read many articles on how to play a file but it always includes a button click and JavaScript.  I am new to JavaScript.  Below is mock-up data of how I need this to work.  Any and all help would be welcome.

public void PlayClientSound(int type)
{
      if (type == 1)
      {
             Call JavaScript to play audio.
      }
      else
      {
            Call JavaScript to play different audio.
      }
}
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

You can't call JavaScript from Code Behind - JavaScript runs in the Browser - Code Behind on the server. JavaScript can call Code Behind but not the other way around.

What you probably want here is most likely a pure JavaScript solution.

But before suggesting an approach - can you explain how this code will be used - where will the Audio file path come from in the above scenario.
Avatar of triplebd69
triplebd69

ASKER

Basically the web application will scan bar code labels.  If the scan is correct play one sound else play another sound.  As far as the location, I'm willing to put them anywhere.
maybe you are looking for something like this

public void PlayClientSound(int type)
{
      if (type == 1)
      {
             response.write("<script>playSong(1);</script>");
      }
      else
      {
            response.write("<script>playSong(2);</script>");
      }
}

Open in new window

I assume that "playSong();", is the path name?  And if so, does it matter where the files are located?
playSong(); is a js function that plays song :)

just guessing...

you should have a js function to play something, dont you?
No, I don't.  Like I said I have very little js knowledge.
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks, but I still have issues.  I have an DevExpress ASPxTextBox that the users scan the bar-code into.  I do some validation to determine if it is a valid scan or not, then I call the PlayClientSound() method.

After adding your code, when I enter a scan, it just shows the spinning icon, like it's working but never does anything else.

I have attached the controls I set up, the script, code behind, spinning, and location of wav files.User generated imageUser generated imageUser generated imageUser generated imageUser generated image
A couple of things.

Your AJAX implementation seems to be a direct copy of my code - where I have t2512.php you need to replace that with a link to your service that validates your scan - it won't work leaving my code in there.

I don't understand why still have the code behind in place that does the playsong code - that is what should be in the callback from the AJAX call.

I think you need to work through my example again and understand what it is doing - to summarise the code does the following

1. It sets up an event handler on the change event for the scan input. What this means is when a change is made to that <input> an event fires and calls our handler

2. The handler retrieves the scan value from the <input> and sends it to a service on the server using AJAX

3. The service validates the scan code and sends back a TRUE / FALSE value

4. The AJAX callback processes the return and then plays the success or fail sounds

The sounds are setup using <audio> controls that contain the different sounds to play.

From the screen grabs above you seem to be mixing two different solutions.
First things first: As @Julian Hansen said you're not going to be able to do that all on the client side (browser) or all on the server side.

Questions for you (so we can guide you better):
1. Are you using a scanner (handheld or stationary) or is the user supposed to use the webcam or a device camera?
2. How is the scan sent to the server? Is it via a button click or automatic?
3. Is the validation logic on the client side or the server side?
4. Is it always a pass/fail situation, or does it need to do something else as well?

@Julian Hansen has already given you all parts you need to make this work; now we just have to figure out how to best explain the integration.
1.  The user is using a handheld wireless scanner.
2.  I use regular expressions and C# code to validate bar-code.  It is automatic (it scans the data to a textbox).
3.  Server Side.
4.  Always a pass/fail.
For #2, there is a mechanism that sends the scanned code to the server.
  • There has to be a JavaScript function that is called by the control. It has to be tied to a an endpoint that you have configured.
  • There has to be a listener tied to that control which waits for a scan to be detected. More than likely this is also a JavaScript function.

If you can find the functions for these two things then this becomes much simpler. Because this is a web application, at the end of the day it all renders down to HTML and JavaScript. It would be most helpful if we could see the rendered source from the browser (Right-Click >> View Source >> Copy >> Paste). Once we've determined what those are then we might be able to modify them to do what you want.
Here is the js.



 //Validate and move next
                function processValidate(htmlEvent) {                    
                    if (htmlEvent.keyCode == 13) {
                    Validate();
                }
            }

            //Callback validation
                function Validate(s, e) {
                if (ASPxClientEdit.ValidateGroup('Group1')) {
                    cbpMain.PerformCallback('');
                }
                }
Are you using a post back to validate the scanned code? If so then you should consider changing your architecture to make the validation a service - not a post back handler - and then use the AJAX solution presented above.
Rendered source from the browser.
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head><link rel="stylesheet" type="text/css" href="/DXR.axd?r=0_929,1_33,1_35,1_18,0_754,0_752-VM8ue" /><title>

</title><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" /><link rel="stylesheet" type="text/css" href="style.css" />
    <style type="text/css">
        #form1 {

        }
    </style>
</head>
<body>
    <audio id="successSound">
        <source src="media/success.wav" type="audio/wav" />
      </audio>
      <audio id="failSound">
        <source src="Sounds/bad.wav" type="audio/wav" />
      </audio>
    <form method="post" action="./KanbanValidation.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="M6u8mTy5fM0ikB6RnXlidF6agK9/MwZONxk9RBmG8um+vyK+Sc6ssDi1TRWBkli/xK6agt+sR3PXKmUmWfM2fv6K3bug5aY5xeCDY3yOxGTh9T5O96DYGL98neHN04nG+s2nSufv60wgd+O84PUWi7EzEPjz6quWNYMaNOBMb0D5m3kUmnq4LEdoZQ0qTgUN+yzHdVATpnuD00V/JA7c7ffveUQGqJYAt/qCfMTTP1KLSZhCE8GxPxg9nqF8za33z//ZLdOY8JVELLFbCJpMiHxUKdwwgXWesFjhZ7BOhJKO/FdLtjRsUkGO02PyCw8gyAeaFnJ+YyJZp8piRpF10/e0xedGtWiD/jkvrAukYNY8NnvCcWcLD0uALE0IIL1SAMWFWp/Dvww+jlSBVVtzcug2Jd0fsBx0/3Fm5caJSiyX50RZDJiv9Q0vwPwRyCchsOwVGd8F04S5x+NuwMjsWhoAeLYrmvCRYCcdkA8BBkw=" />
</div>

<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
    theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}
//]]>
</script>


<script src="/WebResource.axd?d=pynGkmcFUV13He1Qd6_TZD0PXGCc4fN7XNKXgNwrQmAuW01q4mIuWST6kc1HCvM-ULWxK1sXLb5vP67prbA5RA2&amp;t=636198610698160310" type="text/javascript"></script>

        <div>
            <br />
        </div>
        <div style="text-align: center">
            <span id="Label1">Door Validation</span>
        </div>
        <br />
        <div style="text-align: center">
            <span id="lblManifest">Manifest: 1705050047</span>
        </div>
         <br />
        <div style="text-align: center; width: 100%; height: 265px;">
            <input type="hidden"/><script id="dxis_512821647" src="/DXR.axd?r=1_230,1_134,1_223,1_168,1_212,1_131,1_215,1_133,1_166,1_174,1_173,1_155-VM8ue" type="text/javascript"></script><div class="dxpnlControl_DevEx panel" id="cbpMain" style="height:80px;width:400px;">
	

                        <div class="dxpnlControl_DevEx" id="cbpMain_pnlKanban" style="height:80px;">
		
                                        <span class="dxeBase_DevEx" id="cbpMain_pnlKanban_lblitem" style="color:#0000CC;font-size:X-Large;float: left;">Slot: 1 A4C-AE F R 080</span>
                             
                                        <table id="cbpMain_pnlKanban_txtKanban_ET" class="dxeValidDynEditorTable dxeRoot_DevEx" style="font-size:X-Large;">
			<tr>
				<td id="cbpMain_pnlKanban_txtKanban_CC"><table class="dxeTextBoxSys dxeTextBox_DevEx dxeTextBoxDefaultWidthSys" id="cbpMain_pnlKanban_txtKanban" style="font-size:X-Large;height:52px;width:400px;border-collapse:separate;">
					<tr>
						<td class="dxic" style="width:100%;"><input class="dxeEditArea_DevEx dxeEditAreaSys" id="cbpMain_pnlKanban_txtKanban_I" name="cbpMain$pnlKanban$txtKanban" onfocus="ASPx.EGotFocus(&#39;cbpMain_pnlKanban_txtKanban&#39;)" onblur="ASPx.ELostFocus(&#39;cbpMain_pnlKanban_txtKanban&#39;)" onchange="ASPx.EValueChanged(&#39;cbpMain_pnlKanban_txtKanban&#39;)" type="text" /></td>
					</tr>
				</table></td>
			</tr><tr>
				<td id="cbpMain_pnlKanban_txtKanban_EC" class="dxeErrorCell_DevEx dxeErrorFrame_DevEx dxeErrorFrameSys dxeErrorCellSys dxeNoBorderTop" style="font-size:X-Large;display:none;"><table style="width:100%;">
					<tr>
						<td><img id="cbpMain_pnlKanban_txtKanban_EI" class="dxEditors_edtError_DevEx" src="/DXR.axd?r=1_37-VM8ue" alt="" /></td><td id="cbpMain_pnlKanban_txtKanban_ETC" style="font-size:X-Large;width:100%;white-space:nowrap;">Invalid value</td>
					</tr>
				</table></td>
			</tr>
		</table><script id="dxss_83739918" type="text/javascript">
<!--
ASPx.AddDisabledItems('cbpMain_pnlKanban_txtKanban',[[['dxeDisabled_DevEx'],[''],['','I']]]);
document.getElementById("cbpMain_pnlKanban_txtKanban_ET").setAttribute("errorFrame", "errorFrame");

var dxo = new ASPxClientTextBox('cbpMain_pnlKanban_txtKanban');
dxo.InitGlobalVariable('txtKanban');
dxo.uniqueID = 'cbpMain$pnlKanban$txtKanban';
dxo.initialFocused = true;
dxo.Init.AddHandler(function(s, e) {s.Focus();	});
dxo.KeyDown.AddHandler(function(s, e) {processValidate(e.htmlEvent);});
dxo.customValidationEnabled = true;
dxo.isValid = true;
dxo.errorText = 'Invalid value';
dxo.setFocusOnError = true;
dxo.display = "Dynamic";
dxo.errorImageIsAssigned = true;
dxo.controlCellStyles = { cssClass: 'dxeErrorFrame_DevEx dxeErrorFrameSys dxeNoBorderBottom dxeControlsCell_DevEx', style: "font-size:X-Large;" };
dxo.RequireStyleDecoration();
dxo.styleDecoration.AddStyle('I','dxeInvalid_DevEx','');
dxo.styleDecoration.AddStyle('F','dxeFocused_DevEx','');
dxo.errorCellPosition = 'Bottom';
dxo.AfterCreate();

//-->
</script>
                                
	</div>
                        <br />
                        <br />
                        <div class="dxpnlControl_DevEx" id="cbpMain_pnlBankKanban" style="height:80px;">
		
                                        <span class="dxeBase_DevEx" id="cbpMain_pnlBankKanban_ASPxLabel1" style="color:#0000CC;font-size:X-Large;float:left;display:none;">Buffer Kanban:</span><script id="dxss_644997534" type="text/javascript">
<!--
ASPx.AddDisabledItems('cbpMain_pnlBankKanban_ASPxLabel1',[[['dxeDisabled_DevEx'],[''],['']]]);

var dxo = new ASPxClientLabel('cbpMain_pnlBankKanban_ASPxLabel1');
dxo.InitGlobalVariable('cbpMain_pnlBankKanban_ASPxLabel1');
dxo.uniqueID = 'cbpMain$pnlBankKanban$ASPxLabel1';
dxo.clientVisible = false;
dxo.AfterCreate();

//-->
</script>
                                        <table id="cbpMain_pnlBankKanban_txtBankKanban_ET" class="dxeValidDynEditorTable dxeRoot_DevEx" style="font-size:X-Large;display:none;">
			<tr>
				<td id="cbpMain_pnlBankKanban_txtBankKanban_CC"><table class="dxeTextBoxSys dxeTextBox_DevEx dxeTextBoxDefaultWidthSys" id="cbpMain_pnlBankKanban_txtBankKanban" style="font-size:X-Large;height:52px;width:400px;display:none;border-collapse:separate;">
					<tr>
						<td class="dxic" style="width:100%;"><input class="dxeEditArea_DevEx dxeEditAreaSys" id="cbpMain_pnlBankKanban_txtBankKanban_I" name="cbpMain$pnlBankKanban$txtBankKanban" onfocus="ASPx.EGotFocus(&#39;cbpMain_pnlBankKanban_txtBankKanban&#39;)" onblur="ASPx.ELostFocus(&#39;cbpMain_pnlBankKanban_txtBankKanban&#39;)" onchange="ASPx.EValueChanged(&#39;cbpMain_pnlBankKanban_txtBankKanban&#39;)" type="text" /></td>
					</tr>
				</table></td>
			</tr><tr>
				<td id="cbpMain_pnlBankKanban_txtBankKanban_EC" class="dxeErrorCell_DevEx dxeErrorFrame_DevEx dxeErrorFrameSys dxeErrorCellSys dxeNoBorderTop" style="font-size:X-Large;display:none;"><table style="width:100%;">
					<tr>
						<td><img id="cbpMain_pnlBankKanban_txtBankKanban_EI" class="dxEditors_edtError_DevEx" src="/DXR.axd?r=1_37-VM8ue" alt="" /></td><td id="cbpMain_pnlBankKanban_txtBankKanban_ETC" style="font-size:X-Large;width:100%;white-space:nowrap;">Invalid value</td>
					</tr>
				</table></td>
			</tr>
		</table><script id="dxss_921172680" type="text/javascript">
<!--
ASPx.AddDisabledItems('cbpMain_pnlBankKanban_txtBankKanban',[[['dxeDisabled_DevEx'],[''],['','I']]]);
document.getElementById("cbpMain_pnlBankKanban_txtBankKanban_ET").setAttribute("errorFrame", "errorFrame");

var dxo = new ASPxClientTextBox('cbpMain_pnlBankKanban_txtBankKanban');
dxo.InitGlobalVariable('txtBankKanban');
dxo.uniqueID = 'cbpMain$pnlBankKanban$txtBankKanban';
dxo.clientVisible = false;
dxo.KeyDown.AddHandler(function(s, e) {processValidate(e.htmlEvent);});
dxo.customValidationEnabled = true;
dxo.isValid = true;
dxo.errorText = 'Invalid value';
dxo.setFocusOnError = true;
dxo.display = "Dynamic";
dxo.errorImageIsAssigned = true;
dxo.controlCellStyles = { cssClass: 'dxeErrorFrame_DevEx dxeErrorFrameSys dxeNoBorderBottom dxeControlsCell_DevEx', style: "font-size:X-Large;" };
dxo.RequireStyleDecoration();
dxo.styleDecoration.AddStyle('I','dxeInvalid_DevEx','');
dxo.styleDecoration.AddStyle('F','dxeFocused_DevEx','');
dxo.errorCellPosition = 'Bottom';
dxo.AfterCreate();

//-->
</script>
                                
	</div>
                    
</div><table id="cbpMain_LP" class="dxpnlLoadingPanelWithContent_DevEx dxlpLoadingPanelWithContent_DevEx" style="left:0px;top:0px;z-index:30000;display:none;">
	<tr>
		<td class="dx" style="padding-right:0px;"><img class="dxlp-loadingImage dxlp-imgPosLeft" src="/DXR.axd?r=1_37-VM8ue" alt="" style="vertical-align:middle;" /></td><td class="dx" style="padding-left:0px;"><span id="cbpMain_TL">Loading&hellip;</span></td>
	</tr>
</table><div id="cbpMain_LD" class="dxpnlLoadingDivWithContent_DevEx dxlpLoadingDivWithContent_DevEx dx-ft" style="left:0px;top:0px;z-index:29999;display:none;position:absolute;">

</div><script id="dxss_149242808" type="text/javascript">
<!--

var dxo = new ASPxClientCallbackPanel('cbpMain');
dxo.InitGlobalVariable('cbpMain');
dxo.callBack = function(arg) { WebForm_DoCallback('cbpMain',arg,ASPx.Callback,'cbpMain',ASPx.CallbackError,true); };
dxo.hideContentOnCallback=false;
dxo.AfterCreate();

//-->
</script>

        </div>
        <div class="buttonbar"> 
            <div class="buttonbar"> 
            <div class="resetbuttons">
                <div class="dxbButton_DevEx resetpage dxbButtonSys dxbTSys" id="btnClear" style="font-size:X-Large;height:100px;width:190px;">
	<div class="dxb">
		<input id="btnClear_I" class="dxb-hb" value="Clear" type="button" name="btnClear" /><span class="dx-vam">Clear</span>
	</div>
</div><script id="dxss_1865466635" type="text/javascript">
<!--
ASPx.AddHoverItems('btnClear',[[['dxbButtonHover_DevEx'],[''],[''],['','TC']]]);
ASPx.AddPressedItems('btnClear',[[['dxbButtonPressed_DevEx'],[''],[''],['','TC']]]);

var dxo = new ASPxClientButton('btnClear');
dxo.InitGlobalVariable('btnClear');
dxo.autoPostBack = true;
dxo.RegisterServerEventAssigned(['Click']);
ASPx.AddSelectedItems('btnClear',[[['dxbf'],[''],['CD']]]);
dxo.useSubmitBehavior = false;
dxo.autoPostBackFunction = function(postBackArg) { __doPostBack("btnClear", postBackArg); };
dxo.causesValidation = false;
dxo.AfterCreate();

//-->
</script>
                <div class="dxbButton_DevEx resetsession dxbButtonSys dxbTSys" id="btnReset" style="font-size:X-Large;height:100px;width:190px;">
	<div class="dxb">
		<input id="btnReset_I" class="dxb-hb" value="Reset Session" type="button" name="btnReset" /><span class="dx-vam">Reset Session</span>
	</div>
</div><script id="dxss_1413622579" type="text/javascript">
<!--
ASPx.AddHoverItems('btnReset',[[['dxbButtonHover_DevEx'],[''],[''],['','TC']]]);
ASPx.AddPressedItems('btnReset',[[['dxbButtonPressed_DevEx'],[''],[''],['','TC']]]);

var dxo = new ASPxClientButton('btnReset');
dxo.InitGlobalVariable('btnReset');
dxo.autoPostBack = true;
dxo.RegisterServerEventAssigned(['Click']);
ASPx.AddSelectedItems('btnReset',[[['dxbf'],[''],['CD']]]);
dxo.useSubmitBehavior = false;
dxo.autoPostBackFunction = function(postBackArg) { __doPostBack("btnReset", postBackArg); };
dxo.causesValidation = false;
dxo.AfterCreate();

//-->
</script>
            </div>

                    
                    

               
        </div>
            <script src="http://code.jquery.com/jquery.js"></script>

            <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
            <script>
            $(function() {
              var success = $('#successSound')[0];
              var fail = $('#failSound')[0];
              $('#txtKanban.text').change(function () {
                $.ajax({
                    url: 't2512.php',
                    data: { txtKanban this.value },
                    type: 'POST',
                    dataType:'JSON'
                }).then(function(resp) {
                   if (resp.status) {
                      success.play();
                   }
                   else {
                     fail.play();
                   }
                });
              });
            });
            </script>

           <script>                   
               
               //var x = document.getElementById("//rdpsvr//c$//Sounds//bad.mp3");

               //function playAudio() {
               //    x.play();
               //}

                //function Sound() {
                //    document.getElementById("Audio1").src = "//rdpsvr//c$//Sounds//bad.mp3"
                //}

              //  if (!("autofocus" in document.createElement("txtKanban"))) {
              //      setfocusKanban();
              //}

                function setfocusKanban() {
                    if (txtKanban != null) {
                    txtKanban.Focus();
                }
            }

                //Validate and move next
                function processValidate(htmlEvent) {                    
                    if (htmlEvent.keyCode == 13) { 
                    Validate();
                }
            }

            //Callback validation
                function Validate(s, e) {
                if (ASPxClientEdit.ValidateGroup('Group1')) {
                    cbpMain.PerformCallback('');
                }
                }

                //function PlayAudio(id){
                //    document.getElementById('audio'+id).setAttribute("autoplay", "autoplay");
                //}

                
                //// Check for audio element support.
                //if (window.HTMLAudioElement) {
                //    try {
                //        var oAudio = document.getElementById('Bad');
                //        var btn = document.getElementById('play'); 
                //        var audioURL = document.getElementById('\\\rdpsvr\\C$\\Sounds\\bad.wav'); 

                //        //Skip loading if current file hasn't changed.
                //        if (audioURL.value !== currentFile) {
                //            oAudio.src = audioURL.value;
                //            currentFile = audioURL.value;                       
                //        }                   
                //    }
                //    catch (e) {
                //        // Fail silently but show in F12 developer tools console
                //        if(window.console && console.error("Error:" + e));
                //    }
                //}


                //var sObject = null;
                //function Bad() {
                //    if (sObject != null) {
                //        document.body.removeChild(sObject);
                //        sObject.removed = true;
                //        sObject = null;
                //    }
                //    sObject = document.createElement("embed");
                //    sObject.setAttribute("src", "Sounds/bad.wav");
                //    sObject.setAttribute("hidden", true);
                //    document.body.appendChild(sObject);
                //}

            </script>
        </div>
        
    
<div class="aspNetHidden">

	<input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="889B7F24" />
	<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="tw29yLdh1KDxNNw/aHaIZvKhmSdKgQ34lKzgcw2QQ+ZG6WZxYYT9lMR7AcaDR3cC9o8R3L4kvHW6aMeUm9AFFpvScVANKdSnJvn+G9fjsXu2QpyjFdNkL+Uojb1Ag+EA" />
</div>

<script type="text/javascript">
//<![CDATA[

WebForm_InitCallback();//]]>
</script>
</form>

<!-- Visual Studio Browser Link -->
<script type="application/json" id="__browserLink_initializationData">
    {"appName":"Internet Explorer","requestId":"be92a37d12104b20a61a440dd81946ab"}
</script>
<script type="text/javascript" src="http://localhost:52758/6e87b70f28b0432d9368643f31b8a638/browserLink" async="async"></script>
<!-- End Browser Link -->

</body>
</html>

Open in new window

In the Validate(s, e) function...
  • It looks like 's' is the sender.
  • It looks like 'e' are the event arguments.

However, from the code you've pasted neither of these are being used by the function. So it must be getting it from elsewhere. You'll want to look into the cbpMain.PerformCallback() function to figure out what it's doing.

As @Julian Hansen said, you should consider changing your server-side code for this validation/check to be a service.
Ok, I see what's going on. The control has a listener for the Enter key (whether or not you have to physically press it; the scanner might send it as a scan terminator). That works in conjunction with what amounts to be a submit button via JavaScript.

I can't tell which one is the text field that receives the barcode scan; I think it's either txtKanban or txtBankKanban. Whichever one it is, please paste your design-time configuration for that control? Hopefully what we need to do is as simple as providing a function to that configuration.
Most of the time it is only txtKanban the rest is txtKanban and txtBankKanban, with txtBankKanban being the last one scanned.

<dx:ASPxTextBox ID="txtKanban" runat="server" Width="400px"  ClientInstanceName="txtKanban" OnValidation="txtKanban_Validation" Height="52px" Font-Size="X-Large">
                                            <ClientSideEvents KeyDown="function(s, e) {processValidate(e.htmlEvent);}" Init="function(s, e) {s.Focus();      }" />
                                            <ValidationSettings Display="Dynamic" ErrorTextPosition="Bottom" SetFocusOnError="True">
                                            </ValidationSettings>
                                        </dx:ASPxTextBox>

<dx:ASPxTextBox ID="txtBankKanban" runat="server" Width="400px"  ClientInstanceName="txtBankKanban" OnValidation="txtBankKanban_Validation" Height="52px" Font-Size="X-Large">
                                            <ClientSideEvents KeyDown="function(s, e) {processValidate(e.htmlEvent);}" />
                                            <ValidationSettings Display="Dynamic" ErrorTextPosition="Bottom" SetFocusOnError="True">
                                            </ValidationSettings>
                                        </dx:ASPxTextBox>
In this message you pasted the Validate(s, e) function. Is that function editable in your code?

If so then you are golden -- that's where you'd want to start integrating the stuff that @Julian Hansen sent earlier by commenting out the call to cbpMain.PerformCallback('') and adding in the code as appropriate for your needs.
Yes I can edit Validate(s, e) function.
Perfect. You'll want to use your debugging tools (hitting F12 in your browser) to see what's being passed in the Validate(s, e) function... I think you'll find that the scanned code is somewhere in the e parameter.

I can't immediately see the behavior of this form... so you might also need e.preventDefault(); to be the first line of code in your updated Validate(s, e) function if the form automatically submits.
I don't see where to get the values of e after pressing F12.
click Network Tab and you will see request/responses
click a resource here and you will see details...
I'm assuming you're using Chrome as your browser.
1. Hit F12 and then either go to the page or hit Refresh.

2. Right-click on the scanner text field and hit Inspect Element.
Note: This isn't the only way to do this; it just makes for an easy way to get there.

3. Click the Sources tab on the top of the Tools dialog; this is where you'll be doing the debugging.

4. Locate the page in the pane on the left hand side of the Tools. You might need to click the Sources tab over there as well.

5. Once you've got the page open in the middle pane (by clicking it in the left hand pane) scroll until you find the Validate(s, e) function. Click on the left hand gutter on first line inside the function; that will set a break point. Like so:
User generated image
6. Do a scan like you normally would and then use the debugger to see what's there. While debugging you can mouse over the e parameter or use the console (at the bottom of the Tools dialog) to see what the e parameter contains.
e comes back and says undefined.
Thinking this through a bit more you probably don't really need e; what you really want it the value of the textbox. Using the same breakpoint (assuming your breakpoint is inside the Validate(s, e) function), when you hit it paste this into the console and see what it returns; one of the properties in there should give you want you need for the scan data.

$('#cbpMain$pnlKanban$txtKanban')

Open in new window

We need to locate the ID of the rendered control's textbox. The easiest way to do this is to...
1. Right-click on the textbox (when you see it rendered in the browser) and click Inspect.
2. Look for the id attribute in the HTML that it will display.
3. Do a scan again and when it hits the breakpoint type the following into the console and see what comes back:
$('#{the_id_you_found_in_#2_above_without_these_curly_braces}')

Open in new window

Right; now we need to expand that error in the debugger and look at its properties. We're particularly interested in whatever value is.
Here is value and it matches what I input into the textbox, expecting a bad scan.
User generated imageUser generated image
Perfect. Now you need to use that with the solution that @Julian Hansen provided earlier.

Here you need to create a folder called media and add the two wave files (success.wav and fail.wav) to it. Note that they don't have to be .wav files; that's just what he put in the solution. You can use whatever media type that the <audio> element will play.
<audio id="successSound">
    <source src="media/success.wav" type="audio/wav">
</audio>
<audio id="failSound">
    <source src="media/fail.wav" type="audio/wav">
</audio>

Open in new window


<script>
$(function() {
  var scan = $('#cbpMain_pnlKanban_txtKanban_1')[0]; // <=== this just makes the control easier to deal with;
  var success = $('#successSound')[0];
  var fail = $('#failSound')[0];
  scan.change(function() {
    $.ajax({
        url: '/path/to/service', // <=== you still need to create and expose this service endpoint!
        data: {scancode: scan.value},
        type: 'POST',
        dataType:'JSON'
    }).then(function(resp) {
       if (resp.status) {
          success.play();
       }
       else {
         fail.play();
       }
    });
  });
});
</script>

Open in new window

Note that I added a variable called scan and set it to the scan control $('#cbpMain_pnlKanban_txtKanban_1')[0]. This is just to make the code easier to work with.

Don't forget to create that endpoint so that your $.ajax call will work.

Don't forget to at least comment out the code that is inside of Validate(s, e). Really you should consider going through the page and getting rid of any JavaScript code that isn't being explicitly used.

All credit should go to @Julian Hansen as his answers were the ones that provided the code examples.
All credit should go to @Julian Hansen as his answers were the ones that provided the code examples
Thank you but I disagree - azarc3 is carrying the ball to the finish line and is deserving of at least an equal split on this.
I am confused on what service I need to create and expose here,

url: '/path/to/service', // <=== you still need to create and expose this service endpoint!
Right now you are posting back to the page and that postback is handled in the page code behind. You could probably hack a way to make this work but that's not the route to go.

Instead, add a new Web Service (.ASMX) item to your website project and move the code from your code behind that currently handles the scan to that service. Then, update the url part of your ajax call to point to that service.
Not sure how well that would work.  I have attached the code for the page (it's messy and inherited it).
Scan-ASPX.htmlScan-Code-Behibd.cs
Your web service (.asmx) will look something like this:

using Netwonsoft.Json;

public class ScanValidationResult
{
	public string ErrorText { get; set; }

	public bool IsValid { get; set; }

	public int SoundToPlay { get; set; }

	public bool ShouldProcessSlot { get; set; }
}

/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{

	[WebMethod]
	public string HelloWorld(bool bBankKanbanValid, string scan)
	{
		var scanResult = new ScanValidationResult();
		if (!bBankKanbanValid)
		{
			bool result = false;
			Regex vanRegex = new Regex("([0-9A-Z]{3})+-([0-9A-Z]{2})+\\s+([A-Z]{2})+([0-9A-Z]{10})");
			Regex suvRegex = new Regex("([0-9A-Z]{2})+-([0-9A-Z]{2})+\\s+([A-Z]{2})([0-9A-Z]{10})");
			Match vanMatch = vanRegex.Match(scan);
			Match suvMatch = suvRegex.Match(scan);
			bool match = false;
			VehicleType model = new VehicleType();

			if (vanMatch.Success)
			{
				match = true;
				model = VehicleType.van;
			}
			else if (suvMatch.Success)
			{
				match = true;
				model = VehicleType.suv;
			}
			else
			{
				match = false;
			}

			if (match)
			{
				bool kanbanMatch = false;

				if (model == VehicleType.van)
				{
					string seqKanban = txtKanban.Text.Substring(0, 9);
					string bankKanban = txtBankKanban.Text.Substring(0, 9);

					if (seqKanban == bankKanban)
					{
						kanbanMatch = true;
					}
				}

				if (model == VehicleType.suv)
				{
					string seqKanban = txtKanban.Text.Substring(0, 9).Trim();
					string bankKanban = txtBankKanban.Text.Substring(0, 8);
					scanResult.ErrorText = " SEQ: " + seqKanban + " bank: " + bankKanban;

					if (seqKanban == bankKanban)
					{
						kanbanMatch = true;
					}
				}

				if (!kanbanMatch)
				{
					scanResult.IsValid = result;
					scanResult.ErrorText += " Labels do not match!";
					scanResult.SoundToPlay = 2;
				}
				else
				{
					scanResult.IsValid = true;
					scanResult.ErrorText = string.Empty;
					scanResult.ShouldProcessSlot = true;
				}
			}
			else
			{
				scanResult.IsValid = result;
				e.ErrorText = "Incorrect kanban format!";
				scanResult.SoundToPlay = 2;
			}
		}

		return JsonConvert.SerializeObject(scanResult);
	}
}

Open in new window


Basically, pass in whatever values you need (such as bBankKanbanValid and the scanned text) and then pass back what would have been done in the code behind. In this case the url value of your ajax call will be /WebService1.asmx.
I'm still doing something wrong, this code runs but no sound.  Here is what I have.
HTML.htmlCodeBehind.csASMX.csUser generated imageUser generated image
Looking at your webservice output I'm not surprised. The SoundToPlay property is null. You need to debug your webservice method and make sure it always sets SoundToPlay to the value for the fail sound if it's not going to set it to the value for the success sound.

You also need to debug the javascript function itself to ensure that all the proper values are being sent to the web service.

I've modified your HTML file a bit; review the changes and update your WebForm accordingly. Apparently the EE editor doesn't like my tabs, hopefully -- when you copy it out your files -- it should format properly.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<script src="http://code.jquery.com/jquery.js"></script>
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
	<audio id="successSound">
		<source src="media/success.wav" type="audio/wav" />
	</audio>
	<audio id="failSound">
		<source src="Sounds/bad.wav" type="audio/wav" />
	</audio>

	<form id="form1" runat="server">
		<div style="text-align: center; width: 100%; height: 265px;"></div>
		<div class="buttonbar"></div>
	</form>
	<script>
		$(function() {
		  var scan = $('#cbpMain_pnlKanban_txtKanban_1')[0];
		  var success = $('#successSound')[0];
		  var fail = $('#failSound')[0];
		  scan.change(function() {
			$.ajax({
				url: 'http://localhost/WebService/Audio.asmx',
				data: {scancode: scan.value},
				type: 'POST',
				dataType:'JSON'
			})
			.done(function(resp) {
				if (!resp) {
					alert('response was null!');
					return;
				}
				
				if (resp.status) {
					success.play();
				}
				else {
					fail.play();
				}
			})
			.fail(function(error) {
				alert('There was an error. Place a debug breakpoing here (using the dev tools) to see what is inside the error object');
			})
			.always(function() {
				alert('ajax call complete');
			});
		  });
		});
	</script>
</body>
</html>

Open in new window


In this scenario there is no value in placing a call to the webservice file from your codebehind. I'd suggest you remove that event entirely as it should not be called anyway and might lead to confusion in the future.

You'll want to place a breakpoint in your webservice to make sure that the ajax call is actually going there as well.
In the script I see this error

Uncaught TypeError: Cannot read property 'change' of undefined
User generated image
Makes sense. A few minor adjustments to try:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<script src="http://code.jquery.com/jquery.js"></script>
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
	<audio id="successSound">
		<source src="media/success.wav" type="audio/wav" />
	</audio>
	<audio id="failSound">
		<source src="Sounds/bad.wav" type="audio/wav" />
	</audio>

	<form id="form1" runat="server">
		<div style="text-align: center; width: 100%; height: 265px;"></div>
		<div class="buttonbar"></div>
	</form>
	<script>
		$(function() {
		  var scan = $('#cbpMain_pnlKanban_txtKanban_1');
		  var scanValue = scan[0].value;
		  var success = $('#successSound')[0];
		  var fail = $('#failSound')[0];
		  scan.change(function() {
			$.ajax({
				url: 'http://localhost/WebService/Audio.asmx',
				data: {scancode: scanValue},
				type: 'POST',
				dataType:'JSON'
			})
			.done(function(resp) {
				if (!resp) {
					alert('response was null!');
					return;
				}
				
				if (resp.status) {
					success.play();
				}
				else {
					fail.play();
				}
			})
			.fail(function(error) {
				alert('There was an error. Place a debug breakpoing here (using the dev tools) to see what is inside the error object');
			})
			.always(function() {
				alert('ajax call complete');
			});
		  });
		});
	</script>
</body>
</html>

Open in new window


If that doesn't work you'll need to use your Dev Tools to figure out what scan and scanValue need to be.
I get an error saying it cant find http://localhost:27139/media/success.wav

User generated image
2 errors.

Uncaught TypeError: Cannot read property 'value' of undefined
    at HTMLDocument.<anonymous> (KanbanValidation.aspx:248)
    at fire (jquery.js:3119)
    at Object.fireWith [as resolveWith] (jquery.js:3231)
    at Function.ready (jquery.js:3443)
    at HTMLDocument.completed (jquery.js:3474)

media/success.wav Failed to load resource: the server responded with a status of 404 (Not Found)
Looks like you're getting two errors.
1. You still need to figure out what the jQuery object you're looking for is. Otherwise scan will always be undefined and change() won't exist for it. To find it, put a breakpoint at line 20 of the code I sent last time and run the following using the console:
$('#cbpMain_pnlKanban_txtKanban_1')

Open in new window

If that exists then try the following:
$('#cbpMain_pnlKanban_txtKanban_1').change

Open in new window

Note that there are no parenthesis at the end of this command; we just want to see if the function exists.

2. Does your success.wav file live in the /root/media folder of your application?
Only error

Uncaught TypeError: Cannot read property 'value' of undefined
    at HTMLDocument.<anonymous> (KanbanValidation.aspx:248)
    at fire (jquery.js:3119)
    at Object.fireWith [as resolveWith] (jquery.js:3231)
    at Function.ready (jquery.js:3443)
    at HTMLDocument.completed (jquery.js:3474

User generated image
.... So... that definitely won't work. You've effectively told the JavaScript engine that blah-blah-blah.change is a jQuery object. You should change that back and use the console command line (it's at the bottom of the Dev Tools; if you don't see it while on the Sources tab press ESC) and run that command.
What am I wanting from the console?
You need to figure out why the scan variable isn't a jQuery object.
I noticed that when the page first loads it finds the audio variables but not when the a scan is entered.

User generated image
It seems you've gone back to using the code that you directly copied and pasted from @Julien Hansen. That code was a guide that you were expected to model after or update accordingly... so unless you have added a field with an ID of scancode (or changed your txtKanban field ID to scancode you're never going to have that function fire. It's hitting that breakpoint because it's hitting the initial scan for functions, not because of a direct function call.

You'll definitely wan to move the scan, success and fail variables into the change() function. They should be right before the $.ajax() call.
I am getting this error on the scan now, in the jquery.js file.

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

User generated image
Here is the function

<script>
                $(function () {
                        var scan = $('#cbpMain_pnlKanban_txtKanban_I');
                        var scanValue = scan[0].value;
                        var success = $('#successSound')[0];
                        var fail = $('#failSound')[0];
                        scan.change(function() {
                            $.ajax({
                                url: 'http://localhost:27139/WebService/Audio.asmx',
                                data: {scancode: scanValue},
                                type: 'POST',
                                dataType:'JSON'
                            })
                            .done(function(resp) {
                                if (!resp) {
                                    alert('response was null!');
                                    return;
                                }
                        
                                if (resp.status) {
                                    success.play();
                                }
                                else {
                                    fail.play();
                                }
                            })
                            .fail(function(error) {
                                alert('There was an error. Place a debug breakpoing here (using the dev tools) to see what is inside the error object');
                            })
                            .always(function() {
                                alert('ajax call complete');
                            });
                        });
                    });
            </script>
As I said before, you need to put a breakpoint in your web service to ensure that you're actually reaching it and to see what's happening inside it.
I have one but as soon as it  gets to this line, I get the error.

$(function () {
OK, I was able to get info  from error object and this object.

Error: Object

User generated image
This: Object

User generated image
What's happening is that it's executing the $.ajax() call immediately when the DOM says that it's finished loading. Updating the code I provided earlier this morning...
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<script src="http://code.jquery.com/jquery.js"></script>
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
	<audio id="successSound">
		<source src="media/success.wav" type="audio/wav" />
	</audio>
	<audio id="failSound">
		<source src="Sounds/bad.wav" type="audio/wav" />
	</audio>

	<form id="form1" runat="server">
		<div style="text-align: center; width: 100%; height: 265px;"></div>
		<div class="buttonbar"></div>
	</form>
	<script>
		$(function() {
		  var scan = $('#cbpMain_pnlKanban_txtKanban_1');
		  scan.change(function() {
			if(scan.length > 0) {
				var scanValue = scan[0].value;
				if(scanValue && scanValue.length > 0) {
					var success = $('#successSound')[0];
					var fail = $('#failSound')[0];
					$.ajax({
						url: 'http://localhost/WebService/Audio.asmx',
						data: {scancode: scanValue},
						type: 'POST',
						dataType:'JSON'
					})
					.done(function(resp) {
						if (!resp) {
							alert('response was null!');
							return;
						}
						
						if (resp.status) {
							success.play();
						}
						else {
							fail.play();
						}
					})
					.fail(function(error) {
						alert('There was an error. Place a debug breakpoing here (using the dev tools) to see what is inside the error object');
					})
					.always(function() {
						alert('ajax call complete');
					});
				}
			}
		  });
		});
	</script>
</body>
</html>

Open in new window


That should keep the $.ajax() call from firing immediately.
I replaced it,  Here is what I get now.

Response Text

"<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><soap:Fault><soap:Code><soap:Value>soap:Receiver</soap:Value></soap:Code><soap:Reason><soap:Text xml:lang="en">System.Web.Services.Protocols.SoapException: Server was unable to process request. ---&gt; System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
   at System.Xml.XmlTextReaderImpl.Throw(Exception e)
   at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
   at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()
   at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
   at System.Xml.XmlTextReaderImpl.Read()
   at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.Read()
   at System.Xml.XmlReader.MoveToContent()
   at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.MoveToContent()
   at System.Web.Services.Protocols.SoapServerProtocolHelper.GetRequestElement()
   at System.Web.Services.Protocols.Soap12ServerProtocolHelper.RouteRequest()
   at System.Web.Services.Protocols.SoapServerProtocol.RouteRequest(SoapServerMessage message)
   at System.Web.Services.Protocols.SoapServerProtocol.Initialize()
   at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean&amp; abortProcessing)
   --- End of inner exception stack trace ---</soap:Text></soap:Reason><soap:Detail /></soap:Fault></soap:Body></soap:Envelope>"

Error Object

User generated image
What happens when you directly browse to http://localhost/WebService/Audio.asmx using your browser?
I see this.

User generated image
I changed this line url: 'http://localhost:27139/WebService/Audio.asmx', to url: 'http://localhost:27139/WebService/Audio.asmx/KanbanValidation',

now Response Text is

"System.InvalidOperationException: Missing parameter: bKanbanValid.
   at System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection collection)
   at System.Web.Services.Protocols.HtmlFormParameterReader.Read(HttpRequest request)
   at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
   at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
"
Never mind; I see that you're going to get the MEX output.

It's been so long since I've worked with WebForms and ASMXs that I forgot you need an additional decorator on their function definitions to allow them to work with ajax. Update your service definition as follows:

/// <summary>
    /// Summary description for Audio
    /// </summary>
    [WebService(Namespace = "http://localhost/WebService/Audio.asmx")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]  // <=== this part has been uncommented
    public class Audio : System.Web.Services.WebService

Open in new window

Did

Response Text

"System.InvalidOperationException: Missing parameter: bKanbanValid.
   at System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection collection)
   at System.Web.Services.Protocols.HtmlFormParameterReader.Read(HttpRequest request)
   at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
   at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
"
Could I be missing something in my web.config?
No. You've told it that to be a valid call it needs to have a Boolean parameter called bBankKanbanValid and a string parameter called scan.

Try this: http://localhost:27139/WebService/Audio.asmx/KanbanValidation?bBankKanbanValid=true&scan=abcdefg
Result



[InvalidOperationException: Request format is unrecognized for URL unexpectedly ending in '/KanbanValidation'.]
   System.Web.Services.Protocols.WebServiceHandlerFactory.CoreGetHandler(Type type, HttpContext context, HttpRequest request, HttpResponse response) +169669
   System.Web.Services.Protocols.WebServiceHandlerFactory.GetHandler(HttpContext context, String verb, String url, String filePath) +209
   System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated) +48
   System.Web.MaterializeHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +339
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
If I use the Invoke method this is the url I get:
             http://localhost:27139/WebService/Audio.asmx/KanbanValidation

And this is the result

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<string xmlns="http://localhost:27139/WebService/Audio.asmx/KanbanValidation">
{"ErrorText":null,"IsValid":false,"SoundToPlay":2,"ShouldProcessSlot":false}
</string>
In the function you sent, where does scancode come from?

data: { scancode: scanValue }
I'm getting values, but it never seems to get a response, this never gets executed.

if (resp.status) {
 success.play();
   }
 else {
  fail.play();
 }

User generated image
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks for all the help.
@triplebd69,
You are welcome but I am going to open this question and ask you to regrade. I might have supplied some of the code on this but azarc3 really went in to bat for you on this one and should get recognition for that.