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
https://forums.phpfreaks.com/topic/118748-how-to-return-useable-javascript/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.