Ryan D Ryan D - 1 year ago 83
jQuery Question

post unique value using jquery replaceWith out of php while loop

I am trying to post a stock number to an external php file and return the image using ajax replaceWith but it only returns the same image everytime..

Here is my Index.php -

<?php include('inv_data.php');?>

<div id="invCont">
<div id="invTitle">Inventory</div>
<div id="invData"><?php echo $invData;?></div>

<div id="detailData"></div>

$("form").submit(function(e) {
var url = "invDetail.php";
type: "POST",
url: url,
data: $("form").serialize(),
success: function(data)

Here is the inv_data.php with the form -

$sql = "SELECT * FROM table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {

$stock = $row['stock'];

$invData .= '<form id="invForm" method="post">';
$invData .= '<input type="hidden" value="'.$stock.'" name="stock">';
$invData .= '<input type="submit" value="'.$stock.'" name="getDetail" id="iStock">';
$invData .= '</form>';


And finally my invDetail.php -

$stock = $_POST['stock'];

$sql = "SELECT * FROM table WHERE stock = $stock";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {

$image = $row['imagelist'];
echo '<div id="detailData"><img src="'.$image.'" id="image"/></div>';

It all works fine except when it post the data from the ajax call it gives me the same value everytime no matter which stock number is clicked, how do I do it where it gives the the image of the stock number clicked?

Answer Source

The issue may be caused by data: $("form").serialize().

Every time the form is submitted, it is grabbing the data from every form on the page, not just the current one.

Change to data: $(this).serialize()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download