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

Hi
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.
namo21Asked:
Who is Participating?
 
glcumminsCommented:
Here is a good place to start: http://www.tizag.com/ajaxTutorial/ajaxphp.php

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:

http://www.sunflowerroad.com/blog/timstidbits/ajax-tutorial/
http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=10
http://www.modernmethod.com/sajax/
0
 
glcumminsCommented:
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.
0
 
namo21Author Commented:
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??
 
0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
hernst42Commented:
Use an php-AJXA-Framework like http://www.xajaxproject.org

<?php
include './xajax/xajax_core/xajax.inc.php';

$xajax = new xajax();

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

$xajax->processRequest();

function calc($a)
{
    $response = new xajaxResponse();
    $response->script('myvar=' . ($a+5));
    return $response;
}
0
 
namo21Author Commented:
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); }
        else{
                alert("sending request for: "+output);
                geocoder.getLocations(output,setLatLongCallback);
        }
}

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("http://newsrss.bbc.co.uk/rss/newsonline_world_edition/front_page/rss.xml");
                        feed.setNumEntries(3);
                        feed.load(function(result)
                        {
                                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;
        try{
                // Opera 8.0+, Firefox, Safari
                ajaxRequest = new XMLHttpRequest();
            } catch (e){
                // Internet Explorer Browsers
                        try{
                                ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
                        } catch (e) {
                                try{
                                        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);                    
                }
        }
        ajaxRequest.open("GET", "http://www.cse.iitd.ac.in/~cs5030206/getHTlocation.php", true);
        ajaxRequest.send(null);

}






    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????
0
 
namo21Author Commented:
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.
0
 
namo21Author Commented:
crap..........it 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.
0
 
namo21Author Commented:
Got it ............i need to request data from php script synchronously rather than asynchronously.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.