How to run run a post url? - asp-classic

What i am trying to do is basically run a script and post data to a page but the page is not on the server. So i dont want to run a redirect, just run a webpage in the back when the user clicks on a button?
I have tried...
set httpRequest = CreateObject("WinHttp.WinHttprequest.5.1")
Dim var1
var1 = Request("username")
on error resume next
httpRequest.Open "POST", "http://www.example.com", True
httpRequest.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
httpRequest.send var1
set httpRequest = nothing
But this doesnt seem to work. So i want to built the url http://www.example.com?username and run it?

The easiest way is to include a reference to the jQuery script libraries and use
.ajax
http://api.jquery.com/jQuery.ajax/
a call is simply:
<html>
<head>
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" ></script>
</head>
<body>
bip
<div id="result"> results to get replaced here</div>
<div id="msg" style="color:Red">any errors will show here</div>
<input type="button" value="click me" id="loadButton" />
<script language="javascript" type="text/javascript">
//ensure jQuery is loaded before calling script
$(document).ready(function () {
alert('ready');
$('#loadButton').click(function () {
alert('Handler for .click() called.');
$.ajax({
url: 'yoursite/yourpage',
error: function (xhr, ajaxOptions, thrownError) {
alert('doh an error occured. look at the error div above : )');
$('#msg').html(xhr.status + ' ' + thrownError); ;
},
data: "{'someparam':'someparamvalue','someparam2':'someparamvalue2'}",
success: function (data) {
$('#result').html(data);
alert('Load was performed.');
}
});
});
});
</script>
</body>
</html>

Your problem is most likely this line:
httpRequest.Open "POST", "http://www.example.com", True
Your "True" there is saying run in asynchronous mode, i.e. don't wait for the response before carrying on. You are then destroying the object immediately so the request is never going to get very far. Change that "True" to a "False" and you should see the result hit the other server.
Edit 1:
Also noticed you are not formatting the POST data correctly, it should take the traditional url formatted foo=bar, so the send line needs to be modified like so:
httpRequest.send "name=" & var1
Sorry I didn't spot this first time!
Edit 2:
Here is an example of a working GET transaction with WinHttpRequest:
Function GetHTTP(strURL)
Set objWinHttp = Server.CreateObject("WinHttp.WinHttpRequest.5.1")
objWinHttp.Open "GET", strURL, False
objWinHttp.Send
GetHTTP = objWinHttp.ResponseText
Set objWinHttp = Nothing
End Function
If you do really just need a GET transaction, you can use the following with this function:
strResponse = GetHTTP("http://www.example.com/?name=" & Request("username"))
And as you don't need the response, just ignore strResponse from there on in.
Reference:
NeilStuff.com - Open Method

Related

Ajax to R via Rstudio

I started the server in Rstudio using servr::httd().
I hope to learn how to post data to R and back and I found the below.
(jQuery jsonrpc 2.0 call via .ajax() gets correct response but does not work?)
I implemented the below codes on index.html and it looked fine.
However, I am unsure what I should code to implement the server side in Rstudio.
The server codes from above URL is for python, and I have been reading for a few days without finding the way how Rstudio should be done. Please help.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: 'http://localhost:4321/',
data: JSON.stringify ({jsonrpc:'2.0',method:'add', params:[1400,2100],id:"jsonrpc"} ),
type:"POST",
dataType:"json",
success: function (data) { alert("The result is : " + data.result);},
error: function (err) { alert ("Error");}
});
});
</script>
</head>
<body>
<h1> jQuery JSON RPC 2.0 demo </h1>
</body>
</html>

jQuery UI Autocomplete only works in IE on one machine

I've assembled a page as a proof-of-concept for retrieving matching user names from Active Directory (via a web service on out intranet) while typing values into a text box. It works beautifully, but only on my workstation and only in IE (version 10). Every other user who has tried it gets the alert, "error", which is also what I get when I try it in Chrome. I've further verified that the other users can actually retrieve the data by pasting the web service URL directly into their browsers, so the breakdown occurs somewhere between fetching the data and displaying in the form. My only thought was that maybe there are some browser settings responsible for allowing this to work, but I really have no idea what those might be.
Here's what the code looks like:
<div>
<h1>Active Directory lookup</h1>
<input name="txtADAccount" type="text" id="txtADAccount" style="width:400px;" />
</div>
</form>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$("#txtADAccount").autocomplete({
source: function (request, response) {
$.support.cors = true;
$.ajax({
crossDomain: true,
headers: { 'Access-Control-Allow-Origin': '*' },
url: "http://fetch.mycompany.com/ADUser/ADUserByAccountOrDisplayName/" + $('#txtADAccount').val(),
dataType: "json",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
var jsonData = JSON.parse(data);
// Filter out records where there is no email address
var jsonFiltered = jsonData.result.filter(function (row) {
if(row.mail != '') {
return true
} else {
return false;
}
});
response($.map(jsonFiltered, function (item) {
return { label: item.displayName + ' (' + item.mail + ')' }
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + ': ' + errorThrown);
}
});
},
select: function (event, ui) {
// prevent autocomplete from updating the textbox
event.preventDefault();
$(this).val(ui.item.label);
},
minLength: 2 //minLength as 2, it means when ever user enter 2 character in TextBox the AutoComplete method will fire and get its source data.
});
});
</script>
</body>
Just looking for some hints as to what the source of the problem might be.
UPDATE: Updating the script links to the latest versions of jquery and jquery.ui resulted in it working on at least one more workstation that didn't work previously. However, it's still not working on any other machines I've tried and the error messages displayed are not consistent. Sometimes it just displays "error", other times "error: No Transport", and other times "error: Access is Denied".
UPDATE 2: On this second workstation where I've been able to get it working, I noticed that if I log in using a different account, I get the "error: Access is denied" message. This is puzzling... to what exactly is access being denied? It's not the web service itself because any user can drop the web service URL into their browser and it will return the appropriate json data.
UPDATE 3: I just discovered that changing the contentType to "application/x-www-form-urlencoded; charset=utf-8" has resulted in it working now for several other users as well as working for me now in Chrome. It's still not working for at least two users, one using IE who gets no message whatsoever, and another who is still getting the "Access is denied" message (I may need to have them try clearing their browser cache). I'm still baffled as to why it always worked for me alone regardless of the contentType setting.

