简体   繁体   中英

Call a PHP file with AJAX in Magento

Seems like I can't make Ajax to call the PHP file and I can't figure out what or where the problem is. I`m trying to make a module that reads from database and it should display a form with options to select. The form gets populated but when I'm changing an option, it won't display the message.

Basically, it's a module that will list some stores available in database (id, name and email) and when a store is selected, the email should print out. I'm using this as example: http://www.w3schools.com/PHP/php_ajax_database.asp

Here is what I did until now:

in app\\code\\local\\AdiGh\\askStore\\etc\\config.xml

    <frontend>
    <routers>
        <askstore>
            <use>standard</use>
            <args>
                <module>AdiGh_askStore</module>
                <frontName>estores</frontName>
            </args>
        </askstore>
    </routers>
    <layout>
        <updates>
            <askstore>
                <file>estores.xml</file>
            </askstore>
        </updates>
    </layout>
</frontend>

in app\\code\\local\\AdiGh\\askStore\\controllers\\IndexController.php and AjaxController (a file with same code just _AjaxController becomes _IndexController

    class AdiGh_askStore_AjaxController extends Mage_Core_Controller_Front_Action
{
    public function indexAction()
    {
        $this->loadLayout();
        $this->renderLayout();
    }
}

in c:\\Users\\Adi\\Desktop\\askStore\\app\\design\\frontend\\default\\default\\layout\\estores.xml

<layout version="0.1.0">
<default>
    <reference name="content">
    </reference>
</default>
<askstore_index_index>
    <reference name="content">
        <block type="askstore/askstore" name="askstore" template="estores/estores.phtml" />
    </reference>
</askstore_index_index>
<askstore_ajax_index>
    <reference>
        <block type="askstore/askstore" name="root" template="estores/estores.phtml" output="toHtml">
    </block>
    </reference>
</askstore_ajax_index>

and the estores.phtml found in app\\design\\frontend\\default\\default\\template\\ has this:

    <?php
$theIds = $this->getId();
?>
<?php echo get_class($this)."<br />"; ?>
<script type="text/javascript">
    function showEmail(str)
    {
        if (str=="")
        {
            document.getElementById("response").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("response").innerHTML=xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET","ajax/index/store/q="+str,true);
        xmlhttp.send();
    }
</script>
<form name='myForm'>
    Choose Store:
    <select name="store" id="store" onChange="showEmail(this.value);">
        <option value="">Please select a store</option>
        <?php foreach ($theIds as $i => $theId) : ?>
            <?php
                $theNames = $this->getName();
                $theName = $theNames[$i];
            ?>
        <option value="<?php echo $theId; ?>"><?php echo $theName; ?></option>
        <?php endforeach; ?>
    </select>
</form>
<?php echo $this->theResponse() ?>
<?php

?>

Email: <div id="response"></div>

The AskStore.php block that is under app\\code\\local\\AdiGh\\askStore\\Block\\

class AdiGh_askStore_Block_AskStore extends Mage_Core_Block_Template

{

public function getId()
{
    $iduri='';
    $collection = Mage::getModel('adigh_askstore/estores')->getCollection()->setOrder('id','asc');
    foreach($collection as $data)
    {
        $iduri .= $data->getData('id') .',';
    }
    Mage::getSingleton('adminhtml/session')->addSuccess('Cool Ca marche !!');
    return explode(',' , $iduri );
 }

public function getName()
{
    $name='';
    $collection = Mage::getModel('adigh_askstore/estores')->getCollection()->setOrder('id','asc');
    foreach($collection as $data)
    {
        $name .= $data->getData('name') .',';
    }
    Mage::getSingleton('adminhtml/session')->addSuccess('Cool Ca marche !!');
    return explode(',' , $name );
}

public function getEmail()
{
    $email='';
    $collection = Mage::getModel('adigh_askstore/estores')->getCollection()->setOrder('id','asc');
    foreach($collection as $data)
    {
        $email .= $data->getData('email') .',';
    }
    Mage::getSingleton('adminhtml/session')->addSuccess('Cool Ca marche !!');
    return explode(',' , $email );
}

public function theResponse() {

    $q = intval($_GET['q']);



    if($q==0)
    {
        echo "store is 0";
    }
    elseif ($q>0){
        $read = Mage::getSingleton( 'core/resource' )->getConnection( 'core_read' ); // To read from the database
        $productTable = Mage::getSingleton( 'core/resource' )->getTableName( 'adigh_askstore/estores' );

        $query = "SELECT * FROM " . $productTable . "WHERE id = '".$q."'";

        $result = $read->query($query);
        while ( $row = $result->fetch() ) {
            echo 'ID: ' . $row['id'] . '<br>';
            echo 'ID: ' . $row['name'] . '<br>';
            echo 'ID: ' . $row['email'] . '<br>';
    }


    }

    print_r($result);




}

}

So, as I said, it connects to the database and populates the select form with the right options and values. But when I access it under localhost/estores/index it will display the right form but onChange will reload the page without displaying the result. I will be more than grateful to read some constructive opinions.

Thanks a lot!

Check your URL in the AJAX Request

xmlhttp.open("GET","ajax/index/store/q="+str,true);

Seems you are trying to connected to localhost/estores/ajax/index/store rather than just localhost/estores/index/

Try removing the store segment.

Where is the storeAction you send the Get Request on? I mean : ajax/index/store/

Where is the code for that function, seems so that this Request results in an empty string or error, when you say you dont see any changes..

Another thing is, try out:

1) to send a POST request to your action (ajax/index/store/) 2) process the data there 3) send back the result whith more Magento conform code, like:

$this->getResponse()->setBody(Mage::helper('core')->jsonEncode('YOUR DATA'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM