How do you call an ASHX from JavaScript? - javascript

I want to call an ASHX file and pass some query string variables from JavaScript and get the return string into a string in the JavaScript. How would I do this?
The ASHX file is already coded to response.write a string based on whatever the query strings are.

Something like this?:
function createXMLHttpRequest() {
try { return new XMLHttpRequest(); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
alert("XMLHttpRequest not supported");
return null;
}
var xmlHttpReq= createXMLHttpRequest();
xmlHttpReq.open("GET", "your.ashx?v1=1&v2=2&etc", false);
xmlHttpReq.send(null);
var yourJSString = xmlHttpReq.responseText;

Related

Getting variable from ajax function

I've this function.
function ajaxtakesource4(callback){
var ajaxRequest; // The variable that makes Ajax possible!
try{
ajaxRequest = new XMLHttpRequest();
} catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange =function(){
if(ajaxRequest.readyState == 4 &&ajaxRequest.status==200){
var sourcetest = ajaxRequest.responseText;
callback(sourcetest);
}
}
ajaxRequest.open("POST", "takesource4.php", true);
ajaxRequest.send(null);
}
Also:
var somous4;
function run() {
ajaxtakesource4(function(sourcetest){
somous4=sourcetest;
});
alert(somous4);
}
and here I call the above the function:
<div id="run">
<button id="button_run" class="button" onclick="run()">Run</button>
</div>
To make it clear i need to use the variable of somous4 in the function run not only to print it. My idea is to call a number of variables , with the same procedure. I need to store,use these variable by the some way(this is what i am searching) use all of them in the function and run the algorithm. I need something like to return these variables (i think it is not possible) or to use them as global variables in the function run. Thanks for your interest!

writing to a file with php and javascript

So I want to use buttons on my HTML page to call a php program that will write to a text file. What I currently get is a success package from my Ajax function, but the file that it has supposed to have written does not exist.
my HTML
<button type = "button" onclick = "getRequest('changeState.php', changeState('1'), 0)"></button>
my Javascript functions:
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
}
catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function()
{
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
function changeState(input)
{
state = input;
document.GetElementById("state_current").innerHTML = state;
}
My PHP file:
<?php
$f = fopen("file.txt");
fwrite($f, "Hello World");
fclose($f);
?>
I'll be honest, I'm very new to php, but my syntax seems fine because I'm not dropping any error messages, and I know that the program runs successfully because I get the success function to run. Have I missed something glaringly obvious?
file.txt should be created, if calling your PHP-script directly. If not probably PHP is not allowed to create it. Unfortunately its not that easy to understand which user is used to run PHP, and this user must have the rights to write to the webroot-folder of the server. As far as I know this depends on how PHP is executed (module vs CGI).
I would give it a try to change the folders access rights to "777" (anyone is allowed to do anything).
The changeState function doesn't get called on success because you are passing the value returned by the changeState function not the function reference, should be:
<button type = "button" onclick = "getRequest('changeState.php', changeState, 0)"></button>
You can also check on the Network Tab on the Developers Tools to see if you actually sent the request to the URL. If you didn't, then there's something wrong with your URL or your server.

AJAX issue returning the value

I am using a javascript function that calls another javascript function (zConvertEmplidtoRowid) that uses an ajax call that runs a query to return data in a variable (rowid). My problem is I don't know how to return the data to the original function.
Here is a snippet of the original function calling the ajax function (zConvertEmplidtoRowid)
var rowid = zConvertEmplidtoRowid(emplid);
//the alert should show what the query via ajax returned
alert(rowid);
zEmployeePortrait(emplid, ajaxlink);
}
And here is the ajax function...I imagine somewhere in here I need to place the return, but I've never used ajax before, so I'm not sure.
function zConvertEmplidtoRowid(emplid, ajaxlink, callback) {
if (typeof XMLHttpRequest == 'undefined') {
XMLHttpRequest = function() {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
throw new Error('This browser does not support XMLHttpRequest or XMLHTTP.');
};
}
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var rowid = request.responseText;
callback(rowid);
}
}
var ajax_link = ajax_link + "?emplid=" + emplid;
request.open('GET', ajax_link);
request.send();
}
As #epascarello pointed out, the ajax call is asynchronous and the code you have written is expecting the call to return in a synchronous way.
You have two options:
1) Make the ajax call synchronous (I highly recommend not to take this route).
2) Pass a callback function as a parameter to the function making the ajax call and then invoke the callback function once the call returns.
e.g:
function zConvertEmplidtoRowid(emplid, ajaxlink, callback) { //Added a callback function parameter
if (typeof XMLHttpRequest == 'undefined') {
XMLHttpRequest = function() {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
throw new Error('This browser does not support XMLHttpRequest or XMLHTTP.');
};
}
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var rowid = request.responseText;
//now you invoke the callback passing the rowid as argument
callback(rowid);
}
}
var ajax_link = ajax_link + "?emplid=" + emplid;
request.open('GET', ajax_link);
request.send();
}
zConvertEmplidtoRowid(emplid, ajaxlink, function(rowId) {
alert(rowId);
zEmployeePortrait(emplid, ajaxlink);
});
As epascarello has implied in his comment, you need to make the javascript call synchronously in order to get a return value...
I tend to use jquery to assist with the call, but a quick google suggests you can do it your way by changing:
request.open('GET', ajax_link);
to:
request.open('GET', ajax_link, false);
and the response is then accessible through:
request.responseText
taken from here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests

