简体   繁体   English

在Magento中使用AJAX调用PHP文件

[英]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. 似乎我无法让Ajax调用PHP文件,也无法弄清楚问题出在哪里或出在哪里。 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 我以这个为例: 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 在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 在app \\ code \\ local \\ AdiGh \\ askStore \\ controllers \\ IndexController.php和AjaxController中(具有相同代码的文件,只是_AjaxController成为_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 在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: 在app \\ design \\ frontend \\ default \\ default \\ template \\中找到的estores.phtml具有以下内容:

    <?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\\ 在app \\ code \\ local \\ AdiGh \\ askStore \\ Block \\下的AskStore.php块

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() { 公共函数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. 但是,当我在localhost / estores / index下访问它时,它将显示正确的形式,但是onChange将重新加载页面而不显示结果。 I will be more than grateful to read some constructive opinions. 我将不胜感激阅读一些建设性意见。

Thanks a lot! 非常感谢!

Check your URL in the AJAX Request 在AJAX请求中检查您的URL

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/ 似乎您正在尝试连接到localhost/estores/ajax/index/store而不是仅连接到localhost/estores/index/

Try removing the store segment. 尝试删除商店细分。

Where is the storeAction you send the Get Request on? 您将“获取请求”发送到的storeAction在哪里? I mean : ajax/index/store/ 我的意思是: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: 1)向您的操作(ajax / index / store /)发送POST请求2)在其中处理数据3)将结果发送回更多Magento符合代码,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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