Help with my first own object in JavaScript/jQuery - javascript

I have written a PHP script that checks whether a domain is available for registration or not.
To automate the process, I have also written a js script that automatically sends AJAX calls to the PHP script and tells the user whether the domain is available or not, without submitting the form:
$(document).ready(function() {
function Domain() {
this.name = '';
this.dotComRegistered = 1;
this.dotNetRegistered = 1;
this.dotOrgRegistered = 1;
}
Domain.prototype.check = function(input) {
this.name = input;
if (this.name.length >= 3 && this.name.length <= 63) {
$.get('check.php', { d : this.name }, function(json) {
alert(json);
this.dotComRegistered = $.evalJSON(json).com;
this.dotNetRegistered = $.evalJSON(json).net;
this.dotOrgRegistered = $.evalJSON(json).org;
});
}
}
var domain = new Domain();
var input = ''
$('#domain').keyup(function() {
input = $('#domain').val();
domain.check(input);
});
$('form').submit(function() {
input = $('#domain').val();
domain.check(input);
return false;
});
});
As you can see I created an object called Domain which represents a domain name. The object has just one method (besides the constructor) that sends AJAX request to the PHP script (which returns json).
The problem is that the Domain.prototype.check() method doesn't work (I don't get an alert window) and I don't know where's the problem. When I place the AJAX call outside of the method it works, so that isn't the problem.
I'm an OOP beginner so maybe I used some wrong syntax to write the Domain object (I'm reading a book from John Resig about OOP in JavaScript right now).
The #domain is the input field for domain names.

have you stepped through with Firebug? Set a breakpoint at the point the request is made and step through from that point. Where does the dn come from in your code?
Also, is there a specific reason that your Domain function is in $(document).ready()? It doesn't really need to be there (you might consider namespacing your classes too).

Related

Is it possible to read ExperimentId and VariationId in Javascript with Google Optimize?

