开发者

How can I Call a Javascript Function After a PHP Script has Written an XML File

I've got a PHP file with a SELECT statement in it that pulls data from a MySQL database. It then processes the data and writes the results to an XML file.

I've got a javascript file that uses the XML file. How do I call a javascript function, for example, doStuff(), after the PHP file has downloaded the data and written the XML file? I could call it after a setTimeout(), but I hope that there is a better way.

The XML file gets over-written each time the PHP script runs. So, the XML file may already exist.

Is there some event that I could have doStuff() fire after? Or a way of determining whether the PHP script has finished?

Any suggestions?

Thank you.


UPDATE:

Here's some more details on what I've got.

I've got a map with a form. When the users submits the form, I use Ajax to process the form. A PHP function is called and data from a MySQL database is selected. The data includes latitude and longitudes. The PHP file then writes an XML file with this data. The javascript file then reads the XML file and places markers on the map.

The PHP and the javascript work fine. The problem is that the javascript file fires immediately, as soon as the map loads. So, the data in the xml file (from a previous form selection) gets turned into markers. If I delete the xml file, then no markers are put on the map. The javascript tried to use the non-existent xml file as soon as it loads. It's not there, so no markers are placed on the map. And this is before the user has made any selections in the form.

I need some way t开发者_开发百科o have the javascript function that loads the XML file do so only after the XML file has been written.

I'm follwing this tutorial . I've had to adapt it in order for it to work in a WordPress plugin.

In my PHP, I've got:

//Creates XML
//each marker has a lat and long
$my_xml ='<?xml version="1.0" ?>';
$my_xml .= '<markers>';

foreach($csf_data as $incident) {
    $my_xml .='<marker lat="'. $incident->latitude.'" lng="'.$incident->longitude.'" type="resto" />'; 
}

$my_xml .= '</markers>';

//Creates the XML file 
//(I've hardcoded markers.xml's path for now-- will change later)
$file_handle = fopen('/Users/myname/Sites/mysite/wp-content/plugins/myplugin/markers.xml', 'w');
fwrite($file_handle, $my_xml);
fclose($file_handle);

In the javascript, I've got:

function downloadUrl(url,callback) {

 var request = window.ActiveXObject ?
     new ActiveXObject('Microsoft.XMLHTTP') :
     new XMLHttpRequest;

 request.onreadystatechange = function() {

   if (request.readyState == 4) {
     request.onreadystatechange = doNothing;
     callback(request, request.status);
   }
 };

 request.open('GET', url, true);
 request.send(null);

}


var customIcons = {
  resto: {
    icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
    shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
  },
  bar: {
    icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
    shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
  }
};


downloadUrl("http://mysite/wp-content/plugins/myplugin/markers.xml", function(data) {
 var xml = data.responseXML;

  var markers = xml.documentElement.getElementsByTagName("marker");

  for (var i = 0; i < markers.length; i++) {
    var type = markers[i].getAttribute("type");
    var point = new google.maps.LatLng(
        parseFloat(markers[i].getAttribute("lat")),
        parseFloat(markers[i].getAttribute("lng")));
   
    var icon = customIcons[type];
    var marker = new google.maps.Marker({
      map: map,
      position: point,
      icon: icon.icon,
      shadow: icon.shadow
    });

 
  }});



function doNothing() {}

This code works, but I need these javascript functions to run only after PHP has written a new XML file. How can I call this javascript after the new XML file has been written?

Thank you.


You can do it easilly, (not all required things like taking action if file cannot be created etc.. are taken care but main functionality is here) like this with these 2 files:

<html>
<head>
<script type="text/javascript">

