Search code examples
javascriptphpajaxhybrid-mobile-appintel-xdk

passing data from php to javascript for hybrid apps


i'm building a cross platform mobile application using intel xdk and i need to retrieve data from php running on the server into my javascript...... this is my js code

var meRequest;
meRequest = new XMLHttpRequest();
meRequest.onreadystatechange=function()
{
    if(meRequest.readyState==4)
    {
        alert("request sent");
        alert((meRequest.responseText));
    }
}

meRequest.open("GET", "http://127.0.0.1/my_queries_1.php",true);
meRequest.send();

and this is my php code:

<?php
echo json_encode(500);
exit;
?>

this works when i run them both from localhost, i.e both scripts are on the server but i can't use this since for the app, the js has to be embedded in the mobile application and the php script remaining on the server... but if i run the javascript file outside local host get a null responseText. how do i go about this please??


Solution

  • So you need cross domain request and I think something like this should work for you:

    // (1)
    var XHR = ("onload" in new XMLHttpRequest()) ? XMLHttpRequest : XDomainRequest;
    
    var xhr = new XHR();
    
    // (2) cross domain request
    xhr.open('GET', 'http://anywhere.com/request', true);
    
    xhr.onload = function() {
      alert( this.responseText );
    }
    
    xhr.onerror = function() {
      alert( 'error ' + this.status );
    }
    
    xhr.send();
    

    Server side should also allow such requests via generating special response headers:

    HTTP/1.1 200 OK
    Content-Type:text/html; charset=UTF-8
    Access-Control-Allow-Origin: http://example.com