Vignesh
Vignesh

Reputation: 3601

Calling a PHP file from AJAX

I'm trying to develop a small site using Magento, in which I'm trying to display a dynamic content based on the user selection from the drop down box.

So far I've done a JavaScript and used AJAX for XMLHTTP request for the PHP file, its based on the code provided by w3schools example as follows

function loadLocations(value){
var xmlhttp;
if (value==0)
{
  document.getElementById("locationList").innerHTML="";
  return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
  {
    document.getElementById("locationList").innerHTML=xmlhttp.responseText;

  }
}
xmlhttp.open("GET","getLocations.php?countryID="+value,true);
xmlhttp.send();

}

and the getLocations.php is placed in the path

app/code/local/company/module/Block/

and my doubt is how to point the getLocations.php file in the particular location.

Any help, Thanks All.

Upvotes: 2

Views: 3042

Answers (2)

Nick
Nick

Reputation: 602

1) You must create controller. companyName/yuormodule/controllers/AjaxController.php 2) In AjaxController.php create action, for example indexAction(). See code section

public function indexAction()
{
    $this->loadLayout();
    $this->renderLayout();    
}

3) Then add to yourlayout.xml (example: app/design/frontend/base/default/layout/yourlayout.xml) next code

    <yourmodule_ajax_index>
        <block type="yourmodule/getlocations" name="root" template="path/file.phtml">
        </block>
    </yourmodule_ajax_index>

4) Then you must update layout in your confix.xml.

<layout>
    <updates>
        <yourmodule>
            <file>yourlayout.xml</file>
        </yourmodule>
    </updates>
</layout>

5) After this instance of your getLocation class will be available in file.phtml.

6) And last, just need to change this code xmlhttp.open("GET","getLocations.php?countryID="+value,true); to xmlhttp.open("GET","yourmodule/ajax/index/countryID/"+value,true);

Upvotes: 4

Lucas Moeskops
Lucas Moeskops

Reputation: 5443

You should make a controller class to handle your functionality. So for example: app/code/local/company/module/controllers/AjaxController.php. You can read online about controllers (they are a core part of magento). Then you would call most likely something like http://mywebsite.dom/module/ajax/getlocations/countryID/34/.

As far as I know this would be the best method.

P.S. If you're new to Magento, I would suggest this series to learn a bit: http://www.magentocommerce.com/knowledge-base/entry/magento-for-dev-part-1-introduction-to-magento.

Upvotes: 1

Related Questions