I'm using JQuery, CakePHP, and Mysql in my application.
I'm having a code like below in which instructions are a Textbox that when I type it will be shown in the Display panel.
$(".TextFieldSettings #instructions").keyup(function (){
instr=$(".TextFieldSettings #instructions").val();
$("#displayPanel .fieldInstructions"+counter).html(instr).show();
});//Text field instructions keyup
This Code Works well.
Edit:
If I change the value in the Textbox instructions, the keyup value must be shown in the Display Panel. Mean while I need the final changed value in the instr to insert into the database.
How can I do so?
You can delay your operation :
$(".TextFieldSettings #instructions").keyup(function (){
setTimeout(function () {
var instr=$(".TextFieldSettings #instructions").val();
$("#displayPanel .fieldInstructions"+counter).html(instr).show();
}, 1);
});//Text field instructions keyup
That way, when the function is executed, the input value has been updated with the keypress.
Depending on how much content your instructions is holding/how frequently keypressing, i think updating the database every keyup is a bit overkill. Maybe update the database every 5 seconds or something? with each keypress triggering/resetting a setTimeout function.
Also, you can replace your call to pull out the text value with just $(this);
$(".TextFieldSettings #instructions").keyup(function (){
var instr = $(this).val();
$("#displayPanel .fieldInstructions"+counter).html(instr).show();
// Update database
$.ajax({
method: 'POST',
url: 'path/to/a/script_file/executing_the_sql.ext',
data: { 'str': escape(instr.replace(/\n/g,'<br />')) },
success: function(){},
error: function(e){ alert(e.responseText); }
});
});//Text field instructions keyup
Related
I have a large form on my website that I want to be able to autosave to a database as the user is filling it out. Almost identical to how google drive works when typing a document.
I am trying not to have a function that runs every X seconds but rather a function that runs when the user has taken a break in typing. So, if the user has not typed in 1 hour but is still on the page, it doesn't keep pushing save requests.
This is all I have so far which is a basic javascript form submit.
$("#page1Form").submit(function(event){
event.preventDefault();
$changesSaved.text("Saving...");
var url = "/backend/forms/page1-POST.php";
$.ajax({
type: "POST",
url: url,
data: $("#page1Form").serialize(),
success: function(data) { $changesSaved.text(data); }
});
return false;
});
Debounce the textarea change.
Demo: jsFiddle
Put your ajax call in the saveToDB() function. These event names('input propertychange change') will trigger on any form element change such as radio buttons, inputs, etc.
var timeoutId;
$('#the-textarea').on('input propertychange change', function() {
console.log('Textarea Change');
clearTimeout(timeoutId);
timeoutId = setTimeout(function() {
// Runs 1 second (1000 ms) after the last change
saveToDB();
}, 1000);
});
function saveToDB()
{
console.log('Saving to the db');
}
Here is a full demo showing you how to debounce a full form and use ajax to send the data and then return the status (Saving, Saved, etc).
Demo full form and ajax: jsFiddle
I know that this question is old, but I would like to include a code that I like the most. I found it here:
http://codetunnel.io/how-to-implement-autosave-in-your-web-app/
Here is the code:
var $status = $('#status'),
$commentBox = $('#commentBox'),
timeoutId;
$commentBox.keypress(function () {
$status.attr('class', 'pending').text('changes pending');
// If a timer was already started, clear it.
if (timeoutId) clearTimeout(timeoutId);
// Set timer that will save comment when it fires.
timeoutId = setTimeout(function () {
// Make ajax call to save data.
$status.attr('class', 'saved').text('changes saved');
}, 750);
});
It saves after the user stops writing for more than 750 milliseconds.
It also has a status letting the user know that the changes have been saved or not.
Try Sisyphus.js https://github.com/simsalabim/sisyphus. It persists the form data in the browser's local storage and is robust against tabs closing, browser crashes, etc...
I want to trigger the “autocomplete” event from the sorce, and to send the value to set in the textBox.
I want it will be like a user typing the value and trigger the autocomplete,
I tried to look alot but all the examples I found didn't send the value,
and I need to send the value!!
This example dosn't help me, Because I need the request (like someone type it)
$("#CompanyList").autocomplete({
source : yourSource,
change : yourChangeHandler
});
$("#CompanyList").data("autocomplete")._trigger("change");
I hope you Understand me.
If I understand (I'm not sure).
You have to go costum:
Use:
$('.input_text_forms').keyup(function(event){ });
That fires:
var data = $('#lang_pass_threw').val();
$.post('auto_fill.php', { data: data }, function(response) { });
When the request is returned:
var arr = string.split("");
Now call to a Timeout function and set the result as the value...
Here is an example: jsfiddle
This example is a bit buggy, there is a cursor position to set.. and a backspace event to undo the autocomplete etc, let me know if its what you need and i'll tune this script a bit.
Im running into a problem where i have an ajax driven page that is drawn when a user selects something from a simple drop down:
<select id = "selectdepartment">
<option id = "default">Select an option...</option>
....
</select>
and the remainder of the page is drawn using the jquery .change() :
$('#selectdepartment').change(function(){
});
Which then runs some ajax to php script. everything works great, the problem is when i submit a form that was drawn with ajax (using $_SERVER['PHP_SELF'];), the data gets submited, the page reloads, and the page is cleared but the select box is still left where it was. The user has to move to a different option then back to the one the selected originally to re-fire the .change(). that sucks.
I could fix this by passing a php variable in all of my forms, then checking to see the variable set on every page load and if it is draw the page parts then, but this would lead to pretty messy code and it's less than desirable.
There has to be a way to do this with the jquery library, though my knowledge of the javascript language in general is not what i would like it to be. If anyone has any helpful hints please share, dont do it for me though, i wont learn that way :)
edit: code with .trigger
$('#selectdepartment').change(function(){
var department = $('#selectdepartment').val();
var day = $('#data').data('day');
var month = $('#data').data('month');
var year = $('#data').data('year');
//alert (department);
if(department === "Select an option..."){
$('.hiddenuntildepartmentisselected').css({"display":"none"});
}
else{
$('.hiddenuntildepartmentisselected').css({"display":"block"});
}
showpoints(department);
drawpointstable(department, day, month, year);
displaytheuseresforselecteddepartment(department, '');
$('#sendthedepartment').val(''+department+'');
$('#hiddendepartmentidforaddinganewpoint').val(''+department+'');
}).trigger('change');//end run functions
You can use the .trigger() function to immediately trigger the change event handler when the page has loaded:
$('#selectdepartment').change(function() {
// code here
}).trigger('change');
Or if you need to call it elsewhere via JavaScript/jQuery:
$('#selectdepartment').trigger('change'); // or just .change() as a shorthand
Updated
Your button for the form could make use of the onClick attribute, which would invoke a method to parse the form fields and post the data to your php script via .ajax().
In the success event method you then check any flags you need to and modify the element as you desire if needed.
Basic example:
Inside of .ajax():
...
url: 'xxx.xxx.xxx',
async: true,
type: 'POST',
dataType: 'html',
data: JSON.stringify( form_fields ),
beforeSend: function()
{
// Pre send stuff, like starting a loading gif
},
success: function( data, textStatus, xhr )
{
// Be sure you load the page with the content first
$( '#containing-div' ).html( data );
// Do your check here, and modify your element if needed here
if( flagtocheck === 'xxx' )
{
// Modify the element in question...
}
// I call a custom method termed `.ctrls()` here that makes any
// adjustments to the DOM once its loaded/updated.
},
error: function( xhr, textStatus, errorThrown )
{
}
Of course, you'll want to set flagtocheck appropriately in your case.
Hope that helps!
Note regarding edit
This post was edited to be a little more descriptive and more easily understood. Since the person asking the question is already using the .ajax() method, the success event method is the ideal place for doing what the person asking the question is requesting. It is 1 less method invocation to directly modify the element there than using it to call .trigger() or .change() which then also directly modifies the element.
I have a jQuery Ajax request, that I want to call with text input, and so I nested it inside keyup(function(). This works fine.
$("#text_box").keyup(function() {
//AJAX REQUEST
});
But this behaves buggy sometimes. When I input some text very fast, I am getting results for input word with some last letters of the original input word omitted (may be some fault with browser). I want the ajax request to be sent when there is no input activity for a second, I mean, if I input text very fast and rest for a second (means I made the input). How can I do this?
It sounds as if you get results from a previous ajax call. Use a timer with setTimeout and clearTimeout.
var timer = null;
$("#text_box").keyup(function() {
if(timer) {
clearTimeout(timer);
}
timer = setTimeout(someFunction, someDelay);
});
Where someFunction is a function which does your ajax call and someDelay is the delay you want to wait before doing the call, after the user has typed, in ms.
As you are already using jQuery you could use the debounce plugin from Ben Aleman.
Example from the page
// Bind the not-at-all debounced handler to the keyup event.
$('input.text').keyup( text_1 );
// Bind the debounced handler to the keyup event.
$('input.text').keyup( $.debounce( 250, text_2 ) ); // This is the line you want!
omg. for somebody who will search in 2014...
function sendAjax() {
setTimeout(
function() {
$.ajax({
url: "url.php",
type: "POST",
data: data,
success: function(data) {
$("#result").html(data);
}
});
}, 2000);
}
<input onkeyup="function()">
I'm unsure of the best practice for modifying the DOM based on an ajax response. I'll try to let the code do the talking because it's hard to explain.
// page has multiple checkboxes
$("input[type='checkbox']").live('click', function {
var cb = $(this); // for the sake of discussion i need this variable to be in scope
$("form").ajaxSubmit({ dataType: "script" });
}
The server sends a response back, and the js gets eval'd and that means "cb" is out of scope.
What I've done so far is create a couple of helper functions:
var target = undefined;
function setTarget(val) {
target = val;
}
function getTarget() {
return target;
}
And that turns the first snippet of code into this:
// page has multiple checkboxes
$("input[type='checkbox']").live('click', function {
setTarget($(this));
$("form").ajaxSubmit({ dataType: "script" });
}
Then on the server's response I call getTarget where I need to. This seems hackish... Any suggestions?
It's unclear what you're actually trying to do, but I feel like you want to be looking at the success parameter for that AJAX call. The success callback function should execute in parent scope and do what you're looking for.
See 'success' on this page in the jQuery docs.
So what you are trying to do is get the form to submit the content via ajax whenever the user checks/unchecks a checkbox? And because there are several checkboxes, you need to find out which one triggered the submit, so you can change its value to whatever is stored on the server?
If you submit the entire form everytime, why don't you reply with all the checkboxes values, and then change each and every one of them? If not, get the server to reply with the id and the value of the checkbox, then use jquery to find the checkbox with that ID and then change it's value.
How about:
jQuery(function($) {
// give it scope here so that the callback can modify it
var cb,
cbs = $('input[type="checkbox"]');
cbs.live('click', function {
// taking away var uses the most recent scope
cb = $(this);
// disable checkboxes until response comes back so other ones can't be made
cbs.attr('disabled', 'true'); // 'true' (html5) or 'disabled' (xhtml)
// unless you are using 'script' for something else, it's best to use
// a callback instead
$('form').ajaxSubmit({
success : function(response) {
// now you can modify cb here
cb.remove(); // or whatever you want
// and re-enable the checkboxes
cbs.removeAttr('disabled');
}
});
}
});