Jonathan
Jonathan

Reputation: 2983

Run entire PHP-file from Javascript with AJAX

on $(document).ready(function() in index.php, the below AJAX is executed, running the file getData.php:

if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById("dataSuccess").innerHTML=xmlhttp.responseText;
        } 
      }
    xmlhttp.open("GET","getData.php",true);
    xmlhttp.send();

In the getData.php file, data is gathered from MySQL and put in JS-arrays:

  var guestData = new Array("<? for ($j=0;$j< sizeof($guestData);$j++) { print     ($guestData[$j]); ?>","<?php } $j = $j+1; ?>");

And finally, store the data in my js arrays into LocalStorage:

   var guestDataCols = new Array();
    guestDataCols = guestData[0].split(",")


        var arrayIndex=0;
        for(arrayIndex=0;arrayIndex<guestData.length-1;arrayIndex++)
        {
            localStorage.setItem(arrayIndex, guestData[arrayIndex]); // storing
        }

EVERYTHING works! But the problem is that my AJAX code doesn't seem to run through the entire getData.php file since LocalStorage in yet empty after the php-file is executed via AJAX. However (and this is a big one), if I simply refresh getData.php in another window, data is stored perfectly and evernything works. I've also tried using jQuery for this as suggested in another Stack Overflow question

  $('#dataSuccess').load('getData.php'); //instead for the AJAX code 

but with the exact same and somewhat mediocre result. So my questions is, why isn't the AJAX script running the entire php file and HENCE, why is no data stored in LocalStorage?

Upvotes: 0

Views: 555

Answers (2)

Sean Hogan
Sean Hogan

Reputation: 2920

I think you're looking for jQuery.getScript

Upvotes: 0

Peritia
Peritia

Reputation: 103

JavaScript on an HTML page is not run when called by an XMLHttp request. The browser doesn't parse the pages that JavaScript receives over XMLHttp requests and therefore does not run the JavaScript. You would have to output to the browser for it to be run. Your best bet would be do have the PHP return the data you need and then extract it from the XMLHttp request. For example, the getData.php could return a JSON string containing the data you need. Then on the page with the XMLHttp request, you could parse that JSON string and save it to the localStorage on that page.

Upvotes: 2

Related Questions