I'm trying to make something like a web notepad that autosaves the changes every minute.
The notes are stored in a field "notas" for each user on the db.
Here a piece of code involved:
<html>
<head>
<script type='text/javascript'>
function submitForm(){
document.nota.submit();
}
function setTimeForSubmit(){
window.setTimeout("submitForm()",60000);//Expire after 60 Sec
}
</script>
</head>
<body onload="setTimeForSubmit()">
<form method="POST" name="nota" id="nota" action="notas.php">
<textarea name="txtNota" id="txtNota">
<?php
if(isset($_POST['txtNota'])){
$sql =
"UPDATE `login`
SET `notas`= ".$_POST['txtNota']."
WHERE login_id = ".$_SESSION['login_id']."";
$rs = $DB->Execute($sql);
}
$sql2 = "SELECT notas FROM login WHERE login_id=".$_SESSION['login_id']."";
$rs2 = $DB->Execute($sql2);
echo $rs2->fields[0];
echo $_SESSION['login_id'];
?>
</textarea>
<input type='submit' name='guardar' value="guardar"/>
</form>
</body>
</html>
I already checked every variable and query, and they are ok , but the UPDATE isn't working when I try to submit it this way. It works when done by itself, the $_POST and the $_SESSION have the correct values by themselves too, and the SELECT.
Any clues on why isn't it working? It doesn't throws any errors either
change
`notas`= ".$_POST['txtNota']."
to
`notas`= '".$_POST['txtNota']."'
you are missing '
I had a similar problem and this solution is working for me.
this uses a dirty bit and a wrapper around the form submit. This is because I ended up having several save triggers including handling destructive view switching events. And I didn't want to end up saving non change events.
Note: I think I found this solution on another SO question, maybe you can help me link it.
// PROP SHEET: save after a second using dirty bit for other save triggers
$('#props input, #props textarea, #props select').change(function() {
$('#props').attr('dirty', true);
console.log('change event fired',$(this));
delay(function(){
save_props();
}, 1000 );
});
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
Related
I'm using this jquery plugin to create a wysiwyg text editor,
I created a textarea in PHP where:
<textarea name="body" id="body"><?php echo $body?></textarea>
and
<script type="text/javascript">
$(document).ready( function() {
$("#body").Editor();
});
</script>
Now i need to get value of this area for send it to SQL
if (isset($_POST['add-article'])) {
unset($_POST['add-article']);
$_POST['user_id'] = $_SESSION['id'];
$_POST['username'] = htmlentities($_SESSION['username']);
$_POST['published'] = isset($_POST['published']) ? 1 : 0;
// I need this line
$_POST['body'] = htmlentities($_POST['body']);
When I put text into this editor, it doesn't enter (value) into the textarea.
I have to have value before I press the add-article button, beacuse now it gives me an empty text.
I found something like this
function displayText(){
alert($("#body").Editor("getText"));
}
This causes it to return text ( i think only display by JS ) but i completely dont know how to use in my PHP scripts.
Second thing is when i write article and make a mistake something like ( Article title already exist ) ( in one session ) text in textarea stayed, but now doesn`t work it.
I think about if there is an error for example "Title already exist" follows:
} else {
$title = $_POST['title'];
$body = $_POST['body'];
$category_id = $_POST['category_id'];
$published = isset($_POST['published']) ? 1 : 0;
}
In my honest opinion i need something like:
add-article.addEventListener('click', function {
$body (from PHP) = alert($("#body").Editor("getText"))(from JS);
}
Thank you in advance for help.
On the plugin page you referenced, I see this is one of the recommendations. Capture the value you want when the click button is pressed, before the form submits.
Add a script to your form submit to put the texteditor content into this element
<form onsubmit='return getItReady()'>
Add an element to the form you'll use as a proxy element and keep it hidden, something like
<textarea id='txtEditorContent' name='txtEditorContent' style='visibility:hidden;height:0px' tabindex="-1"></textarea>
Then add the script to prepare it
<script>
function getItReady() {
console.log('The content:', $('#body').Editor("getText"));
$('#txtEditorContent').val($('#body').Editor("getText"));
return true;
}
</script>
Then in your PHP, it will come through as $_POST['txtEditorContent'].
I am trying to display the data i retrieve from the database but it is not being displayed. I have a function in the file getComments.php called "getComments(page)" page is just a integer parameter to choose that database. and as you can see that i need to call this function to print the users comments. I am trying to use "load" but it is not being successful i just want to call this function to load the comments on the page. thank you in advance.
<?php
use TastyRecipes\Controller\SessionManager;
use TastyRecipes\Util\Util;
require_once '../../classes/TastyRecipes/Util/Util.php';
Util::init();
function getComments($page){
echo "<br><br>";
$controller = SessionManager::getController();
$controller->getComments($page);
SessionManager::setController($controller);
}
and in my web page where i want to display it using java script, i tried the following
<div class="page" id="comments">
<p class="style">Comments</p>
<button class="btn" id="load-comments">See Previous Comments</button><br>
<br><br>
<?php
if(isset($_SESSION['u_id'])){
echo " <input type='hidden' id='uid' value = '".$_SESSION['u_uid']."'>
<input type='hidden' id='date' value = '".date('Y-m-d H:i:s')."'>
<textarea id='message'></textarea><br>
<button class = 'btn' type = 'submit' id = 'submitCom'>Comment</button>";
}
else{
echo "<p>Please log in to comment</p>";
}
?>
</div><br>
<script>
$(document).ready(function(){
$("#load-comments").click(function(){
document.getElementById('#comments').innerHTML =
$("#comments").load("../extras/getComments.php", getComments(1));
});
});
</script>
Just change your click handler to this:
$("#load-comments").click(function(){
$("#comments").load("../extras/getComments.php", { page: 1 }); //i also added where the elements are loaded
});
and in getComments.php (if practical, otherwise you might need to create a new PHP file which calls the getComments() function and call that from the click handler instead) add something like:
if (isset($_POST['page'])) {
getComments($_POST['page']);
// do any other necessary stuff
exit;
}
so this function seems to be confusing me.
echo"
<td style='font-size:12px;width:150px;'><div style=\"overflow-y:auto; max-height:250px; width:200px;\">
{$row['Notes']} </div><br /><center><br />
<button onclick=\"myFunction('{$row['ID']}','$rowID')\">Add Note</button>
<form action=\"http://calls.fantomworks.com/functions/notes.php\" id='notesForm' name='notesForm' method='post'>
<input type='hidden' id='notesID' name='notesID' />
<input type='hidden' id='rowID' name='rowID'/>
<input type='hidden' id='notes' name='notes' />
</form>
</center>";
Calls this javascript
<script language="JavaScript" type="text/javascript">
function myFunction(ID,rowID)
{
var x;
var ID = ID;
var rowID = rowID;
var note = prompt("Customer Note","Write your customer note here...");
if (note != null) {
document.getElementById("notes").value = note;
document.getElementById("notesID").value = ID;
document.getElementById("rowID").value = rowID;
document.getElementById("notesForm").submit();
}
else{
return false;
}
}
</script>
and ends up at this php page
$notesID = $_POST['notesID'];
$rowID = $_POST['rowID'];
$note = $_POST['notes'];
//Redirect to browser
header("Location: ./index.php#row_$rowID");
The only problem is that the rowID does not seem to be making it through and generates links ending like "index.php#row_"
I can't make sense of why rowID isn't coming through but NotesID and notes are.
As you can see from the debug the value is there.
Thanks for any thoughts or suggestions!!
The script at "http://calls.fantomworks.com/index.php" is being POSTed to by your javascript function - thus the variable that you seek ought to be available through the $_POST global.
Try changing
header("Location: ./index.php#row_$rowID");
To
header("Location: ./index.php#row_{$_POST['rowID']}");
Incidentally, the three variables you define in the javascript function seem redundant and could be removed by the looks of things, namely:-
var x;
var ID = ID;
var rowID = rowID;
Have had a closer look since posting original ( and hadn't noticed the assignment of posted vars by the #OP ) - there are hundreds of forms on the page in question - same IDS used from row to row to row. IMHO - this is definitely NOT the way forward - You could have just one form for "Add Note" as you dynamcally set the value by clicking the button. It does appear that the relevant vars ( rowID etc ) are being set and assigned to the button that calls the javascript so theoretically you could have just one form that is used to post to "notes.php" but have this button on each row.
In terms of a general critique / suggestions
The page is very slow to load - due in part to there being hundreds of complex table row layouts, and by the looks of things a form for every button - then there are the images which themselves are fullsize but could really be ( and should be ) thumbnails. The number of forms could be drastically reduced if each button were to dynamically assign the variables like the one in the question above.
I created an instant search similar to google search using JQuery.
Q1.
The post to search.php using search function searchq() then print out the returned result works fine, but the createq() function doesn't work at all, it didn't triggered when I using alert() to test, any ideas on how to fix it so the variable txt could be post to create_object.php (which has been post successfully to search.php).
Q2
I want to create a function that allow the user to direct to the first search result(which is anchored with an url) when the enter is pressed, any idea how to achieve this? I tried something but it messed up.
Note that I didn't include the connect to database function here. Coz I think the database username and password setting would be different to yours.So please create your own if you want to test it. The mysql is set with a table is called "objects", and it has one column named "name".
Thanks in advance!
<html>
<!-- google API reference -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- my own script for search function -->
<center>
<form method="POST">
<input type="text" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
<input type="submit" value=">>">
<div id="output">
</div>
</form>
</center>
<!-- instant search function -->
<script type="text/javascript">
function searchq(){
// get the value
var txt = $("input").val();
// post the value
if(txt){
$.post("search.php", {searchVal: txt}, function(result){
$("#search_output").html(result+"<div id=\"create\" onclick=\"creatq()\"><br>Not found above? Create.</div>");
});
}
else{
$("#search_output").html("");
}
};
function createq(){
// allert for test purpose
alert("hi");
$.post( "create_object.php",{creatVal:txt} );
}
</script>
</html>
PHP file (search.php)
<?php
if(isset($_POST["searchVal"])){
//get the search
$search=$_POST["searchVal"];
//sort the search
$search=preg_replace("#[^0-9a-z]#i","",$search);
//query the search
echo "<br/>SELECT * from objects WHERE name LIKE '%$search%'<br/>";
$query=mysqli_query($conn,"SELECT * from objects WHERE name LIKE '%$search%'") or die("could not search!");
$count=mysqli_num_rows($query);
//sort the result
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output.="<div><a href='##'".$object_name."</a></div>";
}
}
echo $output;
}
?>
php file (create_object.php)
<?php
if(isset($_POST["createVal"])){
$name=$_POST["createVal"];
var_dump($name);
}
?>
Two questions in one!
Q1: The problem appears to be a misspelling in the onclick function:
onclick=\"creatq()\"
should be
onclick=\"createq()\"
Q2: Pressing enter will submit the form, so you use the submit handler to catch the enter press then redirect:
$(function() { //shorthand document.ready function
$('form ').on('submit', function(e) { //use on if jQuery 1.7+
e.preventDefault(); //prevent form from submitting
$url = $('#search_output div:first a').attr('href'); // find first link
window.location.href = $url; // redirect
});
});
(credit to this answer for most of the work)
This function get a parameter and pass it to this this
$.arte({'ajax_url':'getRealTimeUpdates.php?activity_id='+id, 'on_success':updateLiveUpdates}).start();
[where this line of code feches the upadtes from server each a
specific time period as a jaxed loop]
when I call the function showLiveUpdates(id) with some parameter for example id=5, this line remember id=5 for all this function calls even different parameters !
I want each time I call the function with different id this line of code get the new id
{{ where arte is JQuery plug-in : Ajax Real Time Extension, this is its website click here}}
js code :
function showLiveUpdates(id)
{
//$.arte().stop();
$("#liveUpdates").fadeIn("slow");
$("#liveUpdates").html("");
$("#liveUpdates").append("<div><textarea rows='2' cols='49' id='txtLiveUpdates'></textarea></div>");
$("#liveUpdates").append("<div><input type='button' id='btnliveUpdatesShare' value='share' onClick='addComment("+id+","+getCookie("userId")+")'></div>");
last="";
$.arte({'ajax_url':'getRealTimeUpdates.php?activity_id='+id, 'on_success':updateLiveUpdates}).start();
}
I call it like this:
<input type='button' onClick='showLiveUpdates(<? echo $_GET["id"];?>)' />
edit
function updateLiveUpdates(data)
{
if(data!=last)
{
$("#liveUpdates").append("<div id='updates"+ii+"' style='display:none' >"+data+"</div>");
$("#updates"+ii).fadeIn();
last=data;
}
ii++;
}
getRealTimeUpdates.php
<?php
require("database.php");
$activity_id=$_GET["activity_id"];
$query = "SELECT id,comment from comments where activity_id=$activity_id order by id desc limit 0,1";
echo $query;
$result = mysql_query($query);
$row = #mysql_fetch_assoc($result);
echo $row["id"]."-".$row["comment"];
?>
How about this? Creating a function scope for the id variable:
function createData(id) {
return function () {
return {
'ajax_url':'getRealTimeUpdates.php?activity_id='+id,
'on_success':updateLiveUpdates
}
}
}
for (var id = 0; id < 5; i++) {
$.arte(createData(id)()).start();
}
EDIT 1 Just looked at the code at http://code.google.com/p/arte/source/browse/trunk/jquery-plugin-arte.js.
There is a shared _config property that gets overwritten, and the URL used is always _config['ajax_url'].
EDIT 2 I've posted a demo of this here to demonstrate your issue. So it looks like you cannot call this function multiple times, because the internal state is shared.
EDIT 3 I've updated a jsfiddle with a rough attempt at making this code work as you desire. The demo is here. The new code keeps no state and (seems to) successfully run 5 update loops before terminating them after 3 seconds.