1

I want to submit data through ajax to the database and after inserting data into database this data should be displayed on the file Demo.html dynamically at the last i.e., after div in my case.

Well storing data through ajax i have done but i don't know how to display this newly inserted data to Demo.html.So do guide me how to achieve this.

Below is my code.

AjaxFile.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body >

<p><span id="get">Ajax response comes here</span></p>
<div id="divId">
    <input type="text" name="i1" value=""  /><br />
    <input type="text" name="i2" value=""  /><br />
    <button onclick="ajaxFunction()">Click </button>
</div>

<script src="jquery-3.2.1.min.js" ></script>
<script type="text/javascript">

function ajaxFunction() {
    $(function(){
        var myData1 = $("input[name='i1']").val();
        var myData2 = $("input[name='i2']").val();

        $.ajax({
            type : "post",
            dataType : "text",
            url : "controller.php",
            data : { data1 : myData1, data2 : myData2}, 
            success : function(msg){
                document.getElementById('get').innerHTML = msg;

            }
        });
    });
}

</script>
</body>
</html>

controller.php

<?php

session_start();

$servername = "localhost";
$username = "root";
$password = "";
$databaseName = "mydb1";

 try {

  $conn = new PDO("mysql:host = $servername; dbname = $databaseName", $username, $password);
  // set the PDO error mode to exception
  $conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

   $conn->exec("use mydb1");

  if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['data1']) && isset($_POST['data2'])) {

      $data1 = $_POST['data1'];
      $data2 = $_POST['data2'];

      $statement = $conn->prepare("Insert into mytable (data1, data2) values (:data1 , :data2)");

      if( $statement->execute(array("data1"=>"$data1", "data2"=>"$data2")) ) {

        echo "successfully inserted";
        // want to display $data1 and $data2 at the last in Demo.html just after inserting.


    } else {
      echo "Not successfully inserted";
    }
} else {

     echo "something is not set";
}

}catch(PDOException $e) {
echo "connection failed ". $e->getMessage();
}

$conn = null;
?>

Demo.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style type="text/css">
    body {
        margin : 0;
    }
    #first {
        width : 100%;
        height : 100px;
        margin : 30px auto auto auto;
        border : 1px dashed black;
    }
</style>
</head>
<body>

<div id="first" align="center"> I want to display newly inserted data below this div</div>

</body>
</html>
Aasim
  • 113
  • 2
  • 14
  • After successful post, could you not redirect to Demo.html and append the `msg` to your `#first` div ? – Nikhil Nanjappa Aug 10 '17 at 16:06
  • @Nikhil Nanjappa i want to insert "data1" and "data2" after the div( "#first") i.e. "data1" in first line and "data2" in next line.Hope you understand. – Aasim Aug 10 '17 at 16:09
  • Remove the quotes from around the variables here: `if( $statement->execute(array("data1"=>"$data1", "data2"=>"$data2")) )` Should be `if( $statement->execute(array("data1"=>$data1, "data2"=>$data2)) )` – Jay Blanchard Aug 10 '17 at 16:34
  • @Nikhil Nanjappa Can you tell more about it. I tried it i got is that "AjaxFile.html" is displayed below the "Demo.html" – Aasim Aug 10 '17 at 16:35
  • @Jay Blanchard thanks for your response but it executes successfully using quotes and the problem is to append data1 and data2 to Demo.html – Aasim Aug 10 '17 at 16:37
  • @learner I have provided a solution below, Let me know if it solves your purpose – Nikhil Nanjappa Aug 11 '17 at 08:25

3 Answers3

2

My solution does not involve php but JQuery & HTML5 LocalStorage and most importantly it will solve your issue.

Firstly inside your success function of ajaxFunction() you should store the value of data1 and data2 in Localstorage variables. Read about LocalStorage here

ajaxFunction()

    $.ajax({
        type : "post",
        dataType : "text",
        url : "controller.php",
        data : { data1 : myData1, data2 : myData2}, 
        success : function(msg){
            document.getElementById('get').innerHTML = msg;

            // store your values in LocalStorage
            localStorage.setItem("StoredData1", myData1);
            localStorage.setItem("StoredData2", myData2);

            // redirect after storing 
            window.location.href = 'Demo.html'
        }
    });

Then in a script included in Demo.html or directly in its HTML write the below JavaScript code to fetch the LocalStorage variables we stored earlier and append to the div.

HTML body in Demo.html

<body>
  <div id="first" class="afterThis" align="center"> I want to display newly inserted data below this div</div>
