user3424093
user3424093

Reputation:

how to pass javascript variable to php with ajax

I want to pass javascript variable to php file. 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

echo ( $_POST['val'] );

I didn't get value in php file. Please anyone help me.Thanks in advance...

Upvotes: 0

Views: 119

Answers (2)

Zim84
Zim84

Reputation: 3497

Have you considered, that you are using the variable result twice? One in your code before you fire the ajax-call and once inside the ajax-calls response. 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 );
        }
    });
} 

Upvotes: 0

Rahul Singh
Rahul Singh

Reputation: 892

Check in you browser console, if the AJAX call is actually getting fired or you are getting any error before that. Because there is no error in the AJAX call and you should get the val value in POST array of PHP.

Upvotes: 1

Related Questions