Bugg error in validation - javascript

Goal:
To enable display a pop up if validation was correct or failure.
Problem:
Somehow it doesn't want to make a
validation of the password.
I tried using Firebug but It can't make debugging for this code for some reason.
Before creating this validation I had this code before:
function validation() {
if (mittXHRobjekt.readyState == 4)
alert("Okey");
}
After doing more improvement by adding validation, The readyState don't work properly. All I did was to improve the function validation only.
The current code with validation is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled 1</title>
<script type="text/javascript">
var mittXHRobjekt = null;
function skapaXHRobjekt() {
try {
XHRobjekt = new XMLHttpRequest();
} catch (err1) {
try {
XHRobjekt = new ActiveXObject("Microsoft.XMLHTTP");
} catch (err2) {
try {
XHRobjekt = new ActiveXObject("Msxml2.XMLHTTP");
} catch (err3) {
XHRobjekt = false;
}
}
}
return XHRobjekt;
}
function validation() {
if (mittXHRobjekt.readyState == 4) {
if (window.document.frmPassword.txtPassword.value == mittXHRobjekt.responseText) {
alert("Correct password");
}
else {
alert("Wrong password");
}
}
alert("no ready state 4");
}
function test(url) {
mittXHRobjekt = skapaXHRobjekt();
if (mittXHRobjekt) {
mittXHRobjekt.onreadystatechange = validation;
mittXHRobjekt.open("GET", url);
mittXHRobjekt.send(null);
}
}
</script>
</head>
<body>
<form id="frmPassword">
<input name="txtPassword" type="password" />
<input name="btnPassword" type="button" value="Evaluation" onclick="test('password.txt')" />
</form>
</body>
</html>

Related

Ajax call with WebMethod is not returning the response

I have a simple code to update the database with simple Ajax call using WebMethod but its not updating in the database.
HTML Markup
<i class="fa fa-file"></i> <%= item2 %>
Client Side Method:
<script type="text/javascript">
$(".newProject").on("click", function () {
$.ajax({
type: "POST",
url: "index.aspx/UpdateCode",
data: 'engCode=' + this.id,
success: function (response) {
// window.location.reload();
alert(response);
}
});
return false;
});
</script>
Server side method:
[WebMethod]
public static int UpdateCode(string Code)
{
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Codes"))
{
int intresult = 0;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Mode", SqlDbType.VarChar, 50).Value = "UpdateCodes";
cmd.Parameters.Add("#Code", SqlDbType.VarChar, 50).Value = Code;
cmd.Connection = con;
try
{
con.Open();
intresult = cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
ex.ToString();
}
finally
{
cmd.Dispose();
if (con != null)
{
con.Close();
}
}
return intresult;
}
}
}
Its posting the right value on click event of hyperlink but not updating the database.
ASP.NET WebMethods do only work with JSON as the data format:
In your Ajax call, you need to add
dataType: "json",
and also supply the data as JSON:
data: {"engCode":this.id},
you are not passing data in correct formate. try this
<script type="text/javascript">
$(".newProject").on("click", function () {
$.ajax({
type: "POST",
url: "index.aspx/UpdateCode",
data: {Code: this.id}
success: function (response) {
// window.location.reload();
alert(response);
}
});
return false;
});
</script>
Try this code also....
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="JavaScriptSample._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>How to call CSharp function in Ajax | JavaScript Sample</title>
<script type="text/javascript">
function getServerTime() {
/// <summary>
/// Call ServerTime web method via ajax request
/// </summary>
if (window.XMLHttpRequest) {
// for IE7+, Firefox, Chrome, Opera, Safari
this.xmlhttp = new XMLHttpRequest();
}
else {
// for IE6, IE5
try {
this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
try {
// older version of Msxml
this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
this.xmlhttp = null;
}
}
}
xmlhttp.onreadystatechange = function() {
/// <summary>
/// Display server time when success
/// </summary>
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// success Status
document.getElementById("ServerTimeResponse").innerHTML = xmlhttp.responseText;
}
}
this.xmlhttp.open("POST", "AjaxServer.asmx/ServerTime", true);
this.xmlhttp.send();
}
</script>
</head>
<body>
<form id="ServerTimeForm" runat="server">
<div>
<input id="ServerTimeButton" type="button" onclick="getServerTime();" value="Get Server Time" />
<div id="ServerTimeResponse" runat="server">
</div>
</div>
</form>
</body>
</html>