</body>

JavaScript in Demo.html

$(".afterThis").last().after("<div class='afterThis'>"+ localStorage.getItem("StoredData1") +"</div>");
$(".afterThis").last().after("<div class='afterThis'>"+ localStorage.getItem("StoredData2") +"</div>");
Nikhil Nanjappa
  • 6,454
  • 3
  • 28
  • 44
  • Thanks for your response.I tried your code and it appends data after div's data i.e. inside the $first div's content but i want it should be appended after boundary of div not inside, and data should be appended permanently.Please help me out – Aasim Aug 11 '17 at 17:49
  • please look at my previous post and tell me how to do it.thanks – Aasim Aug 12 '17 at 11:07
  • @Nikihil Nanjappa, please help me as the problem is not solved yet. – Aasim Aug 14 '17 at 05:45
  • Ok. I just came in. If you need after the `div#first`, then just replace `.append` with `.after`. Answer updated – Nikhil Nanjappa Aug 14 '17 at 08:38
  • Thanks for response,by the way how to permanently stick every data after div(#first) whenever submitted and previously attached data should go after newly attached data and so forth. – Aasim Aug 14 '17 at 09:55
  • I don't know what you mean by "permanent", None of what we are doing is temporary. But for appending after the last, you could add a class to each `div` **including div(#first)** and use `.last()`. Answer updated – Nikhil Nanjappa Aug 14 '17 at 10:19
  • All what have understood with .last() is that it returns the last element of a parent but not understand much how to do it.Could you implement it for better understanding.Thanks – Aasim Aug 14 '17 at 10:39
  • I already implemented it in my answer. Did you look? Not necessarily last of parent but **last div with classname `.afterThis`** in your case – Nikhil Nanjappa Aug 14 '17 at 10:47
  • After updating the code with new one you provided nothing is showing.why so? – Aasim Aug 14 '17 at 11:03
  • I added class(.afterThis) to div(#first) and now displaying but previous attached data is getting lost how to keep previous data safe ,as it is overriding. – Aasim Aug 14 '17 at 11:08
  • please help me out as i am close to the solution. – Aasim Aug 16 '17 at 11:13
1

after insert to database use function file() to save to file with append subfunction, that write new row to your file, and the read file in demo.html -< BUT this need to be php file and php function to read your last inserted data, then simple redirection in ajax in success: section to your file, or for example read file to div exaclly where you want.

In your controller php use function file to save in append mode string to your file. look here: http://php.net/manual/en/function.file-put-contents.php

And after this call ajax to get for example read.php inside php use file() of php to read this file what you writed before.

0

It's based on answer from @Nikhil Nanjappa.

You can use an array to store more items in localStorage. Store object in localStorage.

AjaxFile.html

success: function(msg) {
  document.getElementById('get').innerHTML = msg;

  StoredData = JSON.parse(localStorage.getItem("StoredData"));
  if(!StoredData) StoredData = [];
  StoredData.push(myData1);
  StoredData.push(myData2);
  localStorage.setItem("StoredData", JSON.stringify(StoredData));

  window.location.href = 'Demo.html'
}

Demo.html (At the bottom of the body)

<script type="text/javascript">
  StoredData = JSON.parse(localStorage.getItem("StoredData"));
  StoredData.reverse().forEach( function(data) {
    $('#first').after('<div>data = ' + data +'</div>')
  });
</script>
yellowmint
  • 130
  • 5
  • Data is successfully inserted after div(#first) but when i again submit then previously data is overridden but i want to display data1 and data2(both in different line) in "Demo.html" after the div(#first) every time when data is submitted and previously inserted data should shift one position below so that newly data could come after div(#first) every time.I think now you understand the problem – Aasim Aug 18 '17 at 15:22
  • I see. It seems to me that this should be done in php. I don't know php. So my answer is based on @Nikhil Nanjappa code with localStorage. – yellowmint Aug 18 '17 at 16:15
  • I think @Nikhil Nanjappa answer is very close and need some guidance to accomplish the task. thanks – Aasim Aug 18 '17 at 17:41
  • Can you tell me more about it as localStorage can store upto 5MB and for large data what needs to be done? – Aasim Aug 19 '17 at 08:24
  • LocalStorage is designed for small amounts of client-side data - each client can have different data. I think that for more data you should store them in the database on the server. Or for large files as regular files on the server. So you get one source of data. In php you need to take data from the database and send them to the client. – yellowmint Aug 19 '17 at 08:44