phpjavascriptajaxjson

Get value from remote php server in javascript


I have two sites, site A is just html and javascript, and site B has php. What I need is to get variables from site B in site A.

EX:

site A is like

<html>
<head>
  <script>
  //this script has to get the values from siteB
  </script>
</head>
<body>
  <div><!-- here i will do something with the data of site B --></div>
</body>
</html>

Site b is like:

<?php
  var1= "something";
  var2= "somethingElse";
?>

I was thinking to use JSON or Ajax but i do not understand exactly how.


Solution

  • $(document).ready(function() {
      $.ajax({
       type: "GET",
       url: "filename.html",
       dataType: "json",
       success: function(data) {
            // data will contain var1 and var2
       },
       error: function(data) {
            alert("Problem - perhaps malformed JSON?");
       }
      });
    });
    

    and change your PHP file to be something like:

    {
       "var1" : "something",
       "var2" : "somethingElse"
    }
    

    Confirmed to work. Make sure that your file is a well-formed JSON, otherwise "success" won't be fire.

    Note - I am implying usage of JQuery here. Your HTML file should include:

    <script type="txt/javascript" src="jquery-1.8b1.js"></script>