0

I have come to an understanding that the problem is that I am trying to pass a string array to a JavaScript.

I do not know how to proceed.

FORM

<input type="hidden" name="id">
<input type="hidden" name="adProd">

DB Connection

$stmt = $conn->prepare("SELECT product_name, product_quantity, product_id FROM product ");
$stmt->execute();

// set the resulting array to associative
$result = $stmt->fetchAll(PDO::FETCH_OBJ);

foreach ($result as $v) {
  echo "<td style='width:150px;border:1px solid black;'>";
  echo "</td>";
  echo '<tr>';
  echo '<td>' .$v->product_name. "</td>";
  echo '<td>' .$v->product_quantity. "</td>";
  echo '<td>' .$v->product_id.  "</td>";

product_id below works exactly as it should.

  echo '<td> <button type="submit" onclick="askForSell('.$v->product_id.')">  Sell  </button>  </td>';

product_name on the other hand does not work.

  echo '<td> <button type="submit" onclick="askForBuy('.$v->product_name.')">   Buy   </button> </td>';

JavaScript

form=document.getElementById("sellAndBuy");

Works fine:

function askForSell(id) {  
    form.action="sellProducts.php";
    form['id'].value = id;
    form.submit();
}

Does not work:

function askForBuy(adProd) {
    form.action="buyProducts.php";
    form['adProd'].value = adProd;
    form.submit();
}

1 Answer 1

2

As the product name is a string, you need to have additional quotes around that name in the HTML. You'll need to escape those, since you already need to use both single and double quotes:

echo '<td> <button type="submit" onclick="askForBuy(\''.$v->product_name.'\')">   Buy   </button> </td>';

Note the \' that were added.

As these escaped quotes can become a pain in more complex situations, and also because it is better practice, you should consider binding event handlers with pure JavaScript code instead of using onclick HTML attributes.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.