I'm trying to pass a variable to a javascript function, but I'm not sure what's going on as I am primarily a PHP person.
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction( str){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById("emailconfirm").innerHTML= ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "Atest.php?Email="+str, true);
ajaxRequest.send(null);
}
//-->
</script>
the form
<form name='myForm'>
<input name="email" id="email"type="text" />
<input name="button" onclick="ajaxFunction(document.getElementById('email').value" type="button" />
</form>
I wanna be able once the button get clicked, the email text input will be passed to the javascript function.
You're almost perfect, just a few things:
You missed a ) in your onclick event. Just add it to the end and it should work.
You don't need all that try..catch stuff, unless you need to support Internet Explorer 6, so you can just get rid of it and leave ajaxRequest = new XMLHttpRequest().
Related
I'd like to run some javascript code directly "from the flash (swf) banner".
Is it possible? And how can I manage that?
In order to be able to inject JS scripts in the DOM using ActionScript and then communicate via the injected functions you could do something like this:
1) import the external class.
import flash.external.ExternalInterface;
2) declare a constant variable with all the JS functions:
private const script_js :XML =
<script>
<![CDATA[
function() {
AJXFNC = {
ajaxFunction:function(_url){
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari, Chrome
ajaxRequest = new XMLHttpRequest();
ajaxRequest.open("GET", _url, true);
ajaxRequest.send(null);
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
ajaxRequest.open("GET", _url, true);
ajaxRequest.send();
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
ajaxRequest.open("GET", _url, true);
ajaxRequest.send();
} catch (e){
// Something went wrong
return false;
}
}
}
}
}
}
]]>
</script>;
3) inject the JS to DOM:
try {
if( ExternalInterface.available )ExternalInterface.call( script_js );
} catch( error:Error ) {
trace("ExternalInterface is not available");
}
4) call a function:
ExternalInterface.call( "AJXFNC.ajaxFunction", "http://www.google.com" );
I have pasted the technique into this answer because i usually do not trust the up-time of a blog, but all rights go to Adi Feiwel, for writing this: http://todepoint.com/blog/2011/08/01/injecting-and-calling-js-functions-from-within-flash-using-external/
Trying to implement the simplest server-client on my PC.
The argv part is because I'm debugging it in VS and it started as an application. It works as a standalone app and I want to make it a server. If I enter
http://localhost:8080/
in the browser I can see in the node.exe window that the server runs properly. But when I run the html with the script nothing happens (I get no response, although no error either, and the server doesn't get the request)
If anyone could help I would appreciate it.
Client:
<html>
<body>
<script type = "text/javascript">
<!--
//Browser Support Code
function ajaxFunction() {
var ajaxRequest; // The variable that makes Ajax possible!
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4) {
document.myForm.response.value = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "http://localhost:8080", true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
<button onclick="ajaxFunction()">request</button> <br />
<input type='text' name='response' />
</form>
</body>
</html>
Server:
var fs = require("fs"),
my_http = require("http"),
sys = require("sys");
my_http.createServer(function(request,response){
fs.readFile(process.argv[2], 'utf8', function(err, data) {
if (err) {
console.log("FILE READ ERROR: ", err);
process.exit();
}
response.writeHeader(200, {"Content-Type": "text/plain"});
response.write("message");
response.end();
});
}).listen(8080);
sys.puts("Server Running on 8080");
EDIT:
Well, I made some progress you could say, but I don't like not knowing what the problem is. I created a new TypeScript project in VS and put my ajaxFunction in it and the button\textbox as in the initial html file. Now the server does get the request but it doesn't seem to call the callback function onreadystatechange.
The new client code:
default.htm:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>TypeScript HTML App</title>
<link rel="stylesheet" href="app.css" type="text/css" />
<script src="app.js"></script>
</head>
<body>
<h1>TypeScript HTML App</h1>
<div id="content"></div>
<button onclick="ajaxFunction()">request</button> <br />
<input type='text' name='response' />
</body>
</html>
app.ts: (it's in js though)
var response;
function ajaxFunction() {
var ajaxRequest; // The variable that makes Ajax possible!
var response;
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4) {
response.innerHTML = "hi";
}
}
ajaxRequest.open("GET", "http://localhost:8080", true);
ajaxRequest.send(null);
}
window.onload = () => {
response = document.getElementById('content');
};
I am now getting a "Cancelled" network request in Chrome's dev tools.
New answer:
What do you get if you log some values out in your onreadystatechange handler?
ajaxRequest.onreadystatechange = function () {
console.log('ajaxRequest.readyState=', ajaxRequest.readyState, ajaxRequest.status);
if (ajaxRequest.readyState == 4) {
document.myForm.response.value = ajaxRequest.responseText;
}
}
Original answer:
There are a couple of possibilities that might be occurring.
Your ajaxRequest variable is local to the ajaxFunction() and might be getting garbage collected after the function is executed.
Try moving the ajaxRequest outside ajaxFunction() like this:
var ajaxRequest; // The variable that makes Ajax possible!
function ajaxFunction() {
... rest of your client code.
}
That way the variable will still be in scope after the function has been invoked.
Alternatively, you might be running into a cross-domain security issue if your client is running on a different domain to your server (e.g. http://localhost:8081/ vs http://localhost:8080/).
Can you check if the browser is actually making the request (i.e. check with the browser's development tools and not on the server)? There should be a 'network' tab in the development tools for whichever browser you are using.
Have a look at the documentation for CORS (Cross-Origin Resource Sharing) to get an idea of what might be happening.
Edit: Here's a nice overview of cross-domain security errors and how to address it in a standard Node.js server: http://bannockburn.io/2013/09/cross-origin-resource-sharing-cors-with-a-node-js-express-js-and-sencha-touch-app/
This answer shows how to add the headers in a Connect server:
How can I add CORS-Headers to a static connect server?
I need to send a mail with jsp, but the page itself mustn't reload. The whole implementation is working fine when reloading on the POST-event, but adjusting the code to work with ajax breaks it. It seems that the jsp-Code within the index.jsp is not executed, when the ajax event is triggerd.
I am gonna show some snippets:
index.jsp
<%
String result = "=(";
String to = request.getParameter("rec_mail");
if(to != null) {
String from = request.getParameter("sendermail");
String host = "mailserver";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session mailSession = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("Feedback");
message.setText(request.getParameter("feedbackinput"));
Transport.send(message);
result = "Sucess!";
}catch (MessagingException e) {
e.printStackTrace();
result = "failed!";
}
}
out.println(request.getParameter("sendermail"));
out.println(result);
%>
<input id="bsend" class="fbutton" type="submit" name="send" value="Send" onclick="loadContent()" style="float:right; width:18%; height:35%;" >
ajax.js
var xmlhttp
function loadContent() {
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Your browser does not support Ajax!");
return;
}
var url="./index.jsp";
xmlhttp.open("post",url,true);
xmlhttp.send(null);
xmlhttp.onreadystatechange=getOutput;
}
function getOutput()
{
if (xmlhttp.readyState==4)
{
alert("Message sent!");
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
(just showing the relevant parts, everywhere)
I get the alert-message, but no mail is sent ... I hope it is clear, what I am trying to do..
Thank you!
Best regards
Don't you also need to set a header for a HTTP Post
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
also, not sure if it will make a difference but I would make "post" to "POST".
I'm using php on a linux machine. My html code issues an ajax request to the local apache server (http://localhost), and the data from the server should be printed out on the screen. However, nothing gets printed.
The code on the "client" side (the html file which I load in the browser) is:
<html>
<body>
<script language="javascript" type="text/javascript">
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if( ajaxRequest.readyState == 4 ){
document.writeln( ajaxRequest.responseText );
}
}
ajaxRequest.open("GET", "http://localhost/s.php", true);
ajaxRequest.send(null);
}
</script>
</body>
</html>
and the "server" script (which is /var/www/s.php) is:
<html>
<body>
<?php
echo date("H:i:s");
?>
</body>
</html>
Any suggestions?
TIA
You should debug your code
Check Apache access log that s.php was loaded
If it loaded then add debug alert function to onreadystatechange callback function
If this function is called then check what return code it received: alert(ajaxRequest.readyState);
If code is 4 then check what content it returned: alert(ajaxRequest.responseText);
There doesn't seem to be anything calling ajaxFunction when the page loads, so the request is never sent.
For some reason, onreadystatechange call back function is not being called in asynchronous mode. I tested the post in synchronous mode and confirmed that post itself is working fine (commented out testing code I used to check post in synchronous mode). The problem occurs both in safari and firefox latest version. Can someone please tell me what I am doing wrong here? Thank you.
<html>
<head>
<script>
function recordScore(str)
{
if (str.length==0)
{
return;
}
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="http://hellworld3.appspot.com/findcountry";
var params = "screenname="+document.getElementById("screenname1").value+"&score="+document.getElementById("score1").value;
alert("params: "+params);
xmlHttp.open("POST",url,true);
xmlHttp.onreadystatechange = function()
{
alert("entered call back function. readstate value is: "+xmlHttpreadyState+". Response Text is: "+xmlHttp.responseText);
if (xmlHttp.readyState==4)
{
document.getElementById("message").innerHTML=xmlHttp.responseText;
}
}
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlHttp.send(params);
//Testing code for synchronous mode
//alert("Http get status is: "+xmlHttp.status);
//alert("Http ready state value is: "+xmlHttp.readyState);
//alert("Http get response text is: "+xmlHttp.responseText);
//document.getElementById("message").innerHTML=xmlHttp.responseText;
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
</script>
</head>
<body>
<form name="testform">
Screename:
<input type="text" id="screenname1" name="screenname">
<br/>
Score:
<input type="text" id="score1" name="score" onchange="recordScore(this.value)">
<br/>
<p id="message">test</p>
<input type="submit" value="Submit">
</form>
</body>
</html>
you have an error in the onreadystatechange function:
alert("entered call back function. readstate value is: "+xmlHttpreadyState+". Response Text is: "+xmlHttp.responseText);
xmlHttpreadyState should be xmlHttp.readyState
After I fixed that, it worked for me in FF3
Correct me if I'm wrong, but for POST don't you need to do a setRequestHeader for Content-Length like so;
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader('Content-length',(params?params.length:0));
xmlHttp.send(params);
This might correct your problem.