简体   繁体   English

如何使用ajax将javascript变量传递给php

[英]how to pass javascript variable to php with ajax

I want to pass javascript variable to php file. 我想将javascript变量传递给php文件。 Here I attached my code 在这里我附上了我的代码

function Calculate(val)
    {

        var h = document.getElementById('xyz').textContent ;
        var result = h * val;
        result = result.toFixed(2);
        document.getElementById('lblRes').innerHTML ='$'+ result;
        $('#ori_price').hide();

        $.ajax ({
            url: 'nonmembersdetail1.php',
            type : 'POST',
            data : {val : h},
            success: function( result ) {
                alert( result );
            }
        });
   }

<?php
echo "<td ><label id='xyz' name='xyz'>".  $row->nonmember_price  ."</label></td>";
echo "<td ><input type='text' style='width:40px' id='words' name='qty' value='1' onchange='Calculate(this.value);'  /></td>";
?>

In my nonmembersdetail1.php code 在我的nonmembersdetail1.php代码中

echo ( $_POST['val'] );

I didn't get value in php file. 我没有在php文件中获得价值。 Please anyone help me.Thanks in advance... 请任何人帮助我。谢谢!

Check in you browser console, if the AJAX call is actually getting fired or you are getting any error before that. 在浏览器控制台中签入,是否实际上已触发AJAX调用,或者在此之前您遇到任何错误。 Because there is no error in the AJAX call and you should get the val value in POST array of PHP. 因为AJAX调用中没有错误,所以您应该在PHP的POST数组中获取val值。

Have you considered, that you are using the variable result twice? 您是否考虑过两次使用变量result One in your code before you fire the ajax-call and once inside the ajax-calls response. 在您触发ajax调用之前,在您的代码中添加一个,在ajax-calls响应内部添加一个。 Change the name of the variable and tell us how that worked. 更改变量的名称,并告诉我们它是如何工作的。

function Calculate(val)
{

    var h = document.getElementById('xyz').textContent ;
    var amount = h * val;
    amount = amount.toFixed(2);
    document.getElementById('lblRes').innerHTML ='$'+ amount ;
    $('#ori_price').hide();

    $.ajax ({
        url: 'nonmembersdetail1.php',
        type : 'POST',
        data : {val : h},
        success: function( result ) {
            alert( result );
        }
    });
} 

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

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