使用Ajax将JS变量传递给PHP的方法?

时间:2017-12-21 08:52:30

标签: javascript php ajax codeigniter

我有一个codeigniter应用程序插入wordpress网站。我需要根据我视图中的html选择的选项值修改php中的短代码。短代码在我的html页面中添加了一个表单。我想我需要使用Ajax将数据从JS移动到PHP。我很困惑如何完成这项工作。这是必须完成的基本序列(减去Ajax或其他需要的方法):

在我的视图中,我需要有以下组件:

<html>
    <select id="select-service">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="mercedes">Mercedes</option>
      <option value="audi">Audi</option>
    </select>

//This is where I am putting the short code I made in JS
<?php echo do_shortcode("shortCode GOES HERE"); ?>

</html>
<script>
    function getService() {
        var serviceItem = $('#select-service option:selected').text();
        shortCode = "[wpi_checkout item='" + serviceItem + "']" ;
        //AN AJAX SEQUENCE HERE?
        var postUrl = GlobalVariables.baseUrl + '/ajax_serviceitem'; 
        $.ajax({
            url: postUrl,
            method: 'post',
            data: shortCode,
            success: function(data) {
                alert(data);
            }
        });
    }
    $(document).ready(getService);
    $('select').on('change', getService);
</script>

在我的控制器中,我想我需要这样的功能:

public function ajax_serviceitem() {
    $shortcode = $_POST('shortCode')
    $this->load->view('myview', $shortcode);
    //I am lost as to what to do next 
}

我是在正确的轨道还是我使这个过于复杂?

3 个答案:

答案 0 :(得分:0)

 override func viewDidLoad()
    {
        super.viewDidLoad()
        collectionView.allowsSelection = true
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
        if cell.isSelected == true
        {
            cell.transform = CGAffineTransform(scaleX: 1.2, y: 2)
        }
        else
        {
            cell.transform = .identity
        }
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
    {
        let cell = collectionView.cellForItem(at: indexPath)
        cell?.isSelected = true
        UIView.animate(withDuration: 0.2, delay: 0, usingSpringWithDamping: 5, initialSpringVelocity: 0, options: [], animations:
        {
            cell?.transform = CGAffineTransform(scaleX: 1.2, y: 2)
        })
    }

========================我看到的另一个修复是================= =

moment.updateLocale(moment.locale(), { invalidDate: "ur msg or NaN/null" });

答案 1 :(得分:0)

您可以针对您的问题尝试此解决方案:

JS:

function getService() {
    var serviceItem = $('#select-service option:selected').val();
    data = {'shortCode':serviceItem};
    //AN AJAX SEQUENCE HERE?
    var postUrl = GlobalVariables.baseUrl + '/ajax_serviceitem'; 
    $.ajax({
        url: postUrl,
        type: "POST",
        dataType: 'json',
        data : data,
        success: function(response) {
            if (response.status == 'success') {
                console.log("Success Request");
                $("#view_selector").html(response.my_view_file);
            } else {
                console.log("Fail Request");
            }
        }
    });
}

PHP:

public function ajax_serviceitem() {
    if ($this->input->is_ajax_request()) {
        $shortcode =  $this->input->post('shortCode');
        if (!empty($shortcode)) {
            $my_view_file = $this->load->view('myview', $shortcode, TRUE);
            $data['status'] = 'success';
            $data['my_view_file'] = $my_view_file;
        } else {
            $data['status'] = 'error';
            $data['my_view_file'] = "";
        }
        echo json_encode($data);
        exit;
    } else {
        redirect('login/logout'); // Logout URL here
    }
}

我希望它会有所帮助。

答案 2 :(得分:0)

这里的问题是虽然php工作在服务器上完成,但传回的变量是在JS中,所以它不起作用。我通过在视图中添加一些php来解决我的问题,从视图中收集选项并从中构建短代码:

//First: In css I hid all the elements that the short code produces


//This select box is built by a foreach routine in my controller.
<html>
    <select id="select-service">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="mercedes">Mercedes</option>
      <option value="audi">Audi</option>
    </select>

//This is where I am putting the short code.  I am grabbing $service['id'] from my database in my controller and sending it to the view. I am building a bunch of divs that reflect the values of the select options here rather than in the controller.  I have to do this because the wordpress do_shortcode() hook will only work in the view.
<?php foreach($available_services as $service) { 
    $shortcode = "[wpi_checkout item='" . $service['id'] "' title ='session_ID' callback_function='ea_paypalcallback']"; ?>
    <div id="<?php echo $service['id'] ?>" class="shortcode"><?php echo do_shortcode($shortcode)?></div>
<?php } ?>  

</html>

然后我在Ajax发送中成功运行以下内容以获取其他内容:

var selServiceId = $('#select-service').val();
$('#' + selServiceId ).find(':submit').click();

这样做了。