0

I'm doing a project where I have a dynamic HTML form. I have a Jquery script that adds new inputs, then I save this data in a data base. This all works perfectly. Now I want to write in an input the value of one mysql field. I give the input his value like this:

<?php
$name = $_SESSION['name'];
?>    
<input type="text" name="name[]" value="<? echo $name ?>" />

add_form.js

<script>

$(document).ready(function(e){
   var html= '<p /><table><tr><td><input type="text" name="field1[]" id="field1child"></td><td><input type="text" name="field2[]" id="field2child"></td></tr></table>';

                $("#add").click(function(e){
                    $("#container").append(html);
                });
});

How can I write value="" with echo $name insied it in the jquery variable? I want to have this name and save it every time I create a new input

save.php

<?php
session_start();
if(!$_SESSION){
  header('Location: login.php');
}
if(isset($_POST['submit'])){
  $mysqli = NEW MySQLi('localhost','user','pass','database');


    $field1   = $_POST['field1'];
    $field2     = $_POST['field2'];

    foreach($field1 AS $key => $value){
        $query = "INSERT INTO facturas (field1,field2)VALUES ('"
        . $mysqli -> real_escape_string($value) .

        "')
        ";

        $insert=$mysqli->query($query);


    }

        if($insert){
            echo "Data saved";
        }               






$mysqli->close();               
}   
?>
3
  • Do you already have the code that fetches the list of names already save in the database (mysql)? If you can post that to the question, we'll be able to guide you on the next step more easily. Commented Dec 13, 2017 at 5:55
  • field2 in your insert query isn't getting a value. You may want to take a look at that. Commented Dec 13, 2017 at 6:20
  • 1
    Check dexterb's answer below. That will give you the basic idea of how to pass a PHP variable to javascript. You can then use that variable's value while generating your <input> html in the JS. Commented Dec 13, 2017 at 6:31

1 Answer 1

3

Assuming that you include your javascript in the footer area of your html, then the simplest way to access your php variables from javascript is to declare it as a new javascript variable.

<?php
   $name = $_SESSION['name'];
?>    
<input type="text" name="name[]" value="<? echo $name ?>" />

<script>
   window.myPhpVars = {};
   myPhpVars.name = '<?php echo $name; ?>';
</script>
<script src="add_form.js"></script>

In this way, in your add_form.js, you can easily access myPhpVars.name

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.