?
Solved

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

Posted on 2007-10-02
8
Medium Priority
?
818 Views
Last Modified: 2008-01-09
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.
0
Comment
Question by:namo21
  • 5
  • 2
8 Comments
 
LVL 24

Expert Comment

by:glcummins
ID: 20004239
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
 

Author Comment

by:namo21
ID: 20004270
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
 
LVL 48

Expert Comment

by:hernst42
ID: 20004292
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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 24

Accepted Solution

by:
glcummins earned 1200 total points
ID: 20004303
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
 

Author Comment

by:namo21
ID: 20004713
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
 

Author Comment

by:namo21
ID: 20004743
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
 

Author Comment

by:namo21
ID: 20004911
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
 

Author Comment

by:namo21
ID: 20005212
Got it ............i need to request data from php script synchronously rather than asynchronously.
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Suggested Courses
Course of the Month17 days, 3 hours left to enroll

862 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