Jump to content

Using AJAX to inject and run Javascript on a page


noochies

Recommended Posts

Hello,

I have an application where I am using AJAX to inject some html into a page on the fly. This html code also includes some javascript that I would like to run.

It doesn't seem like the javascript I am injecting is running at all even though I can see the rest of the html.  If I save the page I'm trying to get to work and then run it on my local machine, the javascript works....go figure.The frustrating thing is that I swear it was working for me at one time.

 

So, I've been trying to get a very simplified version to work and I just can't get the javascript to run.

 

 

Here is the code I'm using:

 

test.php

<html>
<head>
<script language="javascript">

function ajaxFunction(url)
{
  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;
        }
      }
    }
    xmlHttp.onreadystatechange=function()
      {
      if(xmlHttp.readyState==4)
        {
        document.getElementById('extra').innerHTML=xmlHttp.responseText;
        }
      }
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
}
</script>
</head>
<body>

<form method="post" action="">
Ticketsubmit<input type="text" name="ticketsubmit" value="ticketsubmit" onBlur="ajaxFunction('test2.php')">
<input type="submit" name="submit" id="submit" value="submit">
<div id='extra'>
<p>heello</p>
</div>
</form>

</body>
</html>

 

the page called asychronously (test2.php):

<?php
echo "<script type='text/javascript'>
         function hello(){
           alert('hello!')
         }
         </script> 
         Another<input type='text' name='another' value='another' onchange='hello()'>";
?>

 

(my original code has the <script> code all in one line but I broke it up here for readability)

 

I CAN however get the alert in this test2.php to work

<?php
   echo " Another<input type='text' name='another' value='another' onchange='alert(\"hello!\")'>";
?>

 

Has anyone been able to make this work and if so, can you see what I'm doing wrong?

 

 

Link to comment
Share on other sites

Do you have FireFox w/ the web developer and firebug extensions?  If not, get it, and install those.  Reload firefox, and run your code, there will be either a green circle with a white check mark in it or red circle with a white X in it.  Click on that, its like a debugger basically for your javascript, see what the error is and post back what it says.  It should show what your PHP responded back with and any javascript errors.  Looking at your code doesn't throw up any red flags to me, so this is your best bet IMO.

Link to comment
Share on other sites

Yeah, I have the web developer tool bar and there are no errors in the javascript.

 

When I save the page to my local machine the javascript runs fine. I think that injecting Javascript into the page via AJAX doesn't 'run' the Javascript code when it is injected. Er....at least thats what it seems like. But again, I swear it was working for me at one point.

Link to comment
Share on other sites

I do something similiar on one of my Ajax pages.  When a user does a product search it returns this to the div tag:

 

$txt .= '<tr style="background-color:'.$this->returnRowColor($x).'">
<td id="'.$row[iD].'">'.$row[iD].'</td>
<td id="'.$row[iD].'">'.$row[name].'</td>
<td id="'.$row[iD].'">'.$row[price].'</td>
<td><acronym title="add" style="color:#003F87; border:1px solid #ccc; cursor:pointer;" onclick=\'addProduct("'.$row[iD].'", "'.preg_replace($badCharArr, "", $row[name]).'", "'.$row[price].'", "1", "1", "'.round($row[cost],2).'");\'>add</acronym></td>
<td><acronym title="description" style="color:#003F87; border:1px solid #ccc; cursor:pointer;" onclick=getDescription("'.$row[iD].'");>info</acronym></td>
</tr>;

 

Now it's still a user event that will actually add that product to the cart by clicking the acronym tag and this calling the addProduct function.

 

Another bit of a code I have allows a user to import a shopping cart.  Here is the code on my front-end page:

/* virtual shopping cart import */
if($_GET[action]=='vsc_import')
{
$vscImportArr = $T_POS->virtualShoppingCartImport($_GET[cart_id]);
$custArr = $vscImportArr[cust]; // contains customer information, used to pop. text fields
$prodArr = $vscImportArr[prod]; // contains javascript functions calls, see bottom of page
}

 

Back-end code:

function virtualShoppingCartImport($cartId)
{
	/* set cart info, customer and shopping cart arrays */
        $infoArr = $this->VscAdmin->get_cart_info($cartId);
        $itemsArr = $this->VscAdmin->get_cart_items($cartId);
        $custArr = $this->importCustomer($infoArr[customer_id]);
        
        /* create an array of javascript function calls of products in the customers virtual shopping cart */
        foreach($itemsArr as $i)
        {
        	$prodArr[] = 'addProduct("'.$i[pid].'", "'.$this->returnProductName($i[pid]).'", "'.$i[sellPrice].'", "'.$i[qty].'", "0");';
        }
        
        /* append the javascript calcTotals function to the end of the array */
        $prodArr[] = 'calcTotals();';
        
        /* return arrays to be broken apart and processed by front-end code */
        $retArr[cust] = $custArr;
        $retArr[prod] = $prodArr;
        return $retArr;
}

 

And at the very bottom of my front end page I have this:

/* echo out javascript function calls for virtual shopping cart import */
if(is_array($prodArr))
{
foreach($prodArr as $prod)
{
	echo $prod;
}
}

 

Now what makes this easy is, this is all done on page load.  Hopefully these examples help.  You probably need to return you're javascript with php and somehow an event will trigger these functions.  Good luck.

Link to comment
Share on other sites

if javascript is returned by ajax, you need to run it through the eval() function, innerHTML'ing it will not work.  If js and html are returned at the same time, they must be separated and the js run through the eval().  As well only the js statements themselves can be eval'ed, you must not eval the script tag itself:

 

<script>
eval("<script>alert('hello');</script>"); //wrong
eval("alert('hello');"); //works!

var myscript = xmlHttp.responseText;
myscript = **some regular expression functions to remove the <script> </script> tags if neccessary
eval(myscript); //executes the code!
</script>

--if the ajax returned javascript has document.write statements in it, you have more problems, otherwise just follow the above

 

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.