I have created an A/B-test using Google Optimize. Now I would like to read the current experimentId and variationId in Javascript. My goal is to run different javascript based on the given variation.
I can't seem to find any info on this in the documentation. Is it possible?
Now there is also the Google Optimize javascript API available that is a better option:
The experimentId is now available in the Optimize UI, as soon as the experiment is created (before start).
The API is already available in the page and you can use it like this:
google_optimize.get('<experimentId>');
(note: this will work only after the Optimize container script has been loaded)
You can also register a callback to run the javascript that you want at any time (even before the Optimize script has been loaded) using:
function gtag() {dataLayer.push(arguments)}
function implementExperimentA(value) {
if (value == '0') {
// Provide code for visitors in the original.
} else if (value == '1') {
// Provide code for visitors in first variant.
}
gtag('event', 'optimize.callback', {
name: '<experiment_id_A>',
callback: implementExperimentA
});
If you want to find both the experimentId and variation you can register a callback for any experiment:
function implementManyExperiments(value, name) {
if (name == '<experiment_id_A>') {
// Provide implementation for experiment A
if (value == '0') {
// Provide code for visitors in the original.
} else if (value == '1') {
// Provide code for visitors in first variant.
...
} else if (name == '<experiment_id_B>') {
// Provide implementation for experiment B
...
}
gtag('event', 'optimize.callback', {
callback: implementManyExperiments
});
For more details
https://support.google.com/optimize/answer/9059383
EDIT: Nevermind my cookie-based answer below, I found a better solution.
Just do this:
var propertyId = "UA-1234567-33";
var experimentId = Object.keys(gaData[propertyId].experiments)[0];
var variationId = gaData[propertyId].experiments[experimentId];
Old answer:
(Don't do this.. keeping it here for reference)
Maximes answer is working but was not exactly what I was looking for. I wanted to be able to find the experimentId and variationId without adding code through the visual editor. I finally found a way.
The values are actually stored in the _gaexp cookie. The cookie is present when an experiment is running. You can inspect it in Chrome by opening Developer tools, going to the Application tab and clicking Cookies in the left pane. It looks something like this:
GAX1.2.S1SJOWxJTVO9tM2QKV3NcP.17723.1
The experiment id is the part after the second number:
S0SJOWxJTVO1tM2QKD2NcQ
The variation id is the last number:
1
I wrote this code to extract it from the cookie:
function getCookieValue(cookieName) {
var result = document.cookie.match('(^|;)\\s*' + cookieName + '\\s*=\\s*([^;]+)');
return result ? result.pop() : '';
}
function getExperimentId() {
var cookie = getCookieValue('_gaexp');
if (cookie == undefined) {
return undefined;
} else {
var fields = cookie.split('.');
return fields[2];
}
}
function getVariationId() {
var cookie = getCookieValue('_gaexp');
if (cookie == undefined) {
return undefined;
} else {
var fields = cookie.split('.');
return fields[4];
}
}
var experimentId = getExperimentId();
var variationId = getVariationId();
WARNING: Fetching the experiment ID and variationId from the cookie is not a good idea. For two reasons.
When the experiment is finished, the cookie is still present. The cookie is cached, so you will find an experimentId and variationId that does not apply, and you can not know if the experiment is running or not.
If you stop experiment A, and start experiment B, the old value for A will still be part of the cookie. So it will look something like this:
GAX1.2.S1SJOWxJTVO9tM2QKV3NcP.17723.1!vr1mB2L2RX6kSI1ZnUDTzT.18721.0
which is the same as how it would look if you were running to experiments at once. It makes it hard to reason about what experimentId to use.
Google Optimize allow you to run arbitrary JS on a per DOM element basis.
This feature is meant to modify the DOM elements, but there's nothing stopping you from using it to call a JS function or define some variables.
How to set up the script
Edit your experiment variant in the Visual Editor.
Click on the Select elements icon (the rectangle in the top left corner)
In the Element Selector field, type in body.
Click the Add change button and select Javascript. This will bring up a dialog that allows you to input a JS function that will be called for the body.
Put in the code you want to run in there.
What code to run
Assuming you have a doSomething() method define on your page, you can have your Google Optimized function look something like this:
doSomething("Experiment #1", "Variant A");
Alternatively, you can try defining your variables globally.
// We need to use `windows` here, because if we define a variable
// with `var`, it will be limited to the scope of the Google Optimize
// function.
window["google_optimize_exp_id"] = "Experiment #1";
window["google_optimize_exp_var_id"] = "Variant A";
If you use the second method, keep in mind that you need to wait until the Google Optimized function has run before running your own logic.
There are a 3 ways you could do this:
1) Depending on your Google Analytics setup, you can access the following object via Chrome console and pass in your GA property ID:
Object.keys(window.gaData["YOUR-GA-PROPERTY ID"].experiments).forEach(function(key, index){
var value = window.gaData["YOUR-GA-PROPERTY ID"].experiments[key];
console.log("Info", key, value, index);
});
2) As someone has already pointed out, you can access the _gaexp cookie, which stores your experiment ID and variant number.
//READ THE COOKIE
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
};
// GET THE COOKIE
let getCookie = readCookie("_gaexp");
console.log('getCookie', getCookie);
// WILL RETURN A STRING IN THIS FORMAT
// GAX1.2.YOUREXPERIMENTID.18803.0
// The long number in the middle is your experiment ID
// The number at the end is your variant number (0)
// SPLIT THE COOKIE
let splitCookie = readCookie("_gaexp").split("!");
// SPLIT THE COOKIE SO YOU CAN ACCESS THE EXPERIMENT ID AND VARIANT NUMBER
3) And lastly, you could use your dataLayer.
A bit more of a clunky way to do it, but in Optimize 360, you could add JavaScript in each variant, (when you go edit your AB Test/variants). And send your experiment ID to your dataLayer, as well as other information.
EG:
function returnDate() {
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
today = mm + '/' + dd + '/' + yyyy;
return today;
}
var dateToday = returnDate();
var ABTest = {
id: 'YOUREXPERIMENTID',
name: 'Title of your test',
description: 'Test description',
date: dateToday, //The launch date of AB Test.
variant: 1,
totalVariants: 5
};
// AND THEN PUSH ALL THAT INFORMATION INTO THE DATALAYER
dataLayer.Tests.push(ABTest);
Then to access all that information, all you need to do is access the window.dataLayer object.
Now how I've used google tag manager, add the "Test" key, in dataLayer.Tests. But of course you don't need that, but I just like to organise my object :)
I've found that the variant number can be obtained running a code like:
gaData["UA-XXXXXXXX-X"].experiments['ZYkOuNLKEoeLytt-dLWw3x']
The result should be "0"for the original, "1" for the first variant...
You can get the experiments with:
gaData["UA-XXXXXXXX-X"].experiments
Of course you have to replace UA-XXXXXXXX-X for the Google Analytics ID and ZYkOuNLKEoeLytt-dLWw3x for your experiment id.

