ASP.net PageMethods return undefined - javascript

Hi everyone i trying to get data from cs to js using ToolkitScriptManager.
this is my aspx :
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="../assets/lib/jquery/jquery-2.0.3.js" type="text/javascript"></script>
<script>
$(window).load(function () {
alert(PageMethods.isConnected());
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ToolkitScriptManager runat="Server"
EnablePageMethods="true"
EnablePartialRendering="true" />
<div>
</div>
</form>
</body>
</html>
and this is my code behind
[ScriptMethod, WebMethod]
public static bool isConnected()
{
return true;
}
i dont know, but this keep result undefined, sorry if this is really simple problem for you, but for me so hard, because i am new in asp.net
please help me to fix this problem.

You need to supply a success and a failure callback to the webmethod call as below.
$(window).load(function () {
PageMethods.isConnected(fnsuccesscallback,fnerrorcallback);
});
function fnsuccesscallback(data) {
alert(data);
}
function fnerrorcallback(result) {
alert(result.statusText);
}
Also, there is another way of accessing the page methods using $.ajax.
<head id="Head1" runat="server">
<title></title>
<script src="../assets/lib/jquery/jquery-2.0.3.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.9.1.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$(window).load(function () {
$.ajax({
type: "POST",
url: "PageMethodTest.aspx/isConnected",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: fnsuccesscallback,
error:fnerrorcallback
});
}); function fnsuccesscallback(data) {
alert(data.d);
}
function fnerrorcallback(result) {
alert(result.statusText);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager EnablePageMethods="true" runat="server">
</asp:ScriptManager>
<div>
</div>
</form>
</body>

Will do 100% work
<script type="text/javascript">
function Generate()
{
var result = PageMethods.GenerateOTP(your parameter, function (response)
{
alert(response);
});
}
</script>

Related

Show alert error message when certain condition arises

I have the following code on page load that I use to show an error alert:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["message"] == "noemployees")
AlertDanger.Visible = true;
This is where the error is called. The page reloads and the error is shown.
if (payFitments == null)
{
Response.Redirect("Default?message=noemployees");
}
I have the following markup
<script type="text/javascript">
$(document).ready(function () {
window.setTimeout(function () {
$(".alert").fadeTo(1500, 0).slideUp(500, function () {
$(this).remove();
});
}, 3000);
});
-------------------------
<div runat="server" visible="false" id="AlertDanger" class="alert alert-danger">
×
<strong>You must have at least one employee to process</strong>
</div>
How do I show this message without having to load the default page again? Not seeing examples on the web that show this clearly.
You're using JQuery remove, which effectively deletes the alert from your DOM. So showing it again without reloading your page is not possible.
But you could use JQuery detach instead. Then you can insert it again with appendTo.
var alert = null;
function showHideAlert() {
if (alert) {
alert.appendTo("body");
alert = null;
} else {
alert = $(".alert").detach();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body>
<button onclick="showHideAlert();">Show/Hide alert</button>
<div class="alert">ALERT!!!</div>
</body>
Try serving a static html file and then using the alert function in Javascript. You can learn that here. Example for a button press:
<html>
<head>
<script>
function onError() {
try {
...
} catch (...) {
var error
error = "button was pressed"
alert(error)
}
}
</script>
</head>
<body>
<button id="myButton" onClick="onError()">do not click</button>
</body>
</html>
<html>
<head runat="server">
<title></title>
<meta http-equiv="X-UA-Compatible" content="IE=edge;" /><%-- Also Check Compatible View --%>
<%-- Put all your jQuery... Here I'm showing an example--%>
<script src="//ajax.microsoft.com/ajax/jQuery/jquery-2.1.1.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
window.setTimeout(function() {
$(".alert").fadeTo(1500, 0).slideUp(500, function() {
$(this).remove();
});
}, 3000);
});
</script>
<form id="form1" runat="server">
<asp:TextBox ID="txt" runat="server"></asp:TextBox>
<div runat="server" visible="false" id="AlertDanger" class="alert alert-danger">
× <strong>You must have at
least one employee to process</strong>
</div>
</form>
</body>
</html>
Note:- I think you have missed this... put your jQuery code inside your body tag...

Dropzone not working after add 'defer' on js file

