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.

    评论

报告相同问题?

悬赏问题

  • ¥15 一道python难题
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度