call php script from javascript and get php script's output back in javascript

Posted on 2007-10-02
Last Modified: 2008-01-09
I am not an experienced java script php developer. I was doing my programming assignment( a google map mashup)  and now i m stuck at this.
Question is : "How can i call a php script from javascript passing a javascript variable as argument and then get back the ouput produced by the php script in a javascript variable?"

Note that I do not want any user activity in performing this except loading of the javascript/html page itself. after loading javascript/html page it should automatically call the php script in the background and put result in the required variable. I do not want to click on a link after opening the javascript page  and then start the whole process of calling php script.

Hope this helps, Please try to be fast .......i m already too late.
Eagerly waiting for ur help
Thanks in advance for ur time and response.
Question by:namo21
    LVL 24

    Expert Comment

    This is, by definition, AJAX (Asyncronous Javascript and XML). You will submit a background request, via Javascript, to the remote server. The remote server will process your request via PHP, and return the results in XML (or other format of your choice).

    Unfortunately, AJAX is sufficiently complex that I will not post an example here since I do not know your specific requirements. You can find a number of good tutorials via your favorite search engine.

    Author Comment

    Let me clear you the problem.

    The php script( say "geturl.php" )  is on the same server/host as javascript/html page. Moreover geturl.php is a simple php script which  takes a url and downoad its content parse it to get required string and then output it through echo.

    Now I want to  call this geturl.php from javascript passing url as argument and want to get its output back in some javascript variable.

    should i post the code??
    LVL 48

    Expert Comment

    Use an php-AJXA-Framework like

    include './xajax/xajax_core/';

    $xajax = new xajax();

    $rqstAdd =& $xajax->register(XAJAX_FUNCTION, 'calc');


    function calc($a)
        $response = new xajaxResponse();
        $response->script('myvar=' . ($a+5));
        return $response;
    LVL 24

    Accepted Solution

    Here is a good place to start:

    Basically you will create an XMLHttpRequest or XML ActiveXObject (for Firefox/Safari/Opera and MS IE, respectively) which will open a communication channel to your server. You provide the URL of the script you wish to execute as a parameter of the request/object.

    Data will be returned when the PHP script completes it execution, and you will need to parse and display it as needed via your Javascript code.

    A few more tutorials and examples:

    Author Comment

    HI glcummins,

    thanx for ur help. That proved sufficient.
    But I have this another problem while using the code from the tutorials.
    plaese observe the code

    ---------------------------javascript code------------------------
    <script type="text/javascript">

    function setLatLong()
            if(output ==null)
            {alert("warning: place is :"+output); }
                    alert("sending request for: "+output);

    function setLatLongCallback(response)
                    if (!response || response.Status.code != 200)
                            alert("Sorry, Google was unable to find that place:"+ output);
                    } else
                            var feed = new google.feeds.Feed("");
                                    if (!result.error)
                                            for (var i = 0; i < result.feed.entries.length; i++)
                                                    var entry = result.feed.entries[i];
                                                    var attributes = ["title", "link", "publishedDate", "contentSnippet"];
                                                    for (var j = 0; j < attributes.length; j++)
                                                    {                                                      map.addOverlay(addNewsItem(output,response.Placemark[0].Point.coordinates[0],response.Placemark[0].Point.coordinates[1],entry["link"],entry["title"],entry["contentSnippet"],entry["publishedDate"]));


    function ajaxFunction()
            var ajaxRequest;
                    // Opera 8.0+, Firefox, Safari
                    ajaxRequest = new XMLHttpRequest();
                } catch (e){
                    // Internet Explorer Browsers
                                    ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
                            } catch (e) {
                                            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                                    } catch (e){
                                            // Something went wrong
                                            alert("Your browser broke!");
                                            return false;

            // Create a function that will receive data sent from the server
            ajaxRequest.onreadystatechange = function(){
                    if(ajaxRequest.readyState == 4){
                            output  = ajaxRequest.responseText;         <----------- stroring returned value
                            alert("Value returned is:"+output);                    
  "GET", "", true);


        ajaxFunction();                                                        <----------calling ajaxFunction here
        alert("value of output after ajaxfuncton: "+output);              <--------- printing value of var "output"
        setLatLong();                                                           <-------------- this function will use output value

    -----------------------------Code Ends-------------------------------------------------------------------------
     this code works fine in explorer. but firefox has some problem.

    The problem is that when i call "ajaxFunction" it seems the execution of main program(this script) does not halt or wait until ajaxFunction is returned and it continues with function "setLatLaong". so when i print the value of variable "output" it gives me "undefined". This is not the case with explorer 7.0.

    Any suggestions why is this going this way????

    Author Comment

    sorry ......little more
    When I run this in firefox first I will output --->

    Value of after ajaxfunction : undefined
    Warning: place is :undefined

    then i get this line:
    Value returned is: Patna                     <---------------this is the value correclty returned from the php script

    thats is setLatLong function starts before ajaxFunction is returned.

    Author Comment

    by:namo21 does not even work correcly in explorer........I mean execution order is arbit......sometime it does work .........other times it doesnt.
    can i control the excution usig control statements i.e. wait while "output" variable is undefined and then excute setLatLong.

    Author Comment

    Got it ............i need to request data from php script synchronously rather than asynchronously.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Do You Know the 4 Main Threat Actor Types?

    Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

    In Part 1 ( we covered the hexagonal maze basics -- how the cells are represented in a JavaScript array and how the maze is displayed.  In this part, we'…
    This article will give core knowledge of JavaScript and will head in to your first JavaScript program. I am Durvesh Naik and I am here to deal with this series of JavaScript. I will teach you JavaScript in part wise , as its quite boring to read big…
    The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
    The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

    737 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    21 Experts available now in Live!

    Get 1:1 Help Now