Plain Javascript (no JQuery) to load a php file into a div

Hi I don't know javascript but I am required to use it in one of my templates. I was googling around and found a solution whic is like this:
My Index.php file.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<script type="text/javascript">
window.onload = function(){
document.getElementById("aside").innerHTML="<img src='loadingImage.gif'>";
if(XMLHttpRequest) var x = new XMLHttpRequest();
else var x = new ActiveXObject("Microsoft.XMLHTTP");
x.open("GET", "other_content_1.php", true);
x.send("");
x.onreadystatechange = function(){
if(x.readyState == 4){
if(x.status==200) document.getElementById("aside").innerHTML = x.responseText;
else document.getElementById("aside").innerHTML = "Error loading document";
}
}
}
</script>
</head>
<body>
<div id="aside">This is aside</div>
</body>
</html>
My other_content_1.php file
<div id='other-content-1'>
<?php echo 'This text is loading via php command'; ?>
</div>
As this is the only Javascript function in my site I see no reason to load additional JQuery for it. I am sure there must be a way to do this with plain JavaScript / ajax without the need to load JQuery. Can anybody suggest the correct syntax to do so?
I want to happen asynchronously while the page continues to load.
from http://www.tutorialspoint.com/ajax/ , using plain XHR (XmlHttpRequest)
function loadPage() {
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "ajax-example.php", true);
ajaxRequest.send(null);
}
loadPage();
Try this:
window.onload = function(){
aside = document.getElementById("aside");
aside.innerHTML="<img src='loadingImage.gif'>";
if(XMLHttpRequest) var x = new XMLHttpRequest();
else var x = new ActiveXObject("Microsoft.XMLHTTP");
x.open("GET", "other_content_1.php", true);
x.send();
x.onreadystatechange = function(){
if(x.readyState == 4){
if(x.status == 200) aside.innerHTML = x.responseText;
else aside.innerHTML = "Error loading document";
}
}
}
And it is cross browser compatible, you never need the extra 32KB just to make a simple function supported cross browser.

XMLHTTPRequest is not working with IIS integrated Mode

While running the code under classic mode works fine.....but it fails when runnnig under integrated mode.
Here is the code: -
function callAjax(method, request, callback) {
http = newHTTP();
http.open('POST', url, true);
setupHeaders(http, method);
http.onreadystatechange = function () { http_onreadystatechange(http, callback); }
http.send(JSON.stringify(request));
return request.id;
}
function newHTTP() {
if (typeof (window) != 'undefined' && window.XMLHttpRequest)
return new XMLHttpRequest(); /* IE7, Safari 1.2, Mozilla 1.0/Firefox, and Netscape 7 */
else
return new ActiveXObject('Microsoft.XMLHTTP'); /* WSH and IE 5 to IE 6 */
}
function http_onreadystatechange(sender, callback) {
if (sender.readyState == /* complete */4) {
var response = sender.status == 200 ?
JSON.parse(sender.responseText) : {};
response.xmlHTTP = sender;
callback(response);
}
if (sender.readyState == 2 || sender.readyState == 3) {
}
}
function setupHeaders(http, method) {
http.setRequestHeader('Content-Type', 'text/plain; charset=utf-8');
http.setRequestHeader('X-JSON-RPC', method);
}
It returns the following response when running under classic mode: -
"{"id":0,"result":{"serverInfo":{"totalCount":2,"serviceName":"FluorineFx.PageableResult","version":1,"cursor":1,"id":null,"columnNames":["ApplicationId","ApplicationParentID","ParentApp","ChildApp"],"initialData":[[1158,1153,"Apps","App_Application1"],[3159,3161,"Databases","DB_Database1"]]}}}"
Whereas, it returns following when running under integrated mode : -
"
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
</title></head>
<body>
<form method="post" action="xxxxx...." id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEXXXXLTE2MTY2ODcyMjlkZLGuNeIyaZaly9gcTafYavVTQG2payFqxE2OaB+1PjxT" />
</div>
<div>
</div>
</form>
</body>
</html>
"
Due to above response it fails inside http_onreadystatechange() method in this line: -
var response = sender.status == 200 ?
JSON.parse(sender.responseText) : {};
My issue is that why does it returns weird response when running under integrated mode?