passing data from authentication cookie to javascript

I am using an authentication cookie passed between websites on the same domain. The cookie contains some user info and page info (the accession number). The design goal is for the user to click a button on the referring website, and it will launch a second website, authenticate based on the cookie, and do some useful stuff with the accession number. I got most of this built, including getting the authentication passed and properly parsed out on the receiving system.
The problem I am having is that I can't get the data within the cookie into the javascript on the page. It seems when i launch website2 from website1, $(document).ready() is not fired after the page_load event (which handles the cookie parsing). Also I tried using a literal to post the javascript code, it's never fired (seemingly it places it after the client side stuff is executed.
What I really want to do is call a javascript function getResults(accnum) using this data.
I have this code on the page_load event:
if (userdata != null)
{
accnum = userdata[4];
}
if (accnum != String.Empty)
{
//HttpCookie accnumcookie = new HttpCookie("accnum", accnum);
//this.Context.Response.Cookies.Set(accnumcookie);
}
}
When I run the .Set function, I'm not really sure of the innards and details, but long story short, the cookie is set but does nothing.
This is the document.ready.
$(document).ready(function () {
var accnum = new String();
accnum = GetCookie('accnum');
if (accnum != null) {
document.cookie = 'test=testz';
var srch = document.getElementById('crit');
srch.style.display = 'none';
getResults('', 'accnum', accnum);
}

Getting functions from another script in JS

I load this JS code from a bookmarklet:
function in_array(a, b)
{
for (i in b)
if (b[i] == a)
return true;
return false;
}
function include_dom(script_filename) {
var html_doc = document.getElementsByTagName('head').item(0);
var js = document.createElement('script');
js.setAttribute('language', 'javascript');
js.setAttribute('type', 'text/javascript');
js.setAttribute('src', script_filename);
html_doc.appendChild(js);
return false;
}
var itemname = '';
var currency = '';
var price = '';
var supported = new Array('www.amazon.com');
var domain = document.domain;
if (in_array(domain, supported))
{
include_dom('http://localhost/bklts/parse/'+domain+'.js');
alert(getName());
}
[...]
Note that the 'getName()' function is in http://localhost/bklts/parse/www.amazon.com/js. This code works only the -second- time I click the bookmarklet (the function doesn't seem to get loaded until after the alert()).
Oddly enough, if I change the code to:
if (in_array(domain, supported))
{
include_dom('http://localhost/bklts/parse/'+domain+'.js');
alert('hello there');
alert(getName());
}
I get both alerts on the first click, and the rest of the script functions. How can I make the script work on the first click of the bookmarklet without spurious alerts?
Thanks!
-Mala
Adding a <script> tag through DHTML makes the script load asynchroneously, which means that the browser will start loading it, but won't wait for it to run the rest of script.
You can handle events on the tag object to find out when the script is loaded. Here is a piece of sample code I use that seems to work fine in all browsers, although I'm sure theres a better way of achieving this, I hope this should point you in the right direction:
Don't forget to change tag to your object holding the <script> element, fnLoader to a function to call when the script is loaded, and fnError to a function to call if loading the script fails.
Bear in mind that those function will be called at a later time, so they (like tag) must be available then (a closure would take care of that normally).
tag.onload = fnLoader;
tag.onerror = fnError;
tag.onreadystatechange = function() {
if (!window.opera && typeof tag.readyState == "string"){
/* Disgusting IE fix */
if (tag.readyState == "complete" || tag.readyState == "loaded") {
fnLoader();
} else if (tag.readyState != "loading") {
fnError();
};
} else if (tag.readyState == 4) {
if (tag.status != 200) {
fnLoader();
}
else {
fnError();
};
};
});
It sounds like the loading of the external script (http://localhost/bklts/parse/www.amazon.com/js) isn't blocking execution until it is loaded. A simple timeout might be enough to give the browser a chance to update the DOM and then immediately queue up the execution of your next block of logic:
//...
if (in_array(domain, supported))
{
include_dom('http://localhost/bklts/parse/'+domain+'.js');
setTimeout(function() {
alert(getName());
}, 0);
}
//...
In my experience, if zero doesn't work for the timeout amount, then you have a real race condition. Making the timeout longer (e.g. 10-100) may fix it for some situations but you get into a risky situation if you need this to always work. If zero works for you, then it should be pretty solid. If not, then you may need to push more (all?) of your remaining code to be executed into the external script.
The best way I could get working: Don't.
Since I was calling the JS from a small loader bookmarklet anyway (which just tacks the script on to the page you're looking at) I modified the bookmarklet to point the src to a php script which outputs the JS code, taking the document.domain as a parameter. As such, I just used php to include the external code.
Hope that helps someone. Since it's not really an answer to my question, I won't mark this as the accepted answer. If someone has a better way, I'd love to know it, but I'll be leaving my code as is:
bookmarklet:
javascript:(function(){document.body.appendChild(document.createElement('script')).src='http://localhost/bklts/div.php?d='+escape(document.domain);})();
localhost/bklts/div.php:
<?php
print("
// JS code
");
$supported = array("www.amazon.com", "www.amazon.co.uk");
$domain = #$_GET['d']
if (in_array($domain, $supported))
include("parse/$domain.js");
print("
// more JS code
");
?>

Javascript Validation not working on .Net Content Pages

I'm wondering if anyone else has experienced the following issue.
On a single non-linked (to a master page) .aspx page, I'm performing simple JS validations:
function validateMaxTrans(sender, args) {
// requires at least one digit, numeric only characters
var error = true;
var regexp = new RegExp("^[0-9]{1,40}(\.[0-9]{1,2})?$");
var txtAmount = document.getElementById('TxtMaxTransAmount');
if (txtAmount.value.match(regexp) && parseInt(txtAmount.value) >= 30) {
document.getElementById('maxTransValMsg').innerHTML = ""
args.IsValid = true;
}
else {
document.getElementById('maxTransValMsg').innerHTML = "*";
args.IsValid = false;
}
}
Then as soon as I move this into a Master page's content page, I get txtAmount is null.
Is there a different way to access the DOM when attempting to perform client-side JS validation with master/content pages?
Look at the source for your rendered page within the master page. Many elements will have an ID like ControlX$SubControlY$txtMaxTransAmount ... you'll need to adjust your validation accordingly. I will often just inject the IDs into the client doc..
<script type="text/javascript">
var controls = {
'txtAmount': '<%=TxtMaxTransAmount.ClientId%>',
...
}
</script>
I'd put this right before the end of your content area, to make sure the controls are rendered already. This way you can simply use window.controls.txtAmount to reference the server-side control's tag id. You could even make the right-side value a document.getElementById('...') directly.
Are you using asp textboxes? If so I believe you need to do somethign like document.getElementById('<%= txtMaxTransAmount.ClientID %>').
Hope this helps
Tom

Calling a JavaScript function returned from an Ajax response

I have a system where I send an Ajax command, which returns a script block with a function in it. After this data is correctly inserted in the DIV, I want to be able to call this function to perform the required actions.
Is this possible?
I think to correctly interpret your question under this form: "OK, I'm already done with all the Ajax stuff; I just wish to know if the JavaScript function my Ajax callback inserted into the DIV is callable at any time from that moment on, that is, I do not want to call it contextually to the callback return".
OK, if you mean something like this the answer is yes, you can invoke your new code by that moment at any time during the page persistence within the browser, under the following conditions:
1) Your JavaScript code returned by Ajax callback must be syntactically OK;
2) Even if your function declaration is inserted into a <script> block within an existing <div> element, the browser won't know the new function exists, as the declaration code has never been executed. So, you must eval() your declaration code returned by the Ajax callback, in order to effectively declare your new function and have it available during the whole page lifetime.
Even if quite dummy, this code explains the idea:
<html>
<body>
<div id="div1">
</div>
<div id="div2">
<input type="button" value="Go!" onclick="go()" />
</div>
<script type="text/javascript">
var newsc = '<script id="sc1" type="text/javascript">function go() { alert("GO!") }<\/script>';
var e = document.getElementById('div1');
e.innerHTML = newsc;
eval(document.getElementById('sc1').innerHTML);
</script>
</body>
</html>
I didn't use Ajax, but the concept is the same (even if the example I chose sure isn't much smart :-)
Generally speaking, I do not question your solution design, i.e. whether it is more or less appropriate to externalize + generalize the function in a separate .js file and the like, but please take note that such a solution could raise further problems, especially if your Ajax invocations should repeat, i.e. if the context of the same function should change or in case the declared function persistence should be concerned, so maybe you should seriously consider to change your design to one of the suggested examples in this thread.
Finally, if I misunderstood your question, and you're talking about contextual invocation of the function when your Ajax callback returns, then my feeling is to suggest the Prototype approach described by krosenvold, as it is cross-browser, tested and fully functional, and this can give you a better roadmap for future implementations.
Note: eval() can be easily misused, let say that the request is intercepted by a third party and sends you not trusted code. Then with eval() you would be running this not trusted code. Refer here for the dangers of eval().
Inside the returned HTML/Ajax/JavaScript file, you will have a JavaScript tag. Give it an ID, like runscript. It's uncommon to add an id to these tags, but it's needed to reference it specifically.
<script type="text/javascript" id="runscript">
alert("running from main");
</script>
In the main window, then call the eval function by evaluating only that NEW block of JavaScript code (in this case, it's called runscript):
eval(document.getElementById("runscript").innerHTML);
And it works, at least in Internet Explorer 9 and Google Chrome.
It is fully possible, and there are even some fairly legitimate use cases for this. Using the Prototype framework it's done as follows.
new Ajax.Updater('items', '/items.url', {
parameters: { evalJS: true}
});
See documentation of the Ajax updater. The options are in the common options set. As usual, there are some caveats about where "this" points to, so read the fine print.
The JavaScript code will be evaluated upon load. If the content contains function myFunc(),
you could really just say myFunc() afterwards. Maybe as follows.
if (window["myFunc"])
myFunc()
This checks if the function exists. Maybe someone has a better cross-browser way of doing that which works in Internet Explorer 6.
That seems a rather weird design for your code - it generally makes more sense to have your functions called directly from a .js file, and then only retrieve data with the Ajax call.
However, I believe it should work by calling eval() on the response - provided it is syntactically correct JavaScript code.
With jQuery I would do it using getScript
Just remember if you create a function the way below through ajax...
function foo()
{
console.log('foo');
}
...and execute it via eval, you'll probably get a context problem.
Take this as your callback function:
function callback(result)
{
responseDiv = document.getElementById('responseDiv');
responseDiv.innerHTML = result;
scripts = responseDiv.getElementsByTagName('script');
eval(scripts[0]);
}
You'll be declaring a function inside a function, so this new function will be accessible only on that scope.
If you want to create a global function in this scenario, you could declare it this way:
window.foo = function ()
{
console.log('foo');
};
But, I also think you shouldn't be doing this...
Sorry for any mistake here...
I would like to add that there's an eval function in jQuery allowing you to eval the code globally which should get you rid of any contextual problems. The function is called globalEval() and it worked great for my purposes. Its documentation can be found here.
This is the example code provided by the jQuery API documentation:
function test()
{
jQuery.globalEval("var newVar = true;")
}
test();
// newVar === true
This function is extremely useful when it comes to loading external scripts dynamically which you apparently were trying to do.
A checklist for doing such a thing:
the returned Ajax response is eval(ed).
the functions are declared in form func_name = function() {...}
Better still, use frameworks which handles it like in Prototype. You have Ajax.updater.
PHP side code
Name of file class.sendCode.php
<?php
class sendCode{
function __construct($dateini,$datefin) {
echo $this->printCode($dateini,$datefin);
}
function printCode($dateini,$datefin){
$code =" alert ('code Coming from AJAX {$this->dateini} and {$this->datefin}');";
//Insert all the code you want to execute,
//only javascript or Jquery code , dont incluce <script> tags
return $code ;
}
}
new sendCode($_POST['dateini'],$_POST['datefin']);
Now from your Html page you must trigger the ajax function to send the data.
.... <script src="http://code.jquery.com/jquery-1.9.1.js"></script> ....
Date begin: <input type="text" id="startdate"><br>
Date end : <input type="text" id="enddate"><br>
<input type="button" value="validate'" onclick="triggerAjax()"/>
Now at our local script.js we will define the ajax
function triggerAjax() {
$.ajax({
type: "POST",
url: 'class.sendCode.php',
dataType: "HTML",
data : {
dateini : $('#startdate').val(),
datefin : $('#enddate').val()},
success: function(data){
$.globalEval(data);
// here is where the magic is made by executing the data that comes from
// the php class. That is our javascript code to be executed
}
});
}
This code work as well, instead eval the html i'm going to append the script to the head
function RunJS(objID) {
//alert(http_request.responseText);
var c="";
var ob = document.getElementById(objID).getElementsByTagName("script");
for (var i=0; i < ob.length - 1; i++) {
if (ob[i + 1].text != null)
c+=ob[i + 1].text;
}
var s = document.createElement("script");
s.type = "text/javascript";
s.text = c;
document.getElementsByTagName("head")[0].appendChild(s);
}
My usual ajax calling function:
function xhr_new(targetId, url, busyMsg, finishCB)
{
var xhr;
if(busyMsg !== undefined)
document.getElementById(targetId).innerHTML = busyMsg;
try { xhr = new ActiveXObject('Msxml2.XMLHTTP'); }
catch(e)
{
try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
catch(e2)
{
try { xhr = new XMLHttpRequest(); }
catch(e3) { xhr = false; }
}
}
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4)
{
if(xhr.status == 200)
{
var target = document.getElementById(targetId)
target.innerHTML = xhr.responseText;
var scriptElements = target.getElementsByTagName("script");
var i;
for(i = 0; i < scriptElements.length; i++)
eval(scriptElements[i].innerHTML);
if(finishCB !== undefined)
finishCB();
}
else
document.getElementById(targetId).innerHTML = 'Error code: ' + xhr.status;
}
};
xhr.open('GET', url, true);
xhr.send(null);
// return xhr;
}
Some explanation:
targetId is an (usually div) element ID where the ajax call result text will goes.
url is the ajax call url.
busyMsg will be the temporary text in the target element.
finishCB will be called when the ajax transaction finished successfully.
As you see in the xhr.onreadystatechange = function() {...} all of the <script> elements will be collected from the ajax response and will be run one by one. It appears to work very well for me. The two last parameter is optional.
I've tested this and it works. What's the problem? Just put the new function inside your javascript element and then call it. It will work.
This does not sound like a good idea.
You should abstract out the function to include in the rest of your JavaScript code from the data returned by Ajax methods.
For what it's worth, though, (and I don't understand why you're inserting a script block in a div?) even inline script methods written in a script block will be accessible.
I tried all the techniques offered here but finally the way that worked was simply to put the JavaScript function inside the page / file where it is supposed to happen and call it from the response part of the Ajax simply as a function:
...
}, function(data) {
afterOrder();
}
This Worked on the first attempt, so I decided to share.
I solved this today by putting my JavaScript at the bottom of the response HTML.
I had an AJAX request that returned a bunch of HTML that was displayed in an overlay. I needed to attach a click event to a button in the returned response HTML/overlay. On a normal page, I would wrap my JavaScript in a "window.onload" or "$(document).ready" so that it would attach the event handler to the DOM object after the DOM for the new overlay had been rendered, but because this was an AJAX response and not a new page load, that event never happened, the browser never executed my JavaScript, my event handler never got attached to the DOM element, and my new piece of functionality didn't work. Again, I solved my "executing JavaScript in an AJAX response problem" by not using "$(document).ready" in the head of the document, but by placing my JavaScript at the end of the document and having it run after the HTML/DOM had been rendered.
If your AJAX script takes more than a couple milliseconds to run, eval() will always run ahead and evaluate the empty response element before AJAX populates it with the script you're trying to execute.
Rather than mucking around with timing and eval(), here is a pretty simple workaround that should work in most situations and is probably a bit more secure. Using eval() is generally frowned upon because the characters being evaluated as code can easily be manipulated client-side.
Concept
Include your javascript function in the main page. Write it so that any dynamic elements can be accepted as arguments.
In your AJAX file, call the function by using an official DOM event (onclick, onfocus, onblur, onload, etc.) Depending on what other elements are in your response, you can get pretty clever about making it feel seamless. Pass your dynamic elements in as arguments.
When your response element gets populated and the event takes place, the function runs.
Example
In this example, I want to attach a dynamic autocomplete list from the jquery-ui library to an AJAX element AFTER the element has been added to the page. Easy, right?
start.php
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<!-- these libraries are for the autocomplete() function -->
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/ui-lightness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script type="text/javascript">
<!--
// this is the ajax call
function editDemoText(ElementID,initialValue) {
try { ajaxRequest = new XMLHttpRequest();
} catch (e) {
try { ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try { ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
return false;
}}}
ajaxRequest.onreadystatechange = function() {
if ( ajaxRequest.readyState == 4 ) {
var ajaxDisplay = document.getElementById('responseDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var queryString = "?ElementID="+ElementID+"&initialValue="+initialValue;
ajaxRequest.open("GET", "ajaxRequest.php"+queryString, true);
ajaxRequest.send(null);
}
// this is the function we wanted to call in AJAX,
// but we put it here instead with an argument (ElementID)
function AttachAutocomplete(ElementID) {
// this list is static, but can easily be pulled in from
// a database using PHP. That would look something like this:
/*
* $list = "";
* $r = mysqli_query($mysqli_link, "SELECT element FROM table");
* while ( $row = mysqli_fetch_array($r) ) {
* $list .= "\".str_replace('"','\"',$row['element'])."\",";
* }
* $list = rtrim($list,",");
*/
var availableIDs = ["Demo1","Demo2","Demo3","Demo4"];
$("#"+ElementID).autocomplete({ source: availableIDs });
}
//-->
</script>
</head>
<body>
<!-- this is where the AJAX response sneaks in after DOM is loaded -->
<!-- we're using an onclick event to trigger the initial AJAX call -->
<div id="responseDiv">I am editable!</div>
</body>
</html>
ajaxRequest.php
<?php
// for this application, onfocus works well because we wouldn't really
// need the autocomplete populated until the user begins typing
echo "<input type=\"text\" id=\"".$_GET['ElementID']."\" onfocus=\"AttachAutocomplete('".$_GET['ElementID']."');\" value=\"".$_GET['initialValue']."\" />\n";
?>
I needed to get something to do this, I find that this has worked for a long time for me, just posting this here as one of many solutions, I like to have solutions without jQuery and the following function may help you, you can pass the full html with script tags in and it will parse and execute.
function parseScript(_source) {
var source = _source;
var scripts = new Array();
// Strip out tags
while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
var s = source.indexOf("<script");
var s_e = source.indexOf(">", s);
var e = source.indexOf("</script", s);
var e_e = source.indexOf(">", e);
// Add to scripts array
scripts.push(source.substring(s_e+1, e));
// Strip from source
source = source.substring(0, s) + source.substring(e_e+1);
}
// Loop through every script collected and eval it
for(var i=0; i<scripts.length; i++) {
try {
if (scripts[i] != '')
{
try { //IE
execScript(scripts[i]);
}
catch(ex) //Firefox
{
window.eval(scripts[i]);
}
}
}
catch(e) {
// do what you want here when a script fails
if (e instanceof SyntaxError) console.log (e.message+' - '+scripts[i]);
}
}
// Return the cleaned source
return source;
}
Federico Zancan's answer is correct but you don't have to give your script an ID and eval all your script. Just eval your function name and it can be called.
To achieve this in our project, we wrote a proxy function to call the function returned inside the Ajax response.
function FunctionProxy(functionName){
var func = eval(functionName);
func();
}

Categories

Resources