Get value from AJAX using Javascript and ASP - javascript

I am using this Ajax code. But I dont know how i will retrieve my value of value1 on my server-side asp using Javascript.
On my serverside I want to have something like
<%
var newdata = value1 ( which is the one from the serverside - which was send here)
%>
Please Help !!! thanks a million
I know it is possible with PHP but how do i do with javascript
<script>
function ajaxNow(_data)
{
var xmlHttp;
try
{
/* Firefox, Opera 8.0+, Safari */
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
/* newer IE */
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
/* older IE */
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser is old and does not have AJAX support!");
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
/* this puts the value into an alert */
alert("Value read is: "+xmlHttp.responseText);
}
}
xmlHttp.open("GET","ajax_file.asp?value1="+_data,true);
xmlHttp.send(null);
}
</script>

Client-side Javascript can't query server-based databases for obvious reasons. Based on what you appear to be doing, I would suggest you code an ASP which performs the actual query using VBA / C# / whatever, and you can then parse the results in your client-side ajax call as normal.

URL encode _data and nbquestions variables. Request.QueryString("param1") will decode them for you.
JavaScript URLEncode:
escape(_data);
Also you can use Server.URLEncode() methods from VB script.

xmlHttp.send correctly writen
It doesn't check that you have a 200 status before trying to deal with the data.
It fails to encode the data to make sure it is URL safe
I would suggest using a library to handle XHR stuff, instead of reinventing the wheel. Microjs has a list of lots of small libraries if you aren't using one of the large ones (such as YUI or jQuery).
how do I get the values on the server-side using Javascript.
It is just query string data, so it will be in Request.QueryString.

Whatever the server-side script outputs will be picked up by the AJAX request. So if the AJAX requests something, the server-side does the legwork and fetches the result from the database and then outputs it.
There are loads and loads of tutorials on how to do exactly this. Just ensure that you secure your script properly so that it's not open to abuse.

