Havoux
Havoux

Reputation: 165

PHP Concatenate Variable in URL string

<td><input type="submit" onClick="window.location.href='https://www.'.$myVariable.'.test.com'" value="Click!"></td>

I have a button that should go to 1 of 8 possible url's - I have the logic to get the variable however I seem to run into an issue here. I get an error saying

Unresolved Variable: $myVariable

Is this because I am within a HTML table?

I even tried using .<?=$myVariable?>. between the strings and still didnt work. Am I missing something obvious?

Upvotes: 1

Views: 2046

Answers (4)

Alejandro Iv&#225;n
Alejandro Iv&#225;n

Reputation: 4071

You're just getting complicated because of concatenations, so I'll just split them.

<?php
    $fullUrl = "https://www.{$myVariable}.test.com"; // Repeat for every variable
    $locationHref = "window.location.href='{$fullUrl};'";
?>

<td>
    <input type="submit" onClick="<?=$locationHref; ?>" value="Click!" />
</td>

As a sidenote, if you want to stop the normal submit of the form and actually do some processing with AJAX, you need to catch onsubmit on your <form> element (and return false on that attribute, or the form will submit anyway).

Right now you're redirecting using Javascript blocking your form submit (in strict terms, you're redirecting and also submitting, but not waiting for it to finish, which could lead to issues).

Upvotes: 0

Pedro Lobito
Pedro Lobito

Reputation: 99081

Use <?=$myVariable?> or <?php=$myVariable?> if you don't have short tags enabled.

<td><input type="submit" onClick="window.location.href='https://www.<?=$myVariable?>.test.com' value="Click!"></td>

Another option is using heredoc (my favorite) to include the html and php code, this way you don't have to concern about quotes or concatenation i.e.:

<?php
echo <<< LOL
<td><input type="submit" onClick="window.location.href='https://www.{$myVariable}.test.com'" value="Click!"></td>
LOL;

Upvotes: 3

Mahesh Chavda
Mahesh Chavda

Reputation: 593

Try this:

<td><input type="submit" onClick="window.location.href=<?php echo "'https://www.".$myVariable.".test.com'"; ?>" value="Click!"></td>

Just do php echo to your variable string.

Upvotes: 0

Seva Kalashnikov
Seva Kalashnikov

Reputation: 4412

Just output php variable inside one string:

<td><input type="submit" onClick="window.location.href='https://www.<?php=$myVariable; ?>.test.com'" value="Click!"></td>

Upvotes: 3

Related Questions