Live update php variable and simultaneously, show the value in a textbox - php

This is my table row click function in the file, 'BAConsult.php'. On click, showconsultationdata function will run.
$(document).ready(function(){ //table row click
}).on('click','.consultclick tr',function(e){
if(e.target.tagName === "TD"){
$(".consultclick tr").removeClass("highlight");
$(e.target).parent().addClass("highlight");
}
var dateconsulted = $(this).attr('value');
alert(dateconsulted);
showconsultationdata(dateconsulted);
});
This is my ajax script
function showconsultationdata(str) {
if (str == "") {
document.getElementById("txtHint2").innerHTML = "";
return;
} else {
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("txtHint2").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","BAConsultRecordsAJAX.php?q="+str,true);
xmlhttp.send();
}
}
Here is another php file called 'BAConsultRecordsAJAX.php' where i placed the ajax of the showconsultationdata.
session_start();
require('Config/Setup.php');
$q = $_GET['q'];
$consult="SELECT * FROM Counsel where nric='$_SESSION[nric]' and dateconsulted='$q'";
$consultresult = mysqli_query($dbconn,$consult);
while($row = mysqli_fetch_array($consultresult)) {
$skincareremarks=$row['skincareremarks'];
$skinconditionremarks=$row['skinconditionremarks'];
}
On table row click, $skincareremarks and $skinconditionremarks should be updated. And these values will show up in the textboxes in the 'BAConsult.php' page. How can i do this?

So, i followed #Jeff's method by using JSON. However, I realised that the xmlhttp.responseText wasn't only showing my JSON encoded code, but also my javascript which was why the JSON.parse method was unable run properly. I then did the following:
In my BAConsultRecordsAJAX.php file, i did this.
echo "<div id='test1'>";
echo json_encode(array('first'=>$skincareremarks,'second'=>$skinconditionremarks));
echo "</div>";
I gave this output a div called 'test1'.
Then, in my main file's AJAX script, i did this.
var a = JSON.parse($(xmlhttp.responseText).filter('#test1').html());
document.getElementById("test").value=a.first;
So basically, it filters out the rest of the xhtmlhttp.responseText outputs, and selects only the contents in the div where id='test1'.
Hope this helps those who have this problem too..

Related

I want button to do simply task, execute php code

I want my button to do simple task, when i click on it it should send
$sql = "UPDATE `user` SET `free`=2 WHERE username='$username'";
$result = mysql_query($sql) or die(mysql_error());
$count = mysql_num_rows($result);
but without refreshing. I know how to do it, but everytime i click on button it refresh page ( tried with a href that set up to other page etc). Is any way to set it so?
I meant not send, but execute this one.
I would recommend you using AJAX to send your data to a PHP page that will do the task you want.
With Javascript:
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 ) {
if(xmlhttp.status == 200){
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
else if(xmlhttp.status == 400) {
alert('There was an error 400')
}
else {
alert('something else other than 200 was returned')
}
}
}
xmlhttp.open("GET", "ajax_info.txt", true);
xmlhttp.send(); } </script>
With jQuery:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
} });
your looking for ajax
http://en.wikipedia.org/wiki/Ajax_(programming)
Most (maybe all) javascript frameworks have wrappers for AJAX to make it easier
http://api.jquery.com/jquery.get/
and
http://api.jquery.com/jquery.post/
for example

Auto-save textarea every so many seconds

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

Onbeforeunload - popux box will not display or trigger

I am building a website with user-profiles. I am at the picture part at the moment. When a person upload their image with no problem, the picture will be stored in 4 different folders. One for size 25, 100, 150 and normal size. After this they will be redirected to the same page, with new content. This is the part, where they need to crop their picture. Crop part works great, but I have a problem. When they leave the site without cropping, the pciture they just uploaded is still stored in the folders, and that's not what i want. So i mate some checks with AJAX, and it will unlink the 4 files sotred already. My problem is, that this shall only happen, when they leave the site(onbeforeunload.)
This works very great in IE, but not in Chrome.(Only two browsers i've tested yet.)
Here is what I'm doing:
function unfinished(album,img){
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) {
return xmlhttp.responseText;
}
}
xmlhttp.open("GET","incl/unfinished.php?a=" + album + "&i=" + img,true);
xmlhttp.send();
}
The function above get information from "uncl/unfinished.php" by the query string. And it all works well.
Code on unfinished.php:
session_start();
require('../dbconnect.php');
$sql = "SELECT * FROM users WHERE username='".$_SESSION['username']."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
$username= $row['brugernavn'];
}
$album = $_GET['a'];
$img = $_GET['i'];
$sourcex = "../users/".$username."/images/".$album."/x-x/".$img;
$source25 = "../users/".$username."/images/".$album."/25/".$img;
$source100 = "../users/".$username."/images/".$album."/100/".$img;
$source150 = "../users/".$username."/images/".$album."/150/".$img;
if(unlink($sourcex)){
}
if(unlink($source25)){
}
if(unlink($source100)){
}
if(unlink($source150)){
}
echo "Error 908. The picture didn't get cropped, and neither saved. Try again.";
The AJAX code and unfinished.php deletes the images withpout any problems. I've tested that already. Now my problem:
I am running the AJAX code by
The code should be running inside this:
//function warn(album,img){
window.onbeforeunload = function (e) {
e = e || window.event;
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = unfinished(album,img);
}
// For Safari
return unfinished(album,img);
};
//}
But when i try to return xmlhttp.responseText, the popup box doesn't popup, and i am not able to see the response.
But if i add "Hello world"(or some text) to the return like return Helloworld!''; or e.returnValue = 'Hello world!';, instead of the xmlhttp.responseText value, it pops up, and display the message. But it doesn't display the xmlhttp.responseText, because it doesn't run the unfinished() function.
any solutions how i can run the AJAX when user leaves page?
If it helps here is the HTML code:
if($_POST['where'] == "newalbum"){
$nameonalbum = $_POST['nameonalbum'];
}else{
$nameonalbum = $_POST['existingalbum'];
}
$filenamenew=time().'.gif';
?>
<body onload="warn('<?=$nameonalbum?>','<?=$filenamenew?>')">
Solved it by myself. Did like this:
function unfinished(album,img){
window.onbeforeunload = function (e) {
e = e || window.event;
var response = '';
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){
response = xmlhttp.responseText;
}
}
xmlhttp.open("GET","incl/unfinished.php?a=" + album + "&i=" + img,true);
xmlhttp.send();
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = response;
}
// For Safari
return response;
}
}
But now i have another problem... 1st of all the unload function works great, but I don't want it to trigger when the "Save crop" button is clicked. Any ideas how to do this?
Save button html:

Display Multiple Records From SQL Query Using AJAX with Timer

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

favorite button for article

I want to create for my blog an articles fav button. First I use :
<script type="text/javascript">
function AddPost(str,user)
{
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", "addfav.php?p=" + str + "&u=" + user, true);
xmlhttp.send();
}
</script>
Where p is post ID and u is the user who fav'd the article. In the loop for the articles I add an image with:
onclick="AddPost(<php echo of the post id>, <php echo of the current user id>)"
And that was stupid because the function works for all of them, not for just one. In addfav.php I just get the p and u parameters and then INSERT into the database. I'm new to Ajax and I dont know how to make it different for the articles.
Your PHP code needs to not allow any more favorites to be added (I cannot comment further on that because you did not include the PHP/SQL code). Also, in your javascript code, once AJAX has returned successful, disable the other Fav buttons.
By the way, using a well-tested library like jQuery (especially for AJAX) will greatly speed development.

Categories