Building a registration form using webmatrix,asp.net & Javascript,sql server CE. I'm writing an onblur event for the Username textbox.When focus leaves the textbox, it checks if there is an exisiting username in database and displays a label if yes.The foll. code is not working as js code is ignored if inside the "#{}" block. It works fine outside the "#{}" block but then i cant give a condition there.Please help me out.
<html>
<head>
<script>
function RegUsernameLeave()
{
#{
regusername=Request.Form["regusername"];
if(!regusername.IsEmpty())
{
var db = Database.Open("myshop");
int usercount = db.QueryValue("select count(*) from webusers where username=#0",regusername);
db.Close();
if(usercount!=0){
document.getElementById("msg").innerHTML="Username already exists";}
}
}
}
</script>
</head>
<body>
<label>Username:</label>
<p><input type="text" id="regusername" onblur="RegUsernameLeave()"/>
<label id="msg"></label></p>
</body>
</html>
I'm taking a complete stab in the dark here.. but maybe something along these lines?
Basically - I'm assuming that anything #{} is printed out into the JS - so if we can executed the server side code and output it equal to your JS variable userCount then you can use that JS Variable to do your checking and output the error message (if necessary)
#functions{
public int GetUserCount() {
string regusername = Request.Form["regusername"].ToString();
if(!regusername.IsEmpty())
{
var db = Database.Open("myshop");
int usercount = db.QueryValue("select count(*) from webusers where username='#0'",regusername);
db.Close();
return usercount;
}
return 0;
}
}
function RegUsernameLeave()
{
var userCount = #GetUserCount();
if (userCount > 0)
document.getElementById("msg").innerHTML="Username already exists";
}
Related
In my controller I have this function:
Function AppError() As ActionResult
Dim myScript As Object = "popup(" + Properties.postError + ")"
Return RedirectToAction("main", myScript)
End Function
With this function I want to call my razor page where I have a Javascript named popup whith a parameter Properties.postError.
My script is:
<script type="text/javascript">
var errMsg;
function popup(msg) {
errMsg = msg;
window.alert(errMsg);
window.window.focus();
if (window.confirm)
errmsg = '';
msg = '';
}
</script>
What I need is to popup the error message.
I follow the programm thru my debugger and I saw that it goes to my page.
But no error message window raise up.
I have already search in the web for this option without any success.
Is someone to assist me on this issue?
ADDITION - 16/2/19 12:50
what I have done so far is the following:
Function CBError() As ActionResult
Dim myScript As Object = "popup(" + Properties.postError + ")"
ViewData.Add(New KeyValuePair(Of String, Object)("ScriptName", myScript))
Return View("main", myScript)
End Function
As we can see I've change the function by addiding the ViewData
I Add a value pair arguments 1) the name 2) the value
The action of addition it works just fine and the dictionery receive it.
I my script (which is in my reazor page) I put the following:
<script type="text/javascript">
var vd = #ViewData.Item(0);
function popup(msg) {
var errMsg;
errMsg = msg;
window.alert(errMsg);
window.window.focus();
if (window.confirm)
errmsg = '';
msg = '';
//{ window.location.href = "/" }
}
</script>
When I stop (with the bebugger) in the instruction var vd = #ViewData.Item(0); I see that the ViewData is complitely empty. No values no nothing.
I also add this window.onload = #Html.Raw(ViewBag.MyScript);
And in debugger threw me an error
"Uncaught SyntaxError: Unexpected token ;"
Is there somone to instruct me why that happen?
ADDITION - 16/2/19 20:00
New version of function and Script
Function CBError() As ActionResult
Dim myScript As Object = Properties.postError
ViewData.Add(New KeyValuePair(Of String, Object)("Message", myScript))
Return View("main")
End Function<br/>
<script type="text/javascript">
$(document).ready(function (){
alert("#ViewData.Values(0)");
});
</script>
With this version I put the message value to the ViewData
But when the program comes to the point of script then all the ViwData is empty.
No Values no Keys no nothing.
It seems somewhere in the middle it lose all the data
FINAL UPDATE 17/2/19 11:13
The problem has been solved ... but not by the way we are wearing.
It was solved in an extremely simple way.
What we were asking for was to get the error message on the page we are in. From any point of the code.
So I followed the method of rendering the message to property and I read this message from the page with the following Javascript.
The function is:
Function CodePage_Error() As ActionResult
Return View("main")
End Function
End the Javascript is:
<script type="text/javascript">
$(document).ready(function () {
if ("#Properties.InnerError" !== "") {
var msg = "#Properties.InnerError";
window.alert(msg);
} else {
return false;
}
});
The Javascript is placed in the mainLayout.vbhtml file
Generally speaking, it turned out that the transfer method from the controller to the page is not possible in the MVC4 environment
You could pass the error message to the page via Viewbag, and then put the pop up script inside the document ready javascript function to check the message and display the error if required.
Controller:
public IActionResult Index()
{
ViewBag.Message = "this is your message";
return View();
}
View:
<script type="text/javascript">
$(document).ready(function (){
alert("#ViewBag.Message");
});
I think passing JS code through RedirectToAction route value parameter is not a good idea because some special characters will be encoded. You should use either ViewBag or viewmodel properties and pass the script to view in unencoded state.
Here is an example setup:
1) Use ViewBag or a viewmodel property to contain the script you want to execute in the view.
Public Function AppError() As ActionResult
' define Properties.postError here
Dim myScript As String = "popup(" + Properties.postError + ")"
ViewBag.MyScript = myScript
Return View()
End Function
2) Use an event handler e.g. window.onload assigned with #Html.Raw() from ViewBag or viewmodel property to pass unencoded function call inside <script> tag. The event handling must be placed outside function block.
<script type="text/javascript">
var errMsg;
function popup(msg) {
errMsg = msg;
window.alert(errMsg);
window.window.focus();
if (window.confirm)
errmsg = '';
msg = '';
}
// the popup will be called here
window.onload = #Html.Raw(ViewBag.MyScript)
</script>
Note that window.onload will pop up the message after the view is loaded, if you want to pop up the message in another event use any desired event handler instead (also check list of available JS DOM events).
I am running a database app (sql backend). One particular form calls a value from another table using the follwing:
<td class=NewSalesOpCompany id="contactPostCode"><#externalfield SQL="Select POSTALCODE from wce_sales s join wce_linkto l on s.UNIQUEID = l.luniqueid left join wce_contact c on l.LEntityID = c.UNIQUEID where (s.UNIQUEID = '<#field field=uniqueid noedit static>')" ></td>
The above code populates the field with post-code data in text format which works fine. I then want to copy the data in that field to another field. I have tried the folwing but failed to get it to work.
<script language=javascript>
function copyPostCode() {
var parentPOSTALCODE=document.getElementById('contactPostCode');
var oppPOSTCODE=document.forms[0]._POSTCODE;
if (oppPOSTCODE != parentPOSTALCODE)
{ oppPOSTCODE.value = parentPOSTALCODE.value;}
}
</script>
When executing the function I get "parentPOSTALCODE.value is undefined" error via firefox. I'm a bit of a newbie at this so any help would be appreciated.
Try this:
<script language=javascript>
function copyPostCode() {
var parentPOSTALCODE=document.getElementById('contactPostCode');
var oppPOSTCODE=document.forms[0]._postcode;
if (oppPOSTCODE != parentPOSTALCODE)
{
oppPOSTCODE.value = parentPOSTALCODE.innerText;
}
}
</script>
Here is the example FIDDLE
I'm using Twilio to make a call from a browser to the phone. When I click call I get this error Uncaught twilio.exception wrong number of segments
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
Twilio.Device.setup('#token');
Twilio.Device.ready(function (device) {
$("#log").text("Client '#clientName' is ready");
});
Twilio.Device.error(function (error) {
$("#log").text("Error: " + error.message);
});
Twilio.Device.connect(function (conn) {
$("#log").text("Successfully established call");
});
Twilio.Device.disconnect(function (conn) {
$("#log").text("Call ended");
});
Twilio.Device.incoming(function (conn) {
$("#log").text("Incoming connection from " + conn.parameters.From);
// accept the incoming connection and start two-way audio
conn.accept();
});
function call() {
// get the phone number or client to connect the call to
params = { "PhoneNumber": $("#number").val() };
Twilio.Device.connect(params);
}
function hangup() {
Twilio.Device.disconnectAll();
}
</script>
<div class="hero-unit" style="background-color: white; margin-left: 650px;">
<div class="container">
<h3>Call us and watch us answer!</h3>
<p style="margin-left: -65px;">Use Twilio to call our office and watch us answer on camera!</p>
<button class="call" onclick="call();">
Call
</button>
<button class="hangup" onclick="hangup();">
Hangup
</button>
<input type="text" id="number" name="number"
placeholder="Enter a phone number or client to call" />
</div>
</div>
In the code behind I have:
public string TwilioToken
{
get
{
string accountSid = "*************";
string authToken = "*************";
string applicationSid = "************";
string clientName = "*****";
if (Request["client"] != null)
{
clientName = Request["client"];
}
var capability = new TwilioCapability(accountSid, authToken);
capability.AllowClientOutgoing(applicationSid);
capability.AllowClientIncoming(clientName);
return capability.GenerateToken();
}
}
Twilio evangelist here.
I can't quite tell how you are getting the value of the TwilioToken property to render in your HTML. In this line of the JavaScript:
Twilio.Device.setup('#token');
#token should be being replaced by the value being generated in your code-behind. Since you mention code-behind it sounds like you might be using WebForms. In order to render the value of the TwilioToken property in your HTML you'd need to use something like this syntax:
Twilio.Device.setup('<%= TwilioToken %>');
Once you do that when you load the page in a browser you should see that syntax replaced by a long encoded string of characters that Twilio uses to setup the JavaScript library.
Hope that helps.
The sample code shows lines like this:
$capability = new Services_Twilio_Capability($TWILIO_SID, $TWILIO_TOKEN);
$capability->allowClientOutgoing('APabe7650f654fc34655fc81ae71caa3ff');
$TOKEN = $capability->generateToken();
Followed by later on this:
Twilio.Device.setup("<?php echo $TOKEN; ?>");
I was getting this same error until I realized that I had misspelled $TOKEN and was passing a blank string to Twilio.Device.setup. After fixing it, the error went away.
So I am having a problem with HTML5 and javascript.
I made a few .js files for the javascript part and I made the link to connect it with the HMTL code but it will not show the javascript part.
This is my HTML
<!doctype html>
<html lang="en">
<head>
<title>Gateway Tunes</title>
<meta charset="utf-8" />
<script src="playlist_store.js"></script>
<script src="playlist.js"></script>
</head>
<body>
<form>
<input type="text" id="songTextInput" size="40" placeholder="Song name">
<input type="button" id="addButton" value="Add Song">
</form>
<ul id="playlist">
</ul>
</body>
</html>
and here are my javascript files; the names of the files are at the top
playlist_store.js
function save(item) {
var playlistArray = getStoreArray("playlist");
playlistArray.push(item);
localStorage.setItem("playlist", JSON.stringify (playlistArray));
}
function loadPlaylist() {
var playlistArray = getSavedSongs();
var ul = document.getElementById('playlist");
if (playlistArray !Null) {
for (var i = 0; i < playlistArray.length; i++) {
li.innerHTML = playlistArrray[i];
ul.appenChild(li);
}
}
}
function getSavedSongs() {
return getStoreArray("playlist")
}
function getStoreArray (key);
var playlistArray = localStorage.getItem(key);
if(playlistArray == null || playlistArray == "") {
playlistArray = new Array();
}
else {
playlistArray = JSON.parse (playlistArray);
}
return playlistArray;
}
playlist.js
window.onload = init;
function init() {
var button = document.getElementById ("addButton");
button.onclick = handleButtonClick;
loadPlaylist();
}
function handleButtonClick () {
var textInput = document.getElementById("songTextInput");
var songName = textInput.value;
if (songName == "") {
alert("Button was clicked!");
}
else {
alert("Your track has been added!");
}
var li = document.createElement("li");
li.innerHTML = songName;
var ul = document.getElementById("playlist");
ul.appendChild(li);
save (songName);
}
You've got some syntax errors so your javascript isn't running.
In playlist_store.js
var ul = document.getElementById('playlist");
Opens a string with ' but tries to close it with ". It doesn't matter which you use as long as you're consistent, so you can either change it to 'playlist' or "playlist".
if (playlistArray !Null) {
If you're trying to make sure playlistArray isn't null you can do
if (playlistArray != null) {
notice != as the comparison and null needs to be lowercase. If you want to make sure it isn't just undefined or null you can simply do if (!playlistArray).
ul.appenChild(li); needs to be ul.appendChild(li);.
I'm sure there's more, check over your code.
The first line of your script (and the only one that isn't just a function definition) is window.onload = init;. This means that after the page has loaded, your init function is called.
This function looks up the element with id addbutton, and then calls a method on the returned result. Since you don't have an element with this ID, there won't be any object returned, and so an exception will be thrown (something like "button is null or not an object", depending on your browser). This exception stops the method from executing further - and in particular, loadPlaylist() will not be called.
The moral of the story here though is pay attention to the JavaScript error console, especially while you're doing development! You browser will almost certainly have displayed a red exclamation mark icon or similar, which you could double-click to give you the name, message and location of the exception.
You really don't need to post your code listing on Stack Overflow to ask us what's wrong with it, when your browser is already capable of telling you exactly where the problem is.
I have a small problem . If page is refreshed using F5 , TextBox should preserve its old value . In Page_Load() , if i keep // Loading(); then TextBox1 preserve its old value.
As soon as i remove comment , it loose value in TextBox1 .
Please tell me the reason behind it and What should be done to avoid it .
<script type="text/javascript">
function TextBox1_TextChanged() {
<%
Session["HitCount1"] = TextBox1.Text ;
%>
}
function getMyvalSession() {
var ff = "Loading Value";
return ff;
}
</script>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" Name="TextBox1" runat="server"
AutoPostBack='true' onchange="TextBox1_TextChanged()"></asp:TextBox>
<%
string x = null;
x = Session["HitCount1"].ToString().Trim();
if ((x.Equals(null)) || (x.Equals("")))
{
// Session Variable is either empty or null .
}
else
{
TextBox1.Text = Session["HitCount1"].ToString();
}
%>
</form>
</body>
protected void Page_Load(object sender, EventArgs e)
{
// Loading();
}
void Loading()
{
String csname = "OnSubmitScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the OnSubmit statement is already registered.
if (!cs.IsOnSubmitStatementRegistered(cstype, csname))
{
string cstext = " document.getElementById(\"TextBox1\").value = getMyvalSession() ; ";
cs.RegisterOnSubmitStatement(cstype, csname, cstext);
}
}
Combining inline server-side code and code-behind code is generally a bad idea. I would recommend just using the code-behind code.
This code:
function TextBox1_TextChanged() {
<%
Session["HitCount1"] = TextBox1.Text ;
%>
}
... is not going to have the effect of the (server-side) Session entry "HitCount1" getting set to Textbox1.Text, because TextBox1_TextChanged is a client-side function, and your assignment statement is going to happen on the server side. At run time, the chunk of server code will have been removed by the compiler, so TextBox1_TextChanged will be an empty function.
The rule of thumb: Things happen on the client, or they happen on the server on postback, or they happen on the server via Ajax calls. You can't mix client and server code together.
My recommendation: switch to doing everything in code-behind. When you have it working, if you have too many postbacks, investigate Ajax calls.