简体   繁体   中英

Passing php variable to javascript function

I have a php loop that generates several buttons.Each button changes the content of a specific div and update some stuff in the database by using an ajax request.When the button is click it calls a function that executes the ajax request.The problem is that I am not able to pass the Div id as parameter in the function if I concatenate it with a string. Only when I write $TickCrossDiv = $i it is working (only when using number as Div id it works).

Here is my code :

for($i=0;$i<count($PlanningArray);$i++){

        $TickCrossDiv = 'tickCrossDiv'.$i;

     echo "<button onclick=\"SetActDone(
        ".$PlanningArray[$i]'PlanID'].",
        ".$PlanningArray[$i]['ActID'].",
        ".$TickCrossDiv.")\" >
        Mark as done</button>"
}

Here is the function :

function SetActDone(PlanID,ActID,DivID)
    {
        $.ajax({

            type: "POST",
            url: 'testAjax.php',
            data: {PlanID:PlanID, ActID:ActID},
            success: function(data) {

                $("#" + DivID ).html('<p>Status: Done</p> <i style="color:greenyellow; " class="fa fa-check-circle fa-2x"></i>');
            }
        });
    }

I am getting the error :

Uncaught Error: Syntax error, unrecognized expression: #object HTMLDivElement

Without knowing what the values of $PlanningArray[$i][...] are I can't say for sure. But most likely you need to wrap your echoed variable in quotes. That would explain why a number would work, it will be treated as an integer rather than a string. Try this:

for($i=0;$i<count($PlanningArray);$i++){

    $TickCrossDiv = 'tickCrossDiv'.$i;

     echo "<button onclick=\"SetActDone(
        ".$PlanningArray[$i]['PlanID'].",
        ".$PlanningArray[$i]['ActID'].",
        '".$TickCrossDiv."')\" >
        Mark as done</button>"

}

I'm guessing that $PlanningArray[$i]['PlanID'] and $PlanningArray[$i]['ActID'] are also integers so they don't need to be wrapped in quotes.

I also fixed a typo on this line:

$PlanningArray[$i]'PlanID']

If your code works, that typo probably isn't in your real script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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