So I have a dropzone control and everything is working just fine.
Code below:
<head runat="server">
<title></title>
<script type="text/javascript" src="/content/js/jquery-1.11.2.min.js" ></script>
<link rel="stylesheet" href="/content/css/dropzone.css" />
<script type="text/javascript" src="/content/js/dropzone.js" ></script>
<script type="text/javascript">
Dropzone.autoDiscover = false;
$(document).ready(function () {
$("#dZUploadPhoto").dropzone({
url: "/ashx/file-upload.ashx",
sending: function (file, xhr, formData) {
formData.append("type", "employee");
},
success: function (file, response) {
},
acceptedFiles: ".jpeg,.jpg,.png"
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div runat="server" id="divFileUploadBackground">
<div id="dZUploadPhoto" class="dropzone">
<div class="dz-default dz-message">Click or drop photo here to upload</div>
</div>
</div>
</form>
</body>
To speed up page load & eliminate render-blocking javascript files, I put 'defer' on every js file and add "DOMContentLoaded" on document.ready as per below:
<head runat="server">
<title></title>
<script type="text/javascript" src="/content/js/jquery-1.11.2.min.js" defer></script>
<link rel="stylesheet" href="/content/css/dropzone.css" />
<script type="text/javascript" src="/content/js/dropzone.js" defer></script>
<script type="text/javascript">
window.addEventListener('DOMContentLoaded', function () {
(function ($) {
Dropzone.autoDiscover = false;
$(document).ready(function () {
$("#dZUploadPhoto").dropzone({
url: "/ashx/file-upload.ashx",
sending: function (file, xhr, formData) {
formData.append("type", "employee");
},
success: function (file, response) {
},
acceptedFiles: ".jpeg,.jpg,.png"
});
});
})(jQuery);
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div runat="server" id="divFileUploadBackground">
<div id="dZUploadPhoto" class="dropzone">
<div class="dz-default dz-message">Click or drop photo here to upload</div>
</div>
</div>
</form>
</body>
Now, my code is not working with 2 error message:
Uncaught Error: No URL provided.
Uncaught Error: Dropzone already attached.
I've been searching high & low and still don't get it. Can someone enlighten me and show me the way? Where i did wrong?
The problem is that when you include the line:
Dropzone.autoDiscover = false;
Inside the listener for the DOMContentLoaded, this delays the execution of this line to the point that, when its executed, the default dropzone auto discover feature and the default configuration have already been used.
Just move this line outside the listener:
Dropzone.autoDiscover = false;
window.addEventListener('DOMContentLoaded', function () {
/* Rest of the code */
}
In fact dropzone also has a listener for the DOMContentLoaded and runs the auto discover when that event is fired, but since the dropzone library is registered first on that event it triggers before than your script, at least most popular browsers like chrome of firefox do it this way.

HTML button not calling function

this is my 1st javascript attempt and I'm getting the following in the chrome console:
"Uncaught ReferenceError: test1 is not defined."
I'm trying to send an Ajax request via onclick button event and display the data in the document. However, due to the error, I've scoped back to hello-world just for a debug attempt. Pardon this kind of question as I know its very elementary.
Any help is appreciated. Thanks for your time!
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button onclick="test1()">Click Here</button>
<p id="Data"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js">
function test1(){
alert("Hello, World");
/* $.ajax({
url: Target_URL,
headers: {
'Accept':'application/json',
'authorization', 'Bearer ' + vToken
},
method: 'GET'
// dataType: 'json',
// data: YourData,
success: ajaxCall = data
}); */
}
</script>
</body>
</html>
You used only one script tag for loading jquery and for your method - that will not work... "If a script element has a src attribute specified, it should not have a script embedded inside its tags." here a working solution:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button onclick="test1()">Click Here</button>
<p id="Data"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
function test1(){
alert("Hello, World");
/* $.ajax({
url: Target_URL,
headers: {
'Accept':'application/json',
'authorization', 'Bearer ' + vToken
},
method: 'GET'
// dataType: 'json',
// data: YourData,
success: ajaxCall = data
}); */
}
</script>
</body>
</html>
You can't place your javascript code in same <script> tag where you linked an external file (it shouldn't be included in <script src="..."> function </script>). Your test1 function should be separated from scr javascript tag. Try this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js">/<script>
<script> your javascript function should be here </script>
Hope this will solve your problem.
Put the JavaScript in the head of your document, and separate out the script for including jquery and your actual code.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
function test1(){
alert("Hello, World");
}
</script>
</head>
<body>
<button onclick="test1()">Click Here</button>
<p id="Data"></p>
</body>
</html>
You haven't placed your javascript method in proper javascript tag, separately place javascript method and javascript src, please check below for more clarification:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
function test1() {
alert("Hello, World");
}
/* $.ajax({
url: Target_URL,
headers: {
'Accept':'application/json',
'authorization', 'Bearer ' + vToken
},
method: 'GET'
// dataType: 'json',
// data: YourData,
success: ajaxCall = data
}); */
</script>
</head>
<body>
<button onclick="test1()">Click Here</button>
<p id="Data"></p>
</body>
</html>
First off, you need to declare your JavaScript function before you call it.
Change to this:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js" />
<script>
function test1(){
alert("Hello, World");
}
</script>
<button onClick="test1()">Click Here</button>
<p id="Data"></p>
</body>
</html>

Passing form variable to php using JSON

I am using the following code and I need to access the input value of the form textbox from php. The form is not submitted to server directly through the form tag. The button is calling a JS function. I need to access the input textbox called stName from the php code. How can I pass this info to php and access it from there? Thank you.
<!DOCTYPE html>
<html><head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link rel="stylesheet" type="text/css" href="jquery.mobile-1.4.4.min.css">
<script src="jquery-1.11.1.min.js"></script>
<script src="jquery.mobile-1.4.4.min.js"></script>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script charset="utf-8" type="text/javascript">
function connect()
{
$.ajax({
url:'hostname/reply.php',
headers:{"Content-Type": "application/json"},
type:'POST',
data:$(this),
dataType:'JSON',
error:function(jqXHR,text_status,strError){
alert(strError);},
timeout:60000,
success:function(data){
$("#result").html("");
for(var i in data){
$("#result").append("<li>"+data[i]+"</li>");
}
}
});
}
</script>
</head>
<body>
<center><b>My Students</b></center>
<center>
<form method="POST">
<input type="text" value="John" name ="stName" />
<input onclick="connect()" type="button" value="showStudents" />
</form>
</center>
<center><b>Results</b></center>
<ul data-role="listview" id="result"></ul>
</body>
</html>
serialize the form data ..
change your connect function to this
function connect()
{
$.ajax({
url:'hostname/reply.php',
headers:{"Content-Type": "application/json"},
type:'POST',
data:$('form').serializeArray(),
dataType:'JSON',
error:function(jqXHR,text_status,strError){
alert(strError);},
timeout:60000,
success:function(data){
$("#result").html("");
for(var i in data){
$("#result").append("<li>"+data[i]+"</li>");
}
}
});
}
or simply you can compress your code like this ..
function connect()
{
$.post('hostname/reply.php', $('form').serialize(), function(data){
$("#result").html("");
for(var i in data){
$("#result").append("<li>"+data[i]+"</li>");
}
}
});
}
You need to use the Sterilize Function. data:$( "form" ).serialize()
For Reverence to the function: http://api.jquery.com/serialize/
I also just found this StackOverflow that talks about how to structure the ajax request if you are having problems. Submit form using AJAX and jQuery

Jquery Dialog with asp.net

When i click on button to show the message i get one MessageBox that's normal but when i call the Jquery Dialog for the SCOND time i get two MessageBoxs! and when i call Jquery Dialog for the third time i get three MessageBoxs! Please help me!
Here is my Code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/start/jquery-ui.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function () {
$("[id*=Call_Dialog]").click(function() {
$("#MyDiv").dialog({
title: "jQuery Dialog Popup",
buttons: {
Close: function () {
$(this).dialog('close');
}
}
});
$("#ShowMessage").click(function () {
event.preventDefault();
alert('Hi');
$("#MyDiv").dialog('close');
})
})
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="MyDiv" style="display: none">
<asp:Button ID="ShowMessage" runat="server" Text="Button" />
</div>
</form>
<p>
<input id="Call_Dialog" type="button" value="button" /></p>
</body>
</html>
Thanks, but how can i call the dialog with button click?
Dialog should be initialized only once not every time you click on something and regenerate
solution is put dialog initialization outside of click and you're done
$(document).ready(function () {
$("#MyDiv").dialog({
title: "jQuery Dialog Popup",
buttons: {
Close: function () {
$(this).dialog('close');
}
}
});
$("[id*=Call_Dialog]").click(function() {
$("#ShowMessage").click(function () {
event.preventDefault();
alert('Hi');
$("#MyDiv").dialog('close');
})
})
});
to open jquery dialog : use this overload :
$("#MyDiv").dialog('open');

Categories