Creaven
Creaven

Reputation: 319

Putting PHP variable into jQuery function

When my page opens I call a PHP file and output a form in the form of an echo.

A simplified example below:

    echo "<table id='results'>";
    echo "<form method = 'post'><input id='".$row['batchname']."'><button class='btn1'>Query this record</button></form>";
</table>

There will be many versions of the above form as table rows are pulled from the database.

I am usin AJAX to handle the output:

$(document).ready(function(){
    $(".btn1").click(function(e){
        e.preventDefault();
        var bname = ("#<?php echo $row['batchname'];?>").val();
        $post(
            "somephp.php",
            {name : bname},
            function(response, status){
                $("#results").replaceWith(response);
            }
        );
    });
});

When I input an non PHP ID into the jQuery the AJAX work but I always post the first returned row for every form produced as the ids output in the PHP are the same. Can I echo PHP variable into jQuery like this? Is there a better way of getting dynamic ID's into jQuery.

Upvotes: 0

Views: 330

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324810

Rather than hacking about like this, do it properly.

$(".btn1").click(function(e) {
    e.preventDefault();
    var form = $(this).parents("form");
    var value = form.find("input")[0].value; // or something else here
});

Upvotes: 1

Related Questions