Aasim
Aasim

Reputation: 143

Update dynamically a page through ajax and php

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>

Upvotes: 1

Views: 219

Answers (3)

yellowmint
yellowmint

Reputation: 130

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>

Upvotes: 0

Nikhil Nanjappa
Nikhil Nanjappa

Reputation: 6652

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>");

Upvotes: 2

CommanderSpock
CommanderSpock

Reputation: 72

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.

Upvotes: 1

Related Questions