//I want to insert a text in the database (MySql) by calling a js function then another js //scripts retrieves the data from the database and displays it in a div on my html page //from //where i posted the text ....
//HTML from where i submit the text to be saved in the database
<html>
<head>
</head>
<body>
<div id = "change">Naruto</div>
<form id = "foo" action = "update()">
<input type = "text" name = "text" id = "text"/>
<input type = "submit" value = "change" ></input>
</form>
</body>
</html>
// the function that is called when i click the button
<script>
function update()
{
$("#foo").submit(function(event) {
/* Stop form from submitting normally */
event.preventDefault();
/* Clear result div*/
$("#result").html('');
/* Get some values from elements on the page: */
var values = $(this).serialize();
/* Send the data using post and put the results in a div */
$.ajax({
url: "acition.php",
type: "post",
data: values,
success: function(){
alert("success");
$("#result").html('Submitted successfully');
},
error:function(){
alert("failure");
$("#result").html('There is error while submit');
}
});
});
}
</script>
//the php file that actually updates the data
<?php
mysql_connect("localhost","root","") or die ("CANNOT CONNECT TO THE DATABASE".mysql_error());
mysql_select_db("ajax_database") or die ("CANNOT CONNECT TO THE DATABASE");
$text = $_POST['text'];
$sql = "insert into news(statement)values('$text')";
mysql_query($sql);
?>
<html>
<head></head>
<body>
// the script that gets the data from a different page to show it to the html div
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("change").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getdata.php",true);
xmlhttp.send();
</script>
</body>
</html>
// the php file that selects the data to be retrieved from the database // getdata.php
<?php
mysql_connect("localhost","root","") or die ("CANNOT CONNECT TO THE DATABASE".mysql_error());
mysql_select_db("ajax_database") or die ("CANNOT CONNECT TO THE DATABASE");
$sql = "select * from news";
$result = mysql_query($sql);
while ($rows = mysql_fetch_array($result))
{
echo $rows[0];
}
mysql_close();
?>
//basically just like we update the status on facebook .... i am doing the same thing .... //without refreshing the whole page it refreshes the part of the html page where the new //updated text will be shown
//enter code here
thanks i am really in a mess right now .... please help me out .... i am //new to ajax ...