0

I am using Ajax to add 3 values to my database, and then immediately append them at the bottom of my Table using the following:
**EDIT: Added the full code, and I currently only adding 1 value to the database, leaving the others empty (Adding only Text1)

  <!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    </head>
    <body>

    <script>
        $(document).ready(function() {
        $("#Submit").click(function (e) {
                e.preventDefault();
                if($("#Text1").val()==='')
                {
                    alert("Please enter some text!");
                    return false;
                }




                var myData = 'txt1='+ $("#Text1").val(); //build a post data structure
                jQuery.ajax({
                type: "POST", 
                url: "ajax.php", 
                dataType:"text", 
                data:myData, 
                success:function(response){                            
                var row_data = "";
                row_data +="<tr><td><?php echo $_POST['txt1'] ; ?></td><td><?php echo $_POST['txt1'];?></td><td><?php echo $_POST['txt1'];?></td></tr>";
                $("#mytable").append(row_data);
                $("#responds").append(response);
                    $("#Text1").val(''); //empty text field on successful
                    $("#FormSubmit").show(); //show submit button
                    $('table').html(data);


                },
                error:function (xhr, ajaxOptions, thrownError){
                    $("#FormSubmit").show(); //show submit button
                    alert(thrownError);
                }
                });
        });

    });
    </script>



    <?php
    $servername = "localhost";
    $username = "username";
    $password = "";
    $dbname = "test_database";

    $mysqli = new mysqli($servername, $username, $password, $dbname);

    if ($mysqli->connect_error) {
        die("Connection failed: " . $mysqli->connect_error);
    } 
    echo "Connected successfully";


    if(isset($_POST["txt1"]) && strlen($_POST["txt1"])>0) 
    {    

        $contentToSave = filter_var($_POST["txt1"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); 

        $insert_row = $mysqli->query("INSERT INTO test_table(fname) VALUES('".$contentToSave."')");

        if($insert_row)
        {    
              $mysqli->close(); //close db connection

        }else{

            header('ERROR');
            exit();
        }}
        ?>
    <div class="form_style">
    <textarea name="content_txt" id="Text1" cols="45" rows="1"></textarea><br>
    <button id="Submit">Add record</button>
    </div><br>
    <table class="table" id="mytable" style="width:100%">
      <tr>
        <th>Firstname</th>
        <th>Lastname</th> 
        <th>Age</th>
      </tr>
//initially filling the table with db data
    <?php
    $sql = "SELECT fname, lname, age FROM test_table";
    $result = $mysqli->query($sql);

    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            echo "<tr><td>". $row["fname"] . "</td><td>" . $row["lname"] . "</td><td>" . $row["age"] . "</td></tr>";

        }
    } else {
        echo "0 results";
    }
    $mysqli->close();
    ?>



    </table>

    </body>
    </html>

The posting does work: txt1, txt2 and txt3 are inserting into the database, but what I see at the bottom of the table is '.$_POST['txt1'].' and so on, instead of the actual POST data

2 Answers2

0

if you want to use php code in javascript then try below ==>

success:function(response){                               
                    var row_data = "";
                    row_data +="<tr><td><?php echo $_POST['txt1'] ; ?></td><td><?php echo $_POST['txt2'];?></td><td><?php echo $_POST['txt3'];?></td></tr>";
Narayan
  • 1,670
  • 1
  • 19
  • 37
  • Now the submit button does nothing, so there must be something wrong here either –  May 29 '17 at 16:55
  • added, and I only add 1 value currently (Only txt1, so the code only posts txt1, so don't try to find txt2 and txt3 :D) –  May 29 '17 at 17:08
0

The argument you named response in the declaration of the function for success setting of the ajax call (I assume you are using jQuery's $.ajax) contains whatever your Web server sent to you.

In your case if you send AJAX request to the code you provided, that is, if the code you provided is exactly that ajax.php you referenced in the url setting of the jQuery.ajax call, THEN THE response VAR WILL CONTAIN FULL HTML TEXT RENDERED, which is probably absolutely useless to you.

Proper usage of the AJAX would be like this:

$.ajax({
    // ...
    dataType: 'json', // I can remember incorrectly here. It assumes your PHP backend sends JSON-encoded string.
    success: function (data) { // data will be an object already parsed from JSON string sent by server.
        var row_data = "";
        row_data += "<tr><td>";
        row_data += data.txt1;
        row_data += "</td><td>";
        row_data += data.txt2;
        row_data += "</td><td>";
        row_data += data.txt3;
        row_data += "</td></tr>";
    }
});

Move the block of code starting with if(isset($_POST["txt1"]) && strlen($_POST["txt1"])>0) to the very beginning of the file and do the following on successful insert to the database:

header("Content-Type: application/json");
echo json_encode(['txt1' => $_POST['txt1'], 'txt2' => @$_POST['txt2'], 'txt3' => @$_POST['txt3']);
die();

This way when handler registered in success will be entered, the response will contain the proper JSON block. You don't need to re-render the whole page on AJAX requests.

You don't need the $("#responds").append(response); block because it'll lie to you due to rendering of the response contents according to HTML rendering rules. Just use the F12 in browser and inspect the server response directly.

hijarian
  • 2,159
  • 1
  • 28
  • 34
  • A few problems: I am using text not json, and it shows me undefined instead of the data –  May 29 '17 at 16:54
  • I will not go into details of all problems with your code but I updated the answer with explanations regarding your exact question. – hijarian May 29 '17 at 19:06