Variable out of scope [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to return AJAX response Text?
How to return the response from an AJAX call from a function?
After whole day without solution to this. I read that this isn't possible or cant be done etc. I did go trough all of topics related, but cant find solution.
So i think my variable in code is out of scope and i cant return it, cant use it.
js file:
function getXMLHttp()
{
var xmlHttp
try
{
//Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
//Internet Explorer
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
alert("Your browser does not support AJAX!")
return false;
}
}
}
return xmlHttp;
}
function MakeRequest()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState == 4)
{
var myvar = new Array();
myvar=JSON.parse(xmlHttp.responseText);
return myvar;
}
}
xmlHttp.open("GET", "showimage.php", true);
xmlHttp.send();
}
So here above is ok, its returning value of php script when its finished.
And i want this myvar variable in html file. Tried like this:
window.onload = function() {
var myvar = MakeRequest();
alert (myvar);
}
It fails, returning undefined value.
Tried also making MakeRequest function as callback function, and then calling it from html like
MakeRequest(function(txt){
});
Then I got response, but can just alert it. I don't want to alert it. I need it to be stored in variable myvar because its needed later in code.

Newbie AJAX Qn: request.send(information)

I am completely new to AJAX hence this question. I want to send some information from my javascript code to my servlet.
function getDetails() {
vals = document.getElementById("name").value;//works: vals does get inputted value
request = createRequest();
if (request == null) {
alert("Unable to create request");
return;
}
var url= "ValidateUser.do";
request.open("POST", url, true);
request.onreadystatechange = displayDetails;
//How do I send the value of "vals" to my servlet?
request.send("name="+vals);
}
When I run req.getParameter("name") on my servlet, I always get no value even though "vals" does contain the inputted value. So my question is- how do I access this value from my servlet?
EDIT:
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (tryMS) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (otherMS) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = null;
}
}
}
return request;
}
FURTHER EDIT:
Servlet code: I want the println statement to print out the name.
//shortened: this method is called by a ControllerServlet
public Object perform(HttpServletRequest req, HttpServletResponse resp) {
//retrieve customer from database
model = SeekerCustomer.getCustomer(req.getParameter("name"));
System.out.println(req.getParameter("name"));
}
function ajaxRequest(){
var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
for (var i=0; i<activexmodes.length; i++){
try{
return new ActiveXObject(activexmodes[i])
}
catch(e){
//suppress error
}
}
}
else if (window.XMLHttpRequest) // if Mozilla, Safari etc
return new XMLHttpRequest()
else
return false
}
function postReq(){
var mypostrequest=new ajaxRequest()
mypostrequest.onreadystatechange=function(){
if (mypostrequest.readyState==4){
if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("my_Result_tag").innerHTML=mypostrequest.responseText //this is where the results will be put!
}
else{
alert("An error has occured making the request")
}
}
}
var vals = document.getElementById("name").value
var parameters="name="+vals
mypostrequest.open("POST", "ValidateUser.do", true)
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
mypostrequest.send(parameters)
}
In the servlet access vals using:
request.getParameter("name");

Categories

Resources