var sq="'"; 
var dbq="\"";
var request = false;
try { 
  request = new XMLHttpRequest(); 
} catch (trymicrosoft) {                         
  try { 
    request = new ActiveXObject("Msxml2.XMLHTTP"); 
  } catch (othermicrosoft) {
    try {
      request = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (failed) {                  
      request = false;       
    }
  }
}


if (!request) 
  alert("Error initializing XMLHttpRequest!"); 
</script>

<script type="text/javascript">

   function makeFile( ) 
   {    
        var url = "createXml.php";  
        var params = "makeFile=1&limit="+document.getElementById('select').value+"";
        request.open("POST", url, true);  

        //Some http headers must be set along with any POST request.
        request.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
        request.setRequestHeader("Content-length", params.length);
        request.setRequestHeader("Connection", "close");

        request.onreadystatechange = updatePage;
        request.send(params);

   }////////////////////

      //You're looking for a status code of 200 which simply means okay.
   function updatePage() {
     if (request.readyState == 4) {
       if (request.status == 200) 
       {    
            //run the js created by php
            eval(request.responseText);  
            //get tha needed info
            document.getElementById('divResults').innerHTML=response[0]+
            '<input type='+dbq+'submit'+dbq+' value='+dbq+'Get it..'+dbq+
            ' onclick='+dbq+'getXmlFile('+sq+response[1]+sq+')'+dbq+'; >' ; 
       } 
       else{
         //alert("status is " + request.status);
         }
     }
   }//////////////////////////////////////////////////////////////////


   function getXmlFile(fileName) 
   {  
        var url = fileName; 
        var params = null; 
        request.open("POST", url, true);     
        request.setRequestHeader("Connection", "close");    
        request.onreadystatechange = displayFile;
        request.send(params); 
   }////////////////////



      function displayFile() {
     if (request.readyState == 4) {
       if (request.status == 200) 
       {    
            document.getElementById('textareaResults').innerHTML=request.responseText;
            document.getElementById('divResults').innerHTML=
            'File loaded in text area below. '+
            '<font size=1>You could also load these data directly to a js variable using php '+
            'without creating a file...</font>' ;


       } 
       else{
         //alert("status is " + request.status);
         }
     }
   }

</script>
</head>
<body >


How many records from Mysql to put into XML file? <br>
<font size=2>(This is just for testing...)</font> <br> <br>
<select id="select">
  <option value="10">10</option>
  <option value="20">20</option>
  <option value="30">30</option>
  <option value="40">40</option>
</select> <span style="background-color:red;color:yellow;border: 5px solid gray;"  
onClick="makeFile( )"/> Click To Go.. </span>

<br> <br>
<div    id="divResults">Thank you!</div>


<textarea rows="10" cols="88"  id="textareaResults">
</textarea>



</pre>
</body>
</html>

and the other one

<?PHP 
/**
Mysql
*/
mysql_connect('localhost', 'root',''); 
mysql_select_db("mysql"); 
$query="select * from help_category limit ".$_POST['limit'].";";  
$resultID = mysql_query($query ) or die("Data not found."); 

$xml_output = "<?xml version=\"1.0\"?>\n"; 
$xml_output .= "<records>\n"; 

for($x = 0 ; $x < mysql_num_rows($resultID) ; $x++){ 
    $row = mysql_fetch_assoc($resultID); 
    $xml_output .= "\t<record>\n"; 
    $xml_output .= "\t\t<help_category_id>" . $row['help_category_id'] . "</help_category_id>\n";  
    $xml_output .= "\t\t<name>" . $row['name'] . "</name>\n";  
    $xml_output .= "\t\t<parent_category_id>" . $row['parent_category_id'] . "</parent_category_id>\n"; 
    $xml_output .= "\t</record>\n"; 
} 

$xml_output .= "</records>"; 

/**If an xml file wanted or not
*/
if($_POST['makeFile']==1)
{
    $dbq="\"";
    //same queries will make the same file name
    $fileName=md5($query).'.xml';
    //check if the file exists
    if(!file_exists($fileName))
    {
        //create a new file for writing
        $fp = fopen($fileName, 'w');
        fwrite($fp,  $xml_output); 
        fclose($fp);
        echo "var response = new Array( ); response[0]=".$dbq.'A new file created..'.$dbq.";  
        response[1]=".$dbq.$fileName.$dbq.";   ";
    }
    else
    {   
        echo "var response = new Array( ); response[0]=".$dbq.'File exists and waiting..'.$dbq.";  
        response[1]=".$dbq.$fileName.$dbq.";   ";
    }
}
/**If results are required directly to the page send them
*/
else
    echo 
        $xml_output;

?> 

NOTICE The aim of this script is to show in a fast way how can be done these things this guy asks. Down voting this answear (as has happened before -and not only to me-) for sql injections die function etc is in my opinion totally unproductive (security is not what the question asks!), the asker must be able to separate what code is for answearing his question and what is to help the answear get ready to run and test. For example the simple mysql with dies will make it easy to run the answear immediately. Sorry for this but unfortunately we have to make clear some very basic foundamentals some times!


Okay, I used echo to call the javascript function in PHP right after fclose($file_handle); . This way the javascript function is called only after the new XML file has been written. Thank you.


I think you are seeing a small piece of the picture. Echoing the js function after fclose and beliving this is the very fact that makes things happen is a bit incomplete and misleading (will say below what is the big pics).

First of all there is no reason at all to echo js from a php you call, you don't want your code being spread like this, not at all! I too do echo some js after fclose but it is strictly related to sending data as an array instead of text, only this, nothing more. No logic, no conditions, no real real code after all!

The big pics is mainly seen in lines of this kind:

request.onreadystatechange = updatePage;

This line says that whenever the php script we called is ready then call the updatePage() function.

My point is that you should leave the php script out of your client side execution flow, don't put js there, all your functions, logic, conditions and the client side work flow should go in the client side code.

Practiaclly the function that you want to take on after php put it in your client side code in that specific place that will make sure your function is executed after php is ready, that place is here:

   function updatePage() {
     if (request.readyState == 4) {
       if (request.status == 200) 
       {//place me here 

or inside any other function of this kind that is called after the request is ready.

Without this functionality that makes possible to get php result (whenever ready) back to client it doesn't matter if you echo the js function after fclose or anywhere else, you would have no chance to see anything at all. That's why I say you see the small pic.

That's it all, what else.. you can let php inform you if file created successfully or not, you can get the xml directly to page without creating a file etc... hope you can do your job now (study the example... you will benefit a lot).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