I have a need to automate data collection for users who visit specific pages of my site. To do this, I'm querying the LDAP. The LDAP query works just fine when I double click on the file locally (.vbs). However, when I double click on it while it's on the server, it doesn't work (as would be expected). However, I'm as new as new can get to writing VBScript.
After reading a few articles I modified the code and changed the extension to .asp. I ended up with this:
<%
On Error Resume Next
'Create the Array that will be passed
Dim employee(7)
'Employee System Related Info
Set objSysInfo = CreateObject("ADSystemInfo")
employee(0) = objSysInfo.SiteName
'Employee specific information
strUser = objSysInfo.UserName
Set objUser = GetObject("LDAP://" & strUser)
employee(1) = objUser.sAMAccountName
employee(2) = objUser.givenName
employee(3) = objUser.sn
employee(4) = objUser.displayName
employee(5) = objUser.telephoneNumber
employee(6) = objUser.title
Return employee
%>
In the JavaScript function which would call this .asp file via ajax, I am able to get the employee number which I think could be received by the .asp file and do the rest of the query.... However, I'm not even sure if I'm returning everything correctly in the VBScript. Furthermore, I'm not even sure if I should be using a GET or POST AJAX call. Can someone point me in the right direction?
Updated 03/22/2017 at 10AM CDT
I've finally gotten back to the office and tried to play around. I'm still a little lost. I've made some updates to the code below you'll see the javascript and the VBScript
FIRST the JavaScript:
var employee = {};
function getEmp() {
var ldapUserName = ADSystem.UserName;
$.ajax({
type: "POST",
data: ldapUserName,
url: "https://here.is.my/url.asp",
success: $.ajax({
type: "GET",
dataType: "json",
success: function(responseText) {
employee = responseText;
},
error: function() {
alert("No Data Received");
}
}),
error: function() {
alert("Connection Failed");
}
});
}
Now here is the updated VBScript based on a few things I read and the suggestions from here:
<%
Public Function empDemo(username)
On Error Resume Next
'Create the Array that will be passed
Dim employee(7)
'Employee System Related Info
Set objSysInfo = CreateObject("ADSystemInfo")
employee(0) = objSysInfo.SiteName
'Employee specific information
strUser = objSysInfo.username
Set objUser = GetObject("LDAP://" & strUser)
employee(1) = objUser.sAMAccountName
employee(2) = objUser.givenName
employee(3) = objUser.sn
employee(4) = objUser.displayName
employee(5) = objUser.telephoneNumber
employee(6) = objUser.title
response.write "{ site: " & employee(0) & ","
& "empNum: " & employee(1) & ","
& "empFName: " & employee(2) & ","
& "empLName: " & employee(3) & ","
& "empFullName: " & employee(4) & ","
& "empExt: " & employee(5) & ","
& "empTitle: " & employee(6) & "}"
End Function
%>
Currently, I'm getting the alert stating "No Data Received". What am I doing wrong?
Instead of "return Employee", have you tried:
response.write employee
or maybe
response.write employee.sAMAccountName
Is this VB6? Not sure what libraries are available in classic asp, so you might have to manually write the data in JSON form... i.e...
response.write "{ name: " & employee.sAMAccountName & "}"
Related
I've spent tens of hours on it: calling a web service from my school platform with google script. It works in php but not in google script. I don't know how to implement the "getClassList" method in the script. Everything tried nothing works! Please help me before I go completely crazy!
I give you everything I think is necessary to write the script:
Webservices V3 (SOAP)
URL's:
https://tisj-bilzen.smartschool.be/Webservices/V3
https://tisj-bilzen.smartschool.be/Webservices/V3?wsdl
Details of the methode:
getClassList
This method requests a list of all classes. This method provides a serialized array with the class name, description, visibility, and unique class code.
string $accesscode: Password webservices
getClassListJson
This method requests a list of all classes. This method provides a JSON array with the class name, description, visibility and unique class code.
string $accesscode: Password webservices
Password webservices : 408cb6c31db39698b176
Many thanks in advance !!
Patrick Crijns
one of my attempts :
function probeer5(){
var $code = '408cb6c31db39698b176';
var options = {"headers" : {"Authorization" : "accesscode:408cb6c31db39698b176>"} };
var url = "https://tisj-bilzen.smartschool.be/Webservices/V3?wsdl#getClassList";
var response = UrlFetchApp.fetch(url,options);
var result= response.getContentText();
Logger.log(result);
}
I'm trying to do the same thin on my school's smartschool.be-platform. Did you ever get this to work?
I've tried setting up a soap client like in this example!, but didn't get it to work for smartschool...
Update: I got it to work! Check out the demo code bolow, for the saveUserParameter method. I'm sure you'll be able to alter it to get the getClassList method to work as well. Don't forget to change my school prefix (msvoskenslaan) to yours (tisj-bilzen)!
function SS() {
var SSpass = "MySecretPassWord" //webservices PW
var sam = "fake.student" //user identifier (login or uniek ID)
var parameter = "extraInfo" //as this script calls the saveUserParameter webservice, this is the name of the parameter field which will be altered
var data = "Door script ingevoerde waarde met spaties \nen \nline \nbreaks." //the data entered in the field mentioned above
var xml = '<?xml version="1.0" encoding="UTF-8" standalone="no"?><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tns="https://msvoskenslaan.smartschool.be:443/Webservices/V3" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:soap-enc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ><SOAP-ENV:Body><mns:saveUserParameter xmlns:mns="https://msvoskenslaan.smartschool.be:443/Webservices/V3" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><accesscode xsi:type="xsd:string">' + SSpass + '</accesscode><userIdentifier xsi:type="xsd:string">' + sam + '</userIdentifier><paramName xsi:type="xsd:string">' + parameter + '</paramName><paramValue xsi:type="xsd:string">' + data + '</paramValue></mns:saveUserParameter></SOAP-ENV:Body></SOAP-ENV:Envelope>'
var options =
{
"method" : "post",
"contentType" : "text/xml; charset=utf-8",
"payload" : xml,
"muteHttpExceptions" : true
};
var soapCall= UrlFetchApp.fetch("https://msvoskenslaan.smartschool.be/Webservices/V3", options);
Logger.log(soapCall);
}
Battlefield Page
In the image above, there is a page that has a battlefield with 20 users on it. I have written JavaScript to capture the data and store it in a MySQL db. The problem comes into the picture when I need to hit next to go to the next page and gather that data.
It fetches the next 20 users with an Ajax call. Obviously when this happens, the script can't log the new information because the page never loads on an Ajax call which means the script doesn't execute. Is there a way to force a page load when the Ajax link is clicked?
Here's the code:
grabData();
var nav = document.getElementsByClassName('nav')[0].getElementsByTagName('td')[2].getElementsByTagName('a')[0];
nav.addEventListener("click", function(){
grabData();
});
function grabData(){
var rows = document.getElementsByClassName('table_lines battlefield')[0].rows;
var sendData = '';
for(i=1; i < rows.length -1 ; i++){
var getSid = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[2].getElementsByTagName('a')[0].href;
var statsID = getSid.substr(getSid.indexOf("=") + 1); //Grabs ID out of stats link
var name = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[2].textContent.replace(/\,/g,"");
var tff = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[3].textContent.replace(/\,/g,"");
var rank = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[6].textContent.replace(/\,/g,"");
var alliance = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[1].textContent.trim();
var gold = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[5].textContent.replace(/\,/g,"");
if(alliance == ''){
alliance = 'None';
}
if(gold == '??? Gold'){
gold = 0;
}else{
gold = gold.replace(/[^\/\d]/g,'');
}
sendData += statsID + "=" + name + "=" + tff + "=" + rank + "=" + alliance + "=" + gold + "#";
}
$.ajax({
// you can use post and get:
type: "POST",
// your url
url: "url",
// your arguments
data: {sendData : sendData},
// callback for a server message:
success: function( msg ){
//alert(msg);
},
// callback for a server error message or a ajax error
error: function( msg )
{
alert( "Data was not saved: " + msg );
}
});
}
So as stated, this grabs the info and sends to the php file on the backend. So when I hit next on the battlefield page, I need to be able to execute this script again.
UPDATE : Problem Solved. I was able to do this by drilling down in the DOM tree until I hit the "next" anchor tag. I simply added an event listener for whenever it was clicked and had it re execute the JavaScript.
Yes, you can force a page load thus:
window.location.reload(true);
However, what the point of AJAX is to not reload the page, so often you must write javascript code that duplicates the server-side code that builds your page initially.
However, if the page-load-code-under-discussion runs in javascript on page load, then you can turn it into a function and re-call that function in the AJAX success function.
Reference:
How can I refresh a page with jQuery?
I am trying to create a form that, once submitted, will be sent to my index.html page for other users to view. I want it so multiple users anywhere in the world can submit information and so the website displays all their information at once.
Here is my submit page's PHP code:
<form action="submit_a_message.php" method="post">
<textarea name="message" cols="60" rows="10" maxlength="500"></textarea><br>
<input type="submit">
</form>
I am trying to figure out how to make the information submited via that form appear on my index.html page. This is the code I found online, but it doesn't work. Why?
<?php>
string file_get_contents ( string $submit_a_message.php [, bool $use_include_path = false [, resource $context [, int $offset = -1 [, int $maxlen ]]]] )
<?>
Any help would be greatly appreciated.
To make submitted text avaliable on your index page, you need a place where you would store it. You can use MySQL base to do that, or (if you can't or you really don't want) you can use text file with your texts/posts (that is not really good way, i warned you).
To do that with MySQL you can use a code like this on your submit_a_message.php:
<?php
//connection to database and stuff
...
if $_POST['message'] {
$message = $_POST['message'];
$sql = "insert into `mytable` values $message"; //that is SQL request that inserts message into database
mysql_query($sql) or die(mysql_error()); // run that SQL or show an error
}
?>
In order to show desired vaues from table use above-like idea, your SQL request would be like select * from mytable where id = 123
if your not married to the idea of using php and learning how to manage and access a database you could use jquery and a trird party backend like parse.com
If your new to storing and retrieving data, I would definately reccomend the services that https://parse.com/ offeres. It makes storing and retrieving data trivial. Best of all, the service is free unless your app makes more than 30 API requests per second. I have an app that 61 users use daily and we have never come close to the 30 req per second limit.
To save your info, you could write:
$('document').ready(function(){
$('#submit_btn').on('click',function(){ // detect button click, need to add "submit_btn" as the id for your button
var Message = Parse.Object.extend("Message"); //create a reference to your class
var newObject = new EventInfo(); //create a new instance of your class
newObject.set("messageText", $("#myMessage").val()); //set some properties on the object, your input will need the id "myMessage"
newObject.save(null, { //save the new object
success: function(returnedObject) {
console.log('New object created with objectId: ' + returnedObject.id);
},
error: function(returnedObject, error) {
console.log('Failed to create new object, with error code: ' + error.message);
}
});
});
});
Retrieving that info later would be as easy as:
var Message = Parse.Object.extend("Message"); //create a reference to your class
var query = new Parse.Query(Message); //create a query to get stored objects with this class
query.find({
success: function(results) { //"results" is an array, you can fine tune your queries to retrieve specific saved objects too
for (var i = 0; i < results.length; i++) {
var object = results[i];
$(body).append("Message #" + (i+1) + object.get("messageText");
}
},
error: function(error) {
console.log("Failed to complete Query - Error: " + error.code + " " + error.message);
}
});
how to trap an error and save error detail in database and redirect to custom error page in classic asp?
I want that I should include a asp page in all page of my website and if any error occur it get that error detail, saved it to database or mail it to mail id and redirect to custom error page.
Please if you have any idea then please help me.
Classic ASP has no try/catch.
It also uses VBscript by default and the answer above is, I'm guessing, C#?
Here is VBscript ASP for what you are trying to do:
<%
Set conn = Server.CreateObject("ADODB.Connection")
SQL_server_string = "Provider=SQLOLEDB; Data Source=myMachine; Initial Catalog=pubs; User ID=sa; Password=pw"
ConnectionString = SQL_server_string
conn.Open ConnectionString
s = "INSERT INTO"
s = s & " tablename "
s = s & "("
s = s & " fieldname1 "
s = s & ",fieldname2 "
s = s & ") "
s = s & "VALUES"
s = s & "( "
s = s & "'" & stringvalue1 & "'"
s = s & ",'" & stringvalue2 & "'"
s = s & ") "
conn.execute(s)
if (err.number<>0) then
m = "error on page ___ line ____<br>"
m = m & "error number: " & err.number & "<br>"
m = m & "error description: " & err.description & "<br>"
m = m 7 "sql: " & s & "<br>"
session("msg") = m
set conn=nothing
response.redirect("error_report.asp")
end if
'got past error checking... do stuff...
%>
use try catch methods in javascript to catch the errors. Within the catch block post the data to the server. In server have an aspx page or php page which one you are familiar. Get the data to be inserted as parameters from this post back in that aspx/php file and from that file insert into DB.
<script>
var txt="";
function ProcessData()
{
try
{
....
}
catch(err)
{
var message = err.message;
$ajax({
type:"POST",
url:"Errorhandler.aspx/InsertErrordetails",
data:"{error: '" + message + "'}",
clientType:"application/json; charset=utf-8",
datatype:"json",
async: false,
success: function () { alert("success"); },
error: function(){alert("error");}
});
}
}
</script>
The server side code appears like this.
public static void InsertErrordetails(string error)
{
SqlConnection Con = new SqlConnection(#"Server=db;Integrated Security=True;" + "Database=userdb");
string query = "INSERT INTO [LogTable]([Message])" +
"VALUES (#error)";
SqlCommand cmd = new SqlCommand(query, Con);
cmd.Parameters.AddWithValue("#Message", error);
try
{
Con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
Con.Close();
}
}
Greetings,
Upon a javascript button click, I'm using jquery to post to a url:
$(".optionClick").click(function () {
var caseOption = $(this).attr('title');
$.post("../tracking/RecordClick.aspx?page=gallery&item=" + caseOption);
});
On the page being called, I'm using the following vb.net code to retrieve the querystring variables and write them to a database:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Request.QueryString("page") Is Nothing Then
Dim trackingPage As String = Request.QueryString("page")
Dim trackingIP As String = Request.UserHostAddress
Dim trackingItem As String = Request.QueryString("item")
Dim trackingDate As String = Date.Now().ToString("G")
Try
Dim conString As String
conString = ConfigurationManager.ConnectionStrings("SSFDBConnectionString").ConnectionString
Dim sqlCon As New SqlConnection(conString)
Dim cmd As New SqlCommand
Select Case trackingPage
Case "gallery"
cmd.CommandType = CommandType.Text
cmd.CommandText = "INSERT INTO UserTrackGallery VALUES ('" & trackingIP & "', '" & trackingItem & "', '" & trackingDate & "')"
cmd.Connection = sqlCon
If sqlCon.State = ConnectionState.Closed Then
sqlCon.Open()
End If
cmd.ExecuteNonQuery()
If sqlCon.State = ConnectionState.Open Then
sqlCon.Close()
End If
Case "products"
Case "search"
End Select
Catch ex As Exception
End Try
Response.Close()
End If
End Sub
In local development, this works perfectly for me recording one database write per button click. On the server however, each post generates anywhere from 1 to 7 database writes.
I've been searching for a solution for a couple of days to no avail. Any help is greatly appreciated!
------------------------------Update--------------------------------
I tried to simplify the process by creating a VB.Net page with only a single button:
<%# Page Language="VB" AutoEventWireup="false" CodeFile="javascript.aspx.vb" Inherits="gallery_javascript" %>
<!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></title>
<script src="../Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajaxSetup({ async: false });
$(".optionClick").click(function () {
$.post("../tracking/RecordClick.aspx?page=gallery&type=click&item=XYZ");
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" class="optionClick" value="button" />
</div>
</form>
</body>
</html>
But the problem persists. Firebug reports "Aborted" and the page is called multiple times. I also tried this javascript:
$(document).ready(function () {
$.ajaxSetup({ url: '../tracking/RecordClick.aspx' });
$(".optionClick").click(function () {
$.ajax({ data: 'page=gallery&type=click&item=XYZ' });
});
});
Tried this also:
url = "../tracking/RecordClick.aspx?page=gallery&type=click&item=XYZ";
if (window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
try {
req.open("POST", url, false);
} catch (e) {
alert(e);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.open("POST", url, false);
req.send();
}
}
Each of the javascript blocks above worked locally as intended but failed in the same manner with multiple DB writes and Firebug "Aborted" status.
If I call the url+querystring directly via the browser, everything works as expected.
Could this be related to a delay of some sort since it works locally?
Thanks for the help thus far!
(Edit) Also tried using the full path url in the code above - no improvement.
I found a solution to my problem. It appears that the more recent versions of .Net prevent HTTP POST calls, but this is allowed for localhost (which is why it worked perfectly locally). HTTPWatch and Firebug both showed the .aspx page connection but no response returned. It appears as though the multiple calls were retry attempts to receive a response.
My solution was to create a web service:
Option Strict On
Imports System.Data.SqlClient
Imports System.Data
Imports System
Imports System.Net
Imports System.Text
Imports System.IO
Imports System.Web.HttpContext
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://mywebsite.com/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class RecordClick
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function RecordClick() As String
Dim trackingPage As String = ""
Dim trackingIP As String = ""
Dim trackingType As String = ""
Dim trackingItem As String = ""
Dim trackingDate As String = ""
With HttpContext.Current
trackingPage = .Request.Params.Item(0)
trackingIP = .Request.UserHostAddress
trackingType = .Request.Params.Item(1)
trackingItem = .Request.Params.Item(2)
trackingDate = Date.Now().ToString("G")
End With
Dim conString As String
conString = ConfigurationManager.ConnectionStrings("SSFDBConnectionString").ConnectionString
Dim sqlCon As New SqlConnection(conString)
Dim cmd As New SqlCommand
cmd.Connection = sqlCon
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "spInsertRecordClick"
cmd.Parameters.Add("#IPAddress", SqlDbType.NVarChar, 50)
cmd.Parameters("#IPAddress").Direction = ParameterDirection.Input
If trackingIP = "" Then
cmd.Parameters("#IPAddress").Value = DBNull.Value
Else
cmd.Parameters("#IPAddress").Value = trackingIP
End If
cmd.Parameters.Add("#CaseOption", SqlDbType.NVarChar, 50)
cmd.Parameters("#CaseOption").Direction = ParameterDirection.Input
If trackingItem = "" Then
cmd.Parameters("#CaseOption").Value = DBNull.Value
Else
cmd.Parameters("#CaseOption").Value = trackingItem
End If
cmd.Parameters.Add("#TimeDate", SqlDbType.DateTime)
cmd.Parameters("#TimeDate").Direction = ParameterDirection.Input
If trackingDate = "" Then
cmd.Parameters("#TimeDate").Value = DBNull.Value
Else
cmd.Parameters("#TimeDate").Value = trackingDate
End If
cmd.Parameters.Add("#ViewType", SqlDbType.NChar, 10)
cmd.Parameters("#ViewType").Direction = ParameterDirection.Input
If trackingType = "" Then
cmd.Parameters("#ViewType").Value = DBNull.Value
Else
cmd.Parameters("#ViewType").Value = trackingType
End If
cmd.Parameters.Add("#Page", SqlDbType.NVarChar, 50)
cmd.Parameters("#Page").Direction = ParameterDirection.Input
If trackingPage = "" Then
cmd.Parameters("#Page").Value = DBNull.Value
Else
cmd.Parameters("#Page").Value = trackingPage
End If
Try
If sqlCon.State = ConnectionState.Closed Then
sqlCon.Open()
End If
cmd.ExecuteNonQuery()
Catch ex As Exception
Finally
If sqlCon.State = ConnectionState.Open Then
sqlCon.Close()
End If
End Try
If sqlCon.State = ConnectionState.Open Then
sqlCon.Close()
End If
Return "Success"
End Function
End Class
This is the javascript I used to call the web service:
$.ajax({
type: "POST",
url: "../tracking/RecordClick.asmx/RecordClick",
data: "page=" + DMOriginatingPage + "&type=" + DMType + "&item=" + DMtitle
});
I had to add the following to the system.web section of the web.config:
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
It works perfectly now. I'm not very experienced in this area so there's probably a better solution for what I'm trying to do. However, maybe this will help someone else - took me two weeks to figure this out. :)
I would suggest tracing the problem.
1) Use Firefox + Firebug, open the NET tab and watch how many requests are sent.
2) Paste your AJAX URL in your browser's address bar and see what happens on the server. This way you are sure only one request is made.
Have you tried using the full path from the root of the site in the post call...instead of using the "../"?
Suspect code:
$(".optionClick").click(function () {
$.post("../tracking/RecordClick.aspx?page=gallery&type=click&item=XYZ");
});
try removing the ".." and replacing it with the actual path...I am suspicious that that could be causing your problem.