Calling a remote PHP Script from JavaScript using JQuery

In this tutorial I will show you how to call a remote PHP script (a script that lives on a separate server) from your JavaScript using JQuery.


Why would you want to do this? There are many reasons for calling remote scripts and functions, for example:

  • You want a clear separation between the front end and back end of your app
  • You want to create a RESTful API that allows third party users to access information on your site
  • You want to connect a mobile app to your Web back end


The following video will explain how to go about calling a remote PHP script. The code in the video is given below.


The JavaScript code follows:

        <script language="javascript" type="text/javascript" src="jquery.js"></script>
        <h1>JSON and PHP Example</h1>
        <h3>Output: </h3>
        <div id="output">This text will be replaced with information from the data.php script after an JSON call to the script</div>
            $(function ()
                      url: 'http://localhost:8888/AJAX-PHP/data.php',
                      data: "name=bob",
                      dataType: 'json',
                      success: function(data)
                      } ,
                      error: function()


The code for the remote PHP script is as follows. As you can see, it’s quite simple!

header("Access-Control-Allow-Origin: *");
$id = "1234";
$name = $_GET['name'];
$dataArray[0] = $id;
$dataArray[1] = $name;
echo json_encode($dataArray);
Share This Post
Have your say!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>