Getting Information from Console.log and displaying it in div

Currently I am stuck I want to return the title, plot and poster using themoviedb api I have no idea how to start the coding for this
Currently when i run a search the information is display in the console log of the browser i want to take that information and style it into a table format nothing fancy just the title and poster need help no clue where to start
doc site here http://docs.themoviedb.apiary.io/#get-%2F3%2Fsearch%2Fmovie
<html>
<head>
<title>Sample Seach</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var url = 'http://api.themoviedb.org/3/',
mode = 'search/movie',
input,
movieName,
key = '?api_key=My API KEY HERE';
$('button').click(function() {
var input = $('#movie').val(),
movieName = encodeURI(input);
$.ajax({
url: url + mode + key + '&query='+movieName ,
dataType: 'jsonp',
success: function(data) {
console.log(data);
}
});
});
});
</script>
</head>
<body>
<input id="movie" type="text" /><button>Search</button>
</body>
</html>
output looks like this it returns objects under a movie title in his chase 300
error when running each staement
Something like this:
$.ajax({
url: url + mode + key + '&query='+movieName ,
dataType: 'jsonp',
success: function(data) {
var table = '<table>';
$.each( data.results, function( key, value ) {
table += '<tr><td>' + value.original_title + '</td><td>' + value.release_date + '</td></tr>';
});
table += '</table>';
$('.myelement').html(table);
}
});
You don't read from the console. It's just for outputting debug information. The AJAX call basically returns an JavaScript object (whose structure you can see in the the console).
Access the data from it just like from any other JavaScript object (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects if you need to learn how) and work with that.
EDIT: If you need to know how to display the data on the web page, you need to learn about the DOM. See for example: http://www.elated.com/articles/javascript-dom-intro/

Calling code behind function on dynamically generated href

I am generating
<a href="...">
dynamically in a code behind. When I click on the link it needs to run a sub from the code behind and also I need to know which link actually triggered that code behind function.
This is my code behind (dynamically generating link) which is then displayed in div. I literally dump this (below code) as a string into a div:
<a href='#'
id='" + i.MemberId.ToString() + "'
Text='Click Me'
onServerClick='Check_Clicked'
runat="server">Click Me
</a>
And this is what I need to call:
Sub Check_Clicked(sender As Object, e As EventArgs)
Me.div_result.InnerHtml = "TEST"
End Sub
UPDATE:
Okay I added the following to my project:
<script type="text/javascript">
$(document).ready(function () {
$('#inboxLink').click(function () {
$.ajax({
type: 'POST',
url: 'inbox.aspx/GetSomething',
data: '{ test1: "somevalue" }',
ContentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("Success");
},
error: function (data) {
alert("Fail");
}
});
});
});
</script>
and then
<System.Web.Services.WebMethod()> _
Public Shared Sub GetSomething()
Me.div_result.InnerHtml = "TEST"
End Sub
but there are more problems In the code behind
'Me' is only valid within an instance method.
so I am not sure the way I am approaching this problem might be wrong?
Generating an element at the client side with runat="server" will not make it a server control. You better implement an AJAX based architecture.
Generate your client side anchor element (I'm using jquery here)
$('<a />', {
text:'Click Me',
id:'<whatever you like>',
click:function(){ makeCallToServerWithYourData(yourData); }
}).appendTo('yourTargetDivSelector');
So that's it if you want to call a server method.
If you just want to change the content of a div when you click on the anchor tag, as in your sample code, just replace the click event handler with whatever you want.
Please mark as answer if it helped you.
Thank you :)

jQuery $.get refreshing page instead of providing data

I have written some code using jQuery to use Ajax to get data from another WebForm, and it works fine. I'm copying the code to another project, but it won't work properly. When a class member is clicked, it will give me the ProductID that I have concatenated onto the input ID, but it never alerts the data from the $.get. The test page (/Products/Ajax/Default.aspx) that I have set up simply returns the text "TESTING...". I installed Web Development Helper in IE, and it shows that the request is getting to the test page and that the status is 200 with my correct return text. However, jQuery refreshes my calling page before it will ever show me the data that I'm asking for. Below are the code snippets from my page. Please let me know if there are other code blocks that you need to see. Thank you!
<script type="text/javascript">
$(document).ready(function() {
$(".addtocart_a").click(function() {
var sProdIDFileID = $(this).attr("id");
var aProdIDFileID = sProdIDFileID.split("_");
var sProdID = aProdIDFileID[5];
// *** This alert shows fine -- ProdID: 7
alert("ProdID: " + sProdID);
$.get("/Products/Ajax/Default.aspx", { test: "yes" }, function(data) {
// *** This alert never gets displayed
alert("Data Loaded: " + data);
}, "text");
});
});
</script>
<input src="/images/add_to_cart.png" name="ctl00$ctl00$ContentPlaceHolder1$ContentPlaceHolder1$aAddToCart_7" type="image" id="ctl00_ctl00_ContentPlaceHolder1_ContentPlaceHolder1_aAddToCart_7" class="addtocart_a" />
The easiest way is to tell jQuery not to return anything.
$(".addtocart_a").click(function(e){
// REST OF FUNCTION
return false;
});
Good luck! If you need anything else let me know.

Resources