Jump to content

How to Return Useable JavaScript


The Little Guy

Recommended Posts

In this short segment, you should already know some about AJAX, and some JavaScript.

 

To start off, to use javavascript in our returned results, we use JavaScript's built in eval() function.

 

So, copy this code into an the head section of your HTML (with the script tags), or place it in a separate JavaScript file and include it in your head. Either way works fine.

 

If you look in the javascript readyState where readyState == 4, you will see the following line is our eval function.

function testScript(){
var ajaxRequest;
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 Doesn't support AJAX.");
			return false;
		}
	}
}
ajaxRequest.onreadystatechange = function(){
	if(ajaxRequest.readyState == 4){
		eval(ajaxRequest.responseText);
		alert(myValue);
		alert(function2());
	}
}
ajaxRequest.open("GET", 'tst.php', true);
ajaxRequest.send(null);
}

 

Under ajaxRequest.open, we call the following file: tst.php, which contains our usable JavaScript

 

In this file I added 2 different things, the first is a variable that we can use, and the other is a function that we can use

 

<?php
echo 'var myValue = "Hello World!";';

echo 'function function2(){
return "Function 2!";
}';
?>

 

If you notice in the first JavaScript code, we have alert(myValue);, this comes from the variable from the called php script, and then we have alert(function2()); which also comes from the php file.

 

We will make a basic link for you to test it out with, just place it in your body code.

 

<a href="javascript:testScript()">Click Me</a>

 

That is about it! Experiment, and have FUN! ENJOY!

 

Returning any HTML will cause your code to FAIL

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.