Reading a response in javascript from JSP

I am new in learning AJAX and stuck in the first program. Tried to debug but unable to do so.
Below is my code snippet
----------input-ajax.html-------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>HTML PAGE</title>
<script type="text/javascript">
var request=null;
function createRequest(){
try{
request= new XMLHttpRequest();
)catch(e){
try{
request=new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
request= new ActiveXObject("Microsoft.XMLHTTP");
}catch(failed){
request=null;
}
}
}
if(request==null){
alert("Error Creating Request Object");
}
}
function getName(){
alert("getname called");
createRequest();
var url = "showName-ajax.jsp";
request.open("POST",url,true);
alert("before");
request.onreadystatechange = updatePage;
alert("after");
request.send(null);
}
function updatePage(){
//var newName= request.getResponseHeader("r1");
var newName= request.responseText;
var name1 = document.getElementById("name");
replaceText(name1,newName);
}
function replaceText(el, text) {
if (el != null) {
clearText(el);
var newNode = document.createTextNode(text);
el.appendChild(newNode);
}
}
function clearText(el) {
if (el != null) {
if (el.childNodes) {
for (var i = 0; i < el.childNodes.length; i++) {
var childNode = el.childNodes[i];
el.removeChild(childNode);
}
}
}
}
</script>
</head>
<body>
<h1>WELCOME <span id="name"> GUEST</span></h1>
<form method="POST">
<input type="text" name="t1">
<input type="button" value="Show Name" onclick="getName();"/>
</form>
</body>
</html>
----------showName-ajax.jsp------------
<%
String s1=request.getParameter("t1");
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(s1); // Write response body.
%>
But When I run the program (click on the button) nothing happens. Even the alert message that getName function is called does not appear. PLEASE HELP!!!!
Typo:
)catch(e){
should be
}catch(e){
This would show up as an error in the console of your browser. Be sure to always check that first if things don't work like they should.
You have a ) instead of a } here:
try{
request= new XMLHttpRequest();
)catch(e){
So your function never gets defined.
change )catch(e){ to }catch(e){
but
why are you creating request object everytime on button click?
you just need to call "createRequest()" only once on page load event.

xmlHttp.responseText comes empty

xmlHttp.responseText comes empty, what is the problem and solution?
default.aspx :
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="xmlHttpOrnek._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<script type="text/javascript">
var xmlHttp;
function GetXmlHttpObject() {
var xmlHttp = null;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e) {
// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
//--------------------------
function callAjaxFunc(val) {
xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert("Browser does not support HTTP Request");
return;
}
//you can provide your page URL
var url = "Default.aspx";
url = url + "?kod=" + val;
//state change event-this will occur ass soon as response comes from the url
xmlHttp.onreadystatechange = stateChanged;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
function stateChanged() {
if (xmlHttp.readyState == 4)
{ //Display contents
var xmlResponse = xmlHttp.responseText;
if (xmlResponse != '') {
var inputMessage = document.getElementById('txb');
inputMessage.value = xmlResponse.toString();
alert(xmlResponse);
}
}
}
</script>
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:textbox ID="txb" runat="server"></asp:textbox>
<asp:Button ID="btn" runat="server" Text="bas" OnClientClick="callAjaxFunc('y')" />
</form>
</body>
</html>
default.aspx.cs:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace xmlHttpOrnek
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string d = Request.QueryString["kod"];
if (Request.QueryString["kod"] == "y")
{
Response.Write("Başarılı!");
Response.End();
}
}
}
}
I created another project with copy paste of this one; everything is same, but the second one worked. I'm surprised.

Categories