Creative Solution
Creative Solution

Reputation: 89

Php data to jQuery variables

Please see the

<?php
if($_POST['submit'])
{
$beg=$_POST['basic'];
}

if($_POST['inter'])
{
$int=$_POST['int'];
}

if($_POST['advance'])
{
$adv=$_POST['adv'];
}
?>

function refreshPrices() {

   var beg=<?php echo $beg; ?>;
   var inte=<?php echo $int; ?>;
   var advn=<?php echo $adv; ?>;


    var currentTotalValue = 0;
    currentTotalValue = currentTotalValue + parseInt(beg) + parseInt(inte) + parseInt(advn);
    $("#results div").each(function() {
        if (!isNaN(parseInt($(this).find("span").text().substring(1)))) {
            currentTotalValue += parseInt($(this).find("span").text().substring(1));
        }
    });


    $("#totalValue").text("$" + currentTotalValue)
}

If I add one variable from php and add them to current total in jQuery function, it is working fine, but if I add 3 variables and them to jQuery total it is not working. In my html I have 3 buttons with different hidden values just to post them to second page what ever the value it will be added to jQuery total.

Upvotes: 0

Views: 99

Answers (2)

EnrageDev
EnrageDev

Reputation: 91

just use

json_encode(array($val,$val2,$val3))

and print it to your js-file into a new array.

Upvotes: 2

Leri
Leri

Reputation: 12525

The reason why it does not work is simple. You create invalid javascript.

Let's say $int = null; in that case echo $int; will print nothing and var inte = ; is not valid, so it "won't work". And as long $int and other variables are user input the results can be worse. So first of all validate your input and also have default values so that in content you had valid javascript.

var beg=<?php echo (is_string($beg)) ? $beg : defaultValue; ?>;

Upvotes: 1

Related Questions