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