Rodrigo
Rodrigo

Reputation: 5119

call javascript function from AJAX php file isn't working

SOLVED! I used only javascript to the task. Now it reads the text from the php and use the coordinates.

        var texto = HttpReq.responseText;
        var lats,lons;
        var pos = texto.search(' ');
        lats = texto.substring(0,pos-1);
        lons = texto.substring(pos+1);

Thank you all! You are wonderful!


My site has a main page, where after the user selects a city, I wanna show it on a google map. The coordinates of the cities are in a table, so I'm using php in a separate .php file, accessed through AJAX. In the separate .php, I want to call a JS function from the main page to add the point to the map (the JS map object was on the main page, I also tried to put all the JS in a .js file, but the function still isn't called at all (I'm using FireBug to breakpoint it, but the function is never called).

The result from AJAX's GET is this:

Latitude: -21.15361<BR>Longitude: -41.567501<BR><script src="functions.js" type="text/javascript">addPoint(-21.15361,-41.567501);</script>

The Latitude and Longitude appears on screen, but the method addPoint ain't called. Am I missing something stupid here? Thanks in advance.

-- EDIT -- OK, here's what I'm trying to do (that's inside getcoords.php, the file called thru ajax):

$stmt = $dbh->prepare("select id_mun,lat,lon from municipio where id_mun = '".$_GET['mun']."'");
if ($stmt->execute()) {
    echo '<script src="functions.js" type="text/javascript"></script>';
    while ($row = $stmt->fetch(PDO::FETCH_BOTH)) {
        echo "Latitude: $row[1]<BR>";
        echo "Longitude: $row[2]<BR>";
        echo '<script type="text/javascript">';
        echo 'alert("testando");';
        echo "addPoint($row[1],$row[2]);";
        echo "</script>";
    }
}

and the result that goes to the innerHtml from my div (and is not executed):

<script src="functions.js" type="text/javascript"></script>Latitude: -15.779722<BR>Longitude: -47.929722<BR><script type="text/javascript">alert("testando");addPoint(-15.779722,-47.929722);</script>

Thanks again.

Upvotes: 0

Views: 888

Answers (2)

Milan Babuškov
Milan Babuškov

Reputation: 61098

Stuff in <script> is only executed while page is loading. You need to call the code from within your AJAX response handler, not just inject it into the page.

Upvotes: 0

The Maniac
The Maniac

Reputation: 2626

Any code inside <script></script> will not be executed if the src attribute is present. You'll need two script blocks instead of one:

<script src="functions.js" type="text/javascript"></script><script type="text/javascript">addPoint(-21.15361,-41.567501);</script>

Hope that helps!

Upvotes: 1

Related Questions