you can make the asp page write the result as JSON format read in directly via XMLHttpRequest Object and later processing:
example of JSON
var myJSONObject = {"bindings": [
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
{"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},
{"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}
]
};
then you can use native parsers in web browsers or eval() (NOT RECOMENDED, SERIOUSLY!!!) to parse the data written in your asp page and use it in your javascript client code.
More information about JSON basic info
JSON in browsers:
Internet Explorer 8+
Mozilla Firefox/Sea Monkey
in Opera, Chrome, Safari works too

//(javascript, ajax = xmlHttp)
if your response text is an array you can use this.
var myArray = eval(xmlHttp.responseText);
or if it is a just text you can use .
var value = xmlHttp.responseText
Another approach.This is just a template. If you use jquery, you can use this approach. i hope it solve your problem or give an idea.
html part:
<div id="willupdate"></div>
<div id="willupdate2"></div>
JQuery part:
$(document).ready(function() {
getValue("serverurl",updateName)
getValue("serverurl",updateSurName)
});
function updateName(name){
$("#willupdate").text(name)
}
function updateSurName(name){
$("#willupdate2").text(name)
}
function updateSurName(name){
$("#willupdate").text(name)
}
function getValue(url,opt_onRecieved){
if( !url || url == ""){
alert("request url error");
return;
}
$.ajax({
type:"POST",
url: url,
dataType:"json",
success: function(data){
opt_onRecieved(data);
}
});
}

When your Ajax-Request succeeds you will have the querystring-variables in the QueryString-Collection of the Request-Object.
Could work like this on the server side:
<% var newdata = Request.QueryString("value1"); %>

Here is a very good ajax tutorial. There is everything explained. https://developer.mozilla.org/en/AJAX/Getting_Started
You forget a double quote:
xmlHttp.open("post","CmsAjax.asp",true)
To get the data:
/* this puts the value into an alert */
alert(xmlHttp.responseText);

You need to encode the data on the server and then decode them in the client. You can use JSON-RPC for this.
Here are few links:
Official Website
Wikipedia Article about JSON-RPC
Implementations of JSON-RPC Service in different languages
But you don't need to use JSON-RPC if you have only one value you can encode as JSON in ASP and then decode it in JavaScript
var array = JSON.parse(xmlHttp.responseText);

Related

Variable target file with Ajax

I'd like to start by saying that I would rather any suggestions didn't include JQuery; I don't like how JQuery has become a defacto standard within JavaScript.
So here's my problem:
I'd like to pass a variable to a function that then uses that variable as the path to the file in a .open(). Here's my code so far:
Example of function being called:
ajaxPost('chatlog.txt',null);
The function being called:
function ajaxPost(targetPath,toSend){
var getMessage;
if (window.XMLHttpRequest){
getMessage=new XMLHttpRequest();
}
else{
getMessage=new ActiveXObject("Microsoft.XMLHTTP");
alert("Stop using Internet Explorer.");
}
getMessage.open("POST",targetPath,true);
getMessage.onreadystatechange=function(){
if (getMessage.readyState==4 && getMessage.status==200){
alert(getMessage.responseText);
}
};
getMessage.send(toSend);
}
This unfortunately doesn't work, for some kabuki reason.
I see some logical issue in your code:
the whole idea of using POST method is to send any kind of data to a specific backend and do server side stuff based on that data, but here you are using POST method to actually GET the 'chatlog.txt'. so you had to use GET method, to begin with.
BUT if you still insist on using POST instead of GET, you should know that you can use POST method instead of GET and it does the same, but you would face with some unforeseen problems.
YOUR ACTUAL PROBLEM:
I loaded your actual page and saw your problem, you have a error in your console:
Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
and as I said it means you have to change your method. I changed it like this:
function ajaxPost(targetPath,toSend){
var getMessage;
if (window.XMLHttpRequest){
getMessage=new XMLHttpRequest();
}
else{
getMessage=new ActiveXObject("Microsoft.XMLHTTP");
alert("Stop using Internet Explorer.");
}
getMessage.open("GET",targetPath,true);
getMessage.onreadystatechange=function(){
if (getMessage.readyState==4 && getMessage.status==200){
alert(getMessage.responseText);
}
};
getMessage.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
getMessage.send(toSend);
}
and it returned a data like this:
<b>Peck:</b> Hello World!<br/>#
<b>World:</b> Hello Peck!<br/>#
Add
getMessage.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
Before you send it. It tells the server how to process the POST stuff.
Using XMLHttpRequest is a very bad idea. If you are already using JQuery, try something like this:
$.post( "test.php", {name: "John", time: "2pm"}).done(function( data )
{
alert ("Succes! Data received: " + data);
});

Dealing with JSON result

I'm having trouble reading the JSON data from a venues search. Here is my code:
xmlhttpRC = new XMLHttpRequest();
url = "https://api.foursquare.com/v2/venues/explore?ll="+pointStrr+"&oauth_token=V5PI2GJ0KDOVH2GAHNHJ5DVLMRKNF440FR1N1HPG0XHX2OBQ&v=2015643&
callback=JSONP";
xmlhttpRC.open("GET", url, true);
xmlhttpRC.onreadystatechange = recCb;
xmlhttpRC.send(null);
//return recommendedArr;
}
function recCb(data){
//console.log(data);
if(xmlhttpRC.readyState == 4){
if(xmlhttpRC.status == 200){
var recRes = xmlhttpRC.response;
console.log(recRes);
//console.log(recRes);
console.log(recRes.meta.code);
}
}
}
I get the reponse I expect from the server, and firebug shows me that a JSON object is returned, but I am not sure how to access the data inside from here.
console.log(recRes.meta.code) returns the error:
"recRes.meta is undefined"
Where am I going wrong?
I want to access the venues information but I am just using meta.code as a simple test.
This is probably really simple but I'm stumped!
Thanks in advance,
Ross.
You need to parse JSON. Modern browsers have JSON.parse built in, older versions of IE etc. do not - you can theoretically use eval(response) but it creates a security hole.
There is a library to parse it if you cannot depend on users having modern browsers.
var decodedResp = JSON.parse(recRes);
if (decodedResp.meta.code === ...)
JSON-object is just a representation of an JS-object, see; it should be parsed first.

How to get the value of a function that is on the server-side on to the client-side (.responsetext) [duplicate]

I am using this Ajax code. But I dont know how i will retrieve my value of value1 on my server-side asp using Javascript.
On my serverside I want to have something like
<%
var newdata = value1 ( which is the one from the serverside - which was send here)
%>
Please Help !!! thanks a million
I know it is possible with PHP but how do i do with javascript
<script>
function ajaxNow(_data)
{
var xmlHttp;
try
{
/* Firefox, Opera 8.0+, Safari */
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
/* newer IE */
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
/* older IE */
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser is old and does not have AJAX support!");
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
/* this puts the value into an alert */
alert("Value read is: "+xmlHttp.responseText);
}
}
xmlHttp.open("GET","ajax_file.asp?value1="+_data,true);
xmlHttp.send(null);
}
</script>
Client-side Javascript can't query server-based databases for obvious reasons. Based on what you appear to be doing, I would suggest you code an ASP which performs the actual query using VBA / C# / whatever, and you can then parse the results in your client-side ajax call as normal.
URL encode _data and nbquestions variables. Request.QueryString("param1") will decode them for you.
JavaScript URLEncode:
escape(_data);
Also you can use Server.URLEncode() methods from VB script.
xmlHttp.send correctly writen
It doesn't check that you have a 200 status before trying to deal with the data.
It fails to encode the data to make sure it is URL safe
I would suggest using a library to handle XHR stuff, instead of reinventing the wheel. Microjs has a list of lots of small libraries if you aren't using one of the large ones (such as YUI or jQuery).
how do I get the values on the server-side using Javascript.
It is just query string data, so it will be in Request.QueryString.
Whatever the server-side script outputs will be picked up by the AJAX request. So if the AJAX requests something, the server-side does the legwork and fetches the result from the database and then outputs it.
There are loads and loads of tutorials on how to do exactly this. Just ensure that you secure your script properly so that it's not open to abuse.
you can make the asp page write the result as JSON format read in directly via XMLHttpRequest Object and later processing:
example of JSON
var myJSONObject = {"bindings": [
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
{"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},
{"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}
]
};
then you can use native parsers in web browsers or eval() (NOT RECOMENDED, SERIOUSLY!!!) to parse the data written in your asp page and use it in your javascript client code.
More information about JSON basic info
JSON in browsers:
Internet Explorer 8+
Mozilla Firefox/Sea Monkey
in Opera, Chrome, Safari works too
//(javascript, ajax = xmlHttp)
if your response text is an array you can use this.
var myArray = eval(xmlHttp.responseText);
or if it is a just text you can use .
var value = xmlHttp.responseText
Another approach.This is just a template. If you use jquery, you can use this approach. i hope it solve your problem or give an idea.
html part:
<div id="willupdate"></div>
<div id="willupdate2"></div>
JQuery part:
$(document).ready(function() {
getValue("serverurl",updateName)
getValue("serverurl",updateSurName)
});
function updateName(name){
$("#willupdate").text(name)
}
function updateSurName(name){
$("#willupdate2").text(name)
}
function updateSurName(name){
$("#willupdate").text(name)
}
function getValue(url,opt_onRecieved){
if( !url || url == ""){
alert("request url error");
return;
}
$.ajax({
type:"POST",
url: url,
dataType:"json",
success: function(data){
opt_onRecieved(data);
}
});
}
When your Ajax-Request succeeds you will have the querystring-variables in the QueryString-Collection of the Request-Object.
Could work like this on the server side:
<% var newdata = Request.QueryString("value1"); %>
Here is a very good ajax tutorial. There is everything explained. https://developer.mozilla.org/en/AJAX/Getting_Started
You forget a double quote:
xmlHttp.open("post","CmsAjax.asp",true)
To get the data:
/* this puts the value into an alert */
alert(xmlHttp.responseText);
You need to encode the data on the server and then decode them in the client. You can use JSON-RPC for this.
Here are few links:
Official Website
Wikipedia Article about JSON-RPC
Implementations of JSON-RPC Service in different languages
But you don't need to use JSON-RPC if you have only one value you can encode as JSON in ASP and then decode it in JavaScript
var array = JSON.parse(xmlHttp.responseText);

How to handle jSON XMLHttpRequest response?

I'm trying to control the json response I send back to the client but didnt know exactly how..
Here is a simple demo:
js code
xhr = new XMLHttpRequest();
xhr.open("POST", "page.aspx", true);
xhr.send();
// handle the response with xhr.responseText
.cs code
bool success = false;
string message = String.Empty;
// Create JSON Response
var jsonData = new
{
success = success,
message = message
};
Response.Write(jsonData);
The problem is that when I look on the xhr.responseText I see:
"{ success = False, message = }
<!DOCTYPE html PUBLIC ....
....
..
"
You want to do Response.Clear() and then Response.End() after writing the jsonData.
Then you'll need to handle the JSON response in javascript. I recommend Crockford's JSON library.
I also recommend using jQuery's $.ajax() function rather than hand-rolling your own XHR calls.
PS. Ajax calls would be better made to either ASHX resources or PageMethods/WebMethods declared on your ASPX page. Better still, abandon webforms and use ASP.NET MVC with JsonResults returned from your Controller.
PPS. If you do end up using WebMethods, this article is excellent.
You need to Response.Clear() to clear the response before Response.Write
Your cs code is not generating valid JSON (in addition to it displaying other things after the JSON data). All JSON descriptors must be double quoted, and so must any string values. Values are separated from their descriptors by colons. Example:
{"success": false, "message": "It didn't work"}.
Have a look at http://json.org/ for libraries to use with specific languages.

Using AJAX to access to the Twitter API

I'm thinking about adding some twitter functions in my web-application, so I started doing some tests. I checked the way to call the search twitter URL (more info in: http://dev.twitter.com/doc/get/search) in order to get tweets that contains the searched word/sentence. I realized that you can do it in php just getting the JSON file that the search URL returns with the file_get_contents() function. Also you can do it directly in JavaScript creating a script object, appending it to the body and use the callback parameter of the search URL to process the data.
Different ways to do, but that's the way I finally did it:
MAIN HTML FILE:
<title>Twitter API JSON</title>
<script type="text/javascript">
//function that created the AJAX object
function newAjax(){
var xmlhttp=false;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
//function that search the tweets containing an specific word/sentence
function gettweets(){
ajax = newAjax();
//ajax call to a php file that will search the tweets
ajax.open( 'GET', 'getsearch.php', true);
// Process the data when the ajax object changes its state
ajax.onreadystatechange = function() {
if( ajax.readyState == 4 ) {
if ( ajax.status ==200 ) { //no problem has been detected
res = ajax.responseText;
//use eval to format the data
searchres = eval("(" + res + ")");
resdiv = document.getElementById("result");
//insert the first 10 items(user and tweet text) in the div
for(i=0;i<10;i++){
resdiv.innerHTML += searchres.results[i].from_user+' says:<BR>'+searchres.results[i].text+'<BR><BR>';
}
}
}
}
ajax.send(null);
} //end gettweets function
</script>
#search_word Tweets
<input type="button" onclick="gettweets();"value="search" />
<div id="result">
<BR>
</div>
</html>
PHP WHERE WE GET THE JSON DATA:
$jsonurl = "http://search.twitter.com/search.json?q=%23search_word&rpp=10";
$json = file_get_contents($jsonurl,0,null,null);
echo $json;
And that's it, in this way it works fine. I call the PHP file, it returns the JSON data retrieved from the search URL, and in the main HTML JavaScript functions I insert the tweets in the div. The problem is that at the first time, I tried to do it directly in JavaScript, calling the search URL with Ajax, like this:
MAIN HTML FILE:
//same code above
//ajax call to a php file that will search the tweets
ajax.open( 'GET', 'http://search.twitter.com/search.json?q=%23search_word&rpp=10', true);
//same code above
I thought it should return the JSON data, but it doesn't. I'm wondering why not and that is what I would like to ask. Does someone have any idea of why I can't get JSON data using the Ajax object? If the search URL http://search.twitter.com/search.json?q=%23search_word&rpp=10 returns JSON data, it should be obtained in the ajax object, right?
XHR requests are generally limited to same-domain requests; e.g, if you're on bertsbees.com, you can't use an Ajax method to pull data from twitter.com.
That said, Twitter's API supports a popular data transport method known as JSON-P, which is really just a glorified injection technique. You simply pass it a callback method, and the data returned will be wrapped in your desired function, so it gets eval'd and passed in.
You cannot make a cross domain request using javascript, unless you are doing from an browser addon.

Categories

Resources