duang5049 2015-07-23 22:11
浏览 44

jQuery $ .post问题(不向PHP发送变量)

I came across a little problem and struggling to solve it... Was wondering if you had any ideas... I have read A LOT of stackoverflow posts about the same issues, but still can't solve mine. I am workin in CodeIgniter.

I am trying to send the variable to PHP controller form the view using jQuery ($.post). Here is mine js code, that is embedded into the view:

$('#testbtn').on('click', function() {
        var orderValue = this.value;
        $.post('http://localhost/codeigniter/welcome/index', {val: 'myValue'}, function(data) {
            alert(data);
        });
    });

Here is the PHP code in the controller:

$a = isset($_POST['val']) ? $_POST['val'] : 'Not set yet.';
echo $a ;

Here is the button: <button id="testbtn" value="thevalue">button</button>

The button is clicked, I get the alert message with the variable and the html code of the whole page, but PHP echo doesn't change, still says: "Not set yet.".

Basically it seems to be very easy, but I can't still find the error...

  • 写回答

1条回答 默认 最新

  • douceng7070 2015-07-23 23:25
    关注

    Without diving into the code more, this would work.

    HTML:

    <button id="testbtn" value="thevalue">button</button>
    

    Javascript:

    $('#testbtn').on('click', function() {
            var orderValue = {"orderValue": $(this).val()};
            $.ajax({
            url: 'http://localhost/codeigniter/welcome/index',
            method: 'POST',
            data: orderValue,
            success: function(data) { alert(data); }
        });
    

    PHP:

    public function index() {
        $a = isset($_POST['orderValue']) ? $_POST['orderValue'] : 'Not set yet.';
        return a;
    }
    

    As stated in other comments though, this may not be the best practice.

    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?