[web] how to dynamically call PHP script via javascript?

Started by
8 comments, last by GekkoCube 17 years, 6 months ago
The subject heading is vague, so i will try to explain what im trying to do below. But first, my guess is that what im trying to do can't be done using the technologies that im using. Technologies that im using are standard HTML, &#106avascript, and PHP. Let's say I have X number of images on my webpage. Now using javacript I can setup an event so that when i click on an image the event will be raised. Each of these images has data associated with it that I must retrieve from a MySQL database that is online. What I would like to do is make a SQL query (using PHP) from this &#106avascript event handle. can this be done? if not, what brights ideas/technologies do you guys suggest for this?
Advertisement
i think i discovered the answer: AJAX.
Quote:Original post by GekkoCube
i think i discovered the answer: AJAX.


LOL
Collectively the technologies are often labeled as "AJAX".

This means that it is a web page which asynchronously requests something from the server to carry out an action or obtain some data (or both).

Normally the method of doing it at a low level is using a &#106avascript object called XMLHttpRequest (Or in some versions of MSIE where this is unavailable, an ActiveX object instead which provides the same function).<br><br>Another method occasionally used is to have a small IFRAME element which is reloaded with some parameters to fetch the information (or submits a small hidden form in the case of a POST). This is not normally used for preference as XMLHttpRequest is more convenient.<br><br>Have a look at <a href="ajaxpatterns.com">ajaxpatterns.com</a> for lots of info and examples.<br><br>Mark
The iframe method has some limitations though, which is why using XMLHttpRequest is preferred.

Check out this Beginner's XMLHttpRequest Tutorial that I have written myself.

--------------------------------------Amaze your friends! Astound your family! Kennify your text!
thanks Verminox. Ill be going thru your tutorial soon.

btw, i do realize that AJAX is a culmination of technologies and it itself is not a technology in and of itself. i suspect that's why i got a big laugh out of mathachew.

anyhow, the reason why i need something that is dynamic and asynchronous to do this is because each time i click on an "object", a mysql query is made to the database which then retrieves certain information that is specific to that object.

however, the object's information is utilized by client-side scripts to display...etc. and this needs to be done without refreshing the ENTIRE page.

cheers.

Quote:Original post by GekkoCube
btw, i do realize that AJAX is a culmination of technologies and it itself is not a technology in and of itself. i suspect that's why i got a big laugh out of mathachew.


Think of it as "I'm laughing with you, not at you" :)
okay, im going to need somebody to show me the direction i need to be going with this as what im currently doing doesnt seem to be very practical.

below i will try to explain what im doing via code:

//This is the &#106avascript function that is called when I click on an "object".
//Specifically, this function is called inside the function callback from //Google Map API's GEvent.addListener function.
function getData()
{
// call this in response to clicking on a google map's node point.
requestData('friend.php', '');
}

RequestData is provided below:
function requestData (url, parameters)    {      http_friend_request = false;      if (window.XMLHttpRequest)       { // Mozilla, Safari,...         http_friend_request = new XMLHttpRequest();         if (http_friend_request.overrideMimeType)          {            http_friend_request.overrideMimeType('text/xml');         }      }       else if (window.ActiveXObject)       { // IE         try          {            http_friend_request = new ActiveXObject("Msxml2.XMLHTTP");         }          catch (e)          {            try             {               http_friend_request = new ActiveXObject("Microsoft.XMLHTTP");            } catch (e) {}         }      }      if (!http_friend_request)       {         alert('Cannot create XMLHTTP instance');         return false;      }      http_friend_request.onreadystatechange = alertResults;      http_friend_request.open('GET', url + parameters, true);      http_friend_request.send(null);   }


The alertResults function is provided below:
function alertResults()    {      if (http_friend_request.readyState == 4)       {         if (http_friend_request.status == 200)          {            var xmldoc = http_friend_request.responseXML;            var root = xmldoc.getElementsByTagName('root').item(0);                        for (var iNode = 0; iNode < root.childNodes.length; iNode++)             {               var node = root.childNodes.item(iNode);               for (i = 0; i < node.childNodes.length; i++)                {                  var sibl = node.childNodes.item(i);                  var len = parseInt(sibl.childNodes.length / 2);                  var arr = new Array(len);                  var cnt = 0;                  for (x = 0; x < sibl.childNodes.length; x++)                   {                     var sibl2 = sibl.childNodes.item(x);                     var sibl3;                     if (sibl2.childNodes.length > 0)                      {                        sibl3 = sibl2.childNodes.item(0);                        arr[cnt] = sibl3.data;                           cnt++;                     }                  }                  addResultRow("ftable", arr);               }            }         }          else          {            alert('There was a problem with the request.');         }      }   }


And finally the addResultRow function is provided below:
function addResultRow(tablename, arr)    {        var tbl = document.getElementById(tablename);        var lastRow = tbl.rows.length;        var row = tbl.insertRow(lastRow);                for (r = 0; r < arr.length; r++)           {                var cell = row.insertCell(r);             cell.innerHTML = arr[r];                alert("here");          }   }


Now when I call requestData there can be 2 scenarios:

1) the first parameter's php script is XML formated.
2) the first parameter's php script makes a mysql query and uses it to return an XML formatted file (thus being sent as the first parameter).

It is this 2nd scenario that i'm stuck on. Im not sure of the practical solution. To summarize my problem, the php script is dynamically generated based on a query result. Should i output the query to a file? Or is there a neater solution to this problem? Any help greatly appreciated.
I am not really understanding what you mean by "first parameter" but I am assuming you mean the first argument in your requestData function, i.e, the PHP file.

Firstly, regarding the second argument of that function, namely parameters...

See this line of code:
http_friend_request.open('GET', url + parameters, true);

This means your 2nd argument must start with a question mark all the time, so instead just use:
http_friend_request.open('GET', url + '?' + parameters, true);


Sorry for being picky :p


Anyhow, if you wanted your PHP file to generate random XML based on a query (perhaps because you are requesting information about a database record) then you are doing it just right. Simple query the database and echo on the same page. For example, you can call:

requestData( 'customers.php' , 'fname=John&lname=Smith' );


And your customers.php file can query the DB with this information using the $_GET array and with the results it can echo data in the XML formatted page. A small excerpt would be:

<customer id="<?php echo $result['id']; ?>">   <job><?php echo $result['job']; ?></job>   <coolness><?php echo $result['coolness']; ?></coolness></customer>



Now you can use your responseXML variable to work on that.

--------------------------------------Amaze your friends! Astound your family! Kennify your text!
thanks guys.
i got this whole xmlhttp thing working like a charm!

This topic is closed to new replies.

Advertisement