I need help with "auto-saving" a textarea. Basically, whenever a user is typing in the textarea, I would like to save a "draft" in our database. So for example, a user is typing a blog post. Every 15 seconds I would like for the script to update the database with all text input that was typed into the textarea.
I would like for this to be accomplished thru jQuery/Ajax but I cannot seem to finding anything that is meeting my needs.
Any help on this matter is greatly appreciated!
UPDATE:
Here is my PHP code:
<?php
$q=$_GET["q"];
$answer=$_GET["a"];
//Connect to the database
require_once('mysql_connect.php') ;
$sql="UPDATE english_backup SET q".$q."='".$answer."' WHERE student_id = {$_COOKIE['student']} LIMIT 1";
$result = mysqli_query($dbc, $sql);
?>
Here is my javascript code:
<script type="text/javascript">
function showUser(str, answer)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser_english.php?q="+str+"&a="+answer,true);
xmlhttp.send();
}
</script>
function saveText() {
var text = $("#myTextArea").val();
// ajax call to save the text variable
// call this function again in 15 seconds
setTimeout(saveText, 15000);
}();
I think you want something like ajax... I'm using ajax jQuery so you will need jQuery Library for it to work. Download it. You can find tutorials on the documentation tab of the website.
//in your javascript file or part
$("textarea#myTextArea").bind("keydown", function() {
myAjaxFunction(this.value) //the same as myAjaxFunction($("textarea#myTextArea").val())
});
function myAjaxFunction(value) {
$.ajax({
url: "yoururl.php",
type: "POST",
data: "textareaname=" + value,
success: function(data) {
if (!data) {
alert("unable to save file!");
}
}
});
}
//in your php part
$text = $_POST["textareaname"];
//$user_id is the id of the person typing
$sql = "UPDATE draft set text='".$text."' where user_id='".$user_id."'"; //Try another type of query not like this. This is only an example
mysql_query($sql);
if (mysql_affected_rows()==1) {
echo true;
} else echo false;
Hey everyone I'm still having a problem please see here https://stackoverflow.com/questions/10050785/php-parse-html-using-querypath-to-plain-html-characters-like-facebook-twitter
Related
I have a form in which all the contacts are listed with fields like first name last name etc. Every row has view edit delete anchor tags on which I am calling a popup div. This popup div contains the php include(external file). I want to access the selected rows unique database primary key in that external file.
The link of the code is
https://www.dropbox.com/s/88qpmkwmaepa5s4/New%20Text%20Document%20%283%29.txt
Any help is appreciated.
Thank you
As a simple example to call Ajax by javascript and send the clicked row id to the php file, check this
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//returned response from ajax to the php page will be in xmlhttp.responseText
alert(xmlhttp.responseText); // Do whatever you need with the respones
}
}
var selected_row = document.getElementById('selected_row').innerText; // we assume this is the value of the selected row
xmlhttp.open("GET","path_to_your_phpfile&row_id=" + encodeURIComponent(selected_row), true);
xmlhttp.send();
}
Now the selected row id is passed by GET and in your php file you can get by $row_id = $_GET['row_id'];
If you are using jQuery, you go for a quick kill with AJAX.
Javascript:
<script>
function show_div(id) {
function show_lightbox(){
// your code
}
$.ajax({
type: "POST",
url: "get_detail.php",
data: "id=" + id,
dataType: "html",
success: function(html){
$("#show_detail").html(html);
}
});
}
</script>
Html:
<div id="lightbox">
<div id="show_detail"></div>
</div>
In your anchors:
<a onClick="show_div(uniqe_primarykey)">Click to fetch details</a>
In get_details.php
<?php
$id = $_POST[id];
//your queries
?>
<html>
Data from queries
</html>
it's my first programming experience in Ajax (or Jquery) so i appreciate any kind of help.
What i am trying to do is that i have 2 select inputs in my html form i want when the first select is changed (onchange) to have its value to use it to filter the second select in php to dynamically generate its options, that must happen without submitting the entire form only the first select.
I tried the following code but whenever the first select changes it submit the entire form.
the ajax function:
function showKadaa(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("kop").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","annonce.php?mid="+str,true);
xmlhttp.send();
}
the html code portion with php:
<?php if(isset($_GET['mid']))
$q=$_GET['mid'];
else $q=$_SESSION['mid'];?>
//code goes here
<tr><td>Kadaa:</td><td><div id="kop"><select name="kadaa" id="kad" ><option value="default">[Choisir Kadaa]</option>
<?php
if(login_db()){
$req="SELECT `nom_kadaa`,`id` FROM `kadaa` WHERE `id_mohafaza`=".$q."";
echo $req;
$kadaa="";
if($res=mysql_query($req)){
while($l=mysql_fetch_array($res)){
echo "<option value=".$l[1].">".$l[0]."</option>";
}
}
}
?>
</select></div></td></tr>
P.S: WHERE EVER I PUT THE div of id="kop"
the entire page is submited in it. Another thing i using the two select on same page with
form action="<?php echo $_SERVER['PHP_SELF'];?>
for getting on field value:
jquery would love to use
$("#IdOfElement").val();
by the way, jquery has a lot more handy methods for ajax:
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
trying to insert a record in my DB using AJAX for the very first time. I have the following...
Form
<form>
<input type="text" id="salary" name="salary">
<input type="button" onclick="insertSalary()">
</form>
AJAX
<script type="text/javascript">
function insertSalary()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById('current-salary').innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("POST","insert_salary.php",true);
xmlhttp.send("salary=" + document.getElementById("salary").value);
}
</script>
PHP
$uid = $_SESSION['oauth_id'];
$monthly_income = mysql_real_escape_string($_POST['salary']);
#Insert a new Record
$query = mysql_query("INSERT INTO `income` (user_id, monthly_income) VALUES ($uid, '$monthly_income')") or die(mysql_error());
$result = mysql_fetch_array($query);
return $result;
Nowmy data is being inserted into the table BESIDES the 'salary' which is being inputted as '0'
Once inserted I also have a div 'current-salary' that should then be populated with there inputted value only it isnt, Can anybody help me to understand where im going wrong?
If you want to save your self a lot of time, effort, and heartache, use the jquery library for your ajax requests. You can download it at http://jquery.com/
After adding a reference(Script tag) to the jquery script your javascript for the ajax request would become:
function insertSalary()
{
var salary = $("#salary").val();
$.post('insert_salary.php', {salary: salary}, function(data)
{
$("#current-salary").html(data);
});
}
Also keep in mind that using "insert_salary.php" as the url means it is a relative path and must be in the folder of the current running script.
Your php script needs to echo whatever you would like to be injected into your current-salary tag also.
I'm trying to find a good example on how to retrieve records using PHP from a table and refresh it say every 2 minutes using Ajax.
Anyone can point me to that tutorial?
I don't think you'll find a tutorial that specific, but you just need to learn AJAX and then make the AJAX call every two minutes using JavaScript's setInterval method.
EDIT
Meh, I'm bored enough to write this example. This isn't tested, but I don't think it has errors.
<html>
<head>
<script type="text/JavaScript">
window.onload = function()
{
// call your AJAX function every 2 minutes (120000 milliseconds)
setInterval("getRecords()", 120000);
};
function getRecords()
{
// create the AJAX variable
var xmlhttp;
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
// set up the response function
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
/*
Your code goes here. 'xmlhttp.responseText' has the output from getRecords.php
*/
document.getElementById("txaRecords").innerHTML = xmlhttp.responseText;
}
}
// make the AJAX call
xmlhttp.open("GET", "getRecords.php", true);
xmlhttp.send();
}
</script>
</head>
<body>
<textarea id="txaRecords"></textArea>
</body>
</html>
This is a bit of code that I wrote for this exact purpose. Adapt as appropriate.
AJAX code:
function timer()
{
var t=setTimeout("check()",2000);
// At an appropriate interval
}
function check(){
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if (xmlhttp.responseText!=""){
var output = xmlhttp.responseText;
// Do what you need to do with this variable
}
}
}
xmlhttp.open("GET","backend.php",true);
// Set file name as appropriate.
xmlhttp.send();
timer();
}
PHP code:
<?php
// This assumes you have already done mysql_connect() somewhere.
// Replace as appropriate
$query = "SELECT * FROM table_name";
// Perform the query
$result = mysql_query($query);
// Get the results in an array
while($row = mysql_fetch_array( $result )) {
// Echo the message in an appropriate format.
echo "<br />" . $row['column_name'];
}
?>
Remember to initiate one of the JS functions as you load the page:
<body onload="timer()">
I want to count the number of hit on an image and also the image will show in a lightbox.
here is my code:
//image-show-content.php
<script>
function hitcounter(imgid)
{
//alert(imgid);
var imgid = imgid;
window.location.href ="image-show-content.php?img_id="+imgid;
}
</script>
<?php
if(!empty($_REQUEST['img_id']))
{
$show = "SELECT * FROM `tbl_image_gallery` WHERE image_id =".$_REQUEST['img_id']." ";
$result_show = mysql_query($show);
$row = mysql_fetch_array($result_show);
$new_click_count = $row['click_on_image'] +1;
$update_sql = "UPDATE `tbl_image_gallery` SET click_on_image =".$new_click_count." WHERE image_id=".$_REQUEST['img_id']."";
$result_sql= mysql_query($update_sql);
}
//image...
<img src="uploadedimage/gallery/thumble/<?=$val['gallery_image']?>" onclick="hitcounter('<?=$val[image_id]?>')"/>
?>
My problem is when I click on an image it return an error.
please help to solve it.Thanks in advance.Can you refer some other option to show light box and hit counter together.
Problem is, when your page loads. Lightbox javascript is already generating dynamic node for your tag.
To achieve this you can try with onclick function into . In that function you should call AJAX call with your image id. It would be possible that your onclick function may call after lightbox call OR before lightbox call. So please debug for this too.
This would be only one way to achieve this as per my opinion.
Place your php code in one another file called, hit_image.php and place your code there,
<?php
if(!empty($_REQUEST['image_id']))
{
$show = "SELECT * FROM `tbl_image_gallery` WHERE image_id =".$_REQUEST['image_id']." ";
$result_show = mysql_query($show);
$row = mysql_fetch_array($result_show);
$new_click_count = $row['click_on_image'] +1;
$update_sql = "UPDATE `tbl_image_gallery` SET click_on_image =".$new_click_count." WHERE image_id=".$_REQUEST['image_id']."";
$result_sql= mysql_query($update_sql);
}
Now your HTML file should be like follow,
<script type="text/javascript">
function counter(imageId)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","hit_image.php?image_id="+imageId,true);
xmlhttp.send();
}
</script>
<a onclick="counter(<?=$val[image_id]?>)" rel="lightbox[100,200]" title="<?=ucfirst($val['category_name'])?>"><img src="uploadedimage/gallery/thumble/<?=$val['gallery_image']?>" onclick="hitcounter('<?=$val[image_id]?>')"/></a>
This is just overview code for your hints.