简体   繁体   中英

Using PHP code in Javascript when adding form input dynamically

I am trying to make a form to register a product details. Everytime user click the 'Add' button, I wanted to add more input fields for the user to key in their products.

The code looks like this.

<form id="myform">
<label>Product Name</label>
<input type="text" name="productname0" value=">
<?= !empty($data["error_productname0"]) ? "<p class=\"help is-danger\">". $data["error_productname0"] ."</p>": ""; ?> 
</form>

<script>
    $("button.add").click(function(){
        let inputNumber = $("#myform").children("input").length;
        $("#myform").append(returnNewInput(inputNumber));
    });


    function returnNewInput(n) {

        return `<input type="text" name="productname${n}" value="">
                <?= !empty($data["error_productname${n}"]) ? "<p class="help is-danger">$data["error_productname${n}"]</p>": ""; ?>`;

    }
</script>

But I had problem using the inputNumber variable. I cannot pass it into the returnNewInput function. The error says,

Notice: Undefined variable: n

Is it impossible to implement PHP code such as empty, isset etc in Javascript code? I thought PHP code is just a chunk of string in Javascript.

PHP executes on the server end. After executing, the result is sent to the user's web browser. PHP absolutely does not ever run in the user's browser, so doing something like this simply isn't going to work.

There are two solutions for the problem you're facing:
1) You can just use JS to do what you're trying to do.
2) You can make an ajax request to your server, have PHP render some HTML for you to use, then retrieve the result and insert it using JS.

The first solution is clearly better as the second is far more complicated and inefficient for accomplishing the same task.

Try to remember it this way: PHP is for setting up the initial state of the web page or ajax request result, not for modifying it afterward.

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