Update JS/JQuery variable based on the input of a html input - javascript

I currently have this javascript/ajax request for my advanced search page
<script>
// window.setInterval(function()
// {
$(function ()
{
var SearchTerm = '<?php echo $_POST['Search']; ?>';
$.ajax({
url: 'Ajax/AjaxAdvSearch.php?SearchTerm='+SearchTerm, dataType: 'json', success: function(rows)
{
$('#output').empty();
for (var i in rows)
{
var row = rows[i];
var id = row[0];
var FunctionName = row[1];
$('#output').append("<a href='Page.php?ID="+id+"'>"+FunctionName+"</a><br>");
}
}
});
});
// }, 5000);
</script>
The $_POST['Search']; is obtained from a HTML textarea:
<textarea name='Search' style='width: 100%; height: 150px;'></textarea><br>
I want to dynamically update my javascript var each time the user types into the textarea, without the user having to press the submit..
so whilst the user is typing, the var SearchTerm is dynamically updated each time the textarea is updated with content.
Could anyone provide some assistance?

Use the .change() method in jQuery
var variableToUpdate = '';
$('#Search').change(function() {
variableToUpdate = $(this).val();
// call your search from within if you want
});
For search-as-you-type tutorials and plugins...
http://dbachrach.com/blog/2007/04/spotlight-like-search-as-you-type-with-css-ajax-js/
http://www.jquery4u.com/plugins/14-jquery-live-search-plugins/

Let me provide you an example
<html>
<head><style>
</style>
<script>
var DataCon;
function UpdateDIV(){
document.getElementById('updater').innerHTML=DataCon;
}
</script>
</head><body>
<div id="updater">
</div>
<textarea onkeydown="DataCon=this.value;UpdateDIV()"></textarea>
</body>
</html>
And here you can see, as you type a global variable updates and along with it, to check its working a UpdateDIV function also given which updates the div with id updater...
Now just assign certain vars and get your job done

Related

How to Display Specific value when I click Specific button

When I click all the button output will be same (i.e 1).I want to display specific value of specified button for EXAMPLE:- When I click button 1 then It must display output as 1 and when I click 2 it must display output as 2.please help me.
<?php
for ($i=0; $i < 10 ; $i++) {
echo '<br><button value="'.$i.'" class="my_remark_btn">'.$i.'</button>';
}
?>
<script type="text/javascript">
$('.my_remark_btn').click(function(){
remark_aftr_click();
});
function remark_aftr_click(){
var k = $(".my_remark_btn").val();
$.ajax({url: "my_remark_act.php",
cache: true,
type: "POST",
data: {go:k},
success: function(data_remark_mi){
alert(data_remark_mi);
}
});
}
</script>
my_remark_act.php:-
<?php echo $_POST['go']; ?>
$('body').append("<button data-value='val' class='my_remark_btn'>val</button>")
$(document).on('click', '.my_remark_btn', function() {
alert($(this).attr('data-value'))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Button has no value.
Use data attribute like data-value.
Get it like $(this).attr('data-value') using this context for clicked button.
Use event delegation for dynamically added elements.
Try This Example.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$( document ).ready(function() {
$("button").click(function() {
alert(this.id); // or alert($(this).attr('id'));
});
});
</script>
</head>
<body>
<button id="some_id1"></button>
<button id="id2"></button>
<button id="id3"></button>
<button id="id4"></button>
<button id="id5"></button>
</body>
</html>
You can use JQuery. try the below code.
// this will fire for all button having class '.my_remark_btn'
$('.my_remark_btn').click(function(){
// using $(this) you will get the current element
var value = $(this).val();
console.log(value);
});
In you code you are accessing value by var k = $(".my_remark_btn").val(); , This will only return value of the first button with class my_remark_btn.
Have a try of this
jQuery
$('.my_remark_btn').click(function(){ // when a button is clicked
var value = $(this).value; // get the value of that specific button
alert(value); // alert the value to the page (to make sure it is correct)
remark_aftr_click(value); // run function, with value as a parameter
});
function remark_aftr_click(val){
$.ajax({
url: "my_remark_act.php",
cache: true,
type: "POST",
data: {go: val}, // post data to Ajax with CORRECT value
success: function(data){
alert(data); // alert returned data
}
});
}
Why your code was not working:
When you were retrieving the value of .my_remark_btn before, you were only ever getting the value of the first element with that specific class.
How you can get it to work:
Instead, you need to pass the value as a parameter within your function (while using this as a selector to get the value of that specific button).
Hope this helps :-)
You need $(this).attr("value") like below:-
<script type="text/javascript">
$('.my_remark_btn').click(function(){
var k = $(this).attr("value");
$.ajax({url: "my_remark_act.php",
cache: true,
type: "POST",
data: {go:k},
success: function(data_remark_mi){
alert(data_remark_mi);
}
});
});
</script>
Example:-
$('.my_remark_btn').click(function(){
var k = $(this).attr("value");
alert(k);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button value ="1" class="my_remark_btn">1</button><br>
<button value ="2" class="my_remark_btn">2</button>

jQuery / ajax data container + organization

My dad and I are working on a project where we'd like to create a script that calls in data when a number is submitted into a form. For example, when you type in your ID number then press ENTER or SUBMIT, the form will print/display information. This is a project for school, so when a student submits their ID number it will read their first period class, for example.
I have the following script code to set up the form:
<form id="firstPeriod" action="firstPeriod.html">
<p>Find your first period.</p>
<p><label>Student no.: <input type="text" name="studentNo"></label></p>
<p><input type="submit" value="Find it"></p>
<p id="result"></p>
</form>
<script type="text/javascript">
$(function() {
$('#firstPeriod').submit(function() {
$.ajax({ // Send the request behind the scenes
url: $(this).attr('action'), // Send it here
data: $(this).serialize(), // With this student no.
success: function(data) {
$('#result').html(data); // Display the resulting HTML
},
error: function(jqxhr, status, error) {
console.log(error);
$('#result').html('No results found. Please check your number and reenter'); // Notify an error
}
});
return false; // Prevent the normal form submission
});
});
My question is, what would be the best way to organize the data? An array, HTML, etc.? There are quite a lot of ID numbers and are currently set up in an HTML table, but that doesn't seem to work in calling the information. And I'd like for the data to be specific. So when a specific ID number is typed in, it reads a specific answer. Right now my problem is when I type in a number it reads several classes.
If there are any suggestions/advice/other posts that could help me, I'd be grateful. I have solid HTML, CSS experience but I'm still learning JS and jQuery so this is a little new for me. Thanks!
Edit, Updated
Note, added value attribute to input type="text" element
<input type="text" name="studentNo" value="" />
substituted .submit() for .on("click") at input type="submit" element
Two possible approaches could be 1) using HTML to store data, .load() to retrieve fragment identifier within html file; or 2) storing data using JSON, retrieving file using php
html at firstPeriod.html
<div id="0">data 0</div><div id="1">data 1</div>
javascript
$(function() {
var form = $("#firstPeriod");
$("input[type=submit]").on("click", function(event) {
event.preventDefault();
event.stopPropagation();
var data = form.serializeArray();
// where `data[0].value` is `id`; e.g.; `0`
var id = data[0].value;
$("#result").load(form.attr("action") +" #"+ id)
})
})
plnkr http://plnkr.co/edit/4onHf9jlJTyDei1zo9IC?p=preview
JSON
0.json
{
"0":"<div id='0'>data 0</div>"
}
1.json
{
"1":"<div id='1'>data 1</div>"
}
javascript
$(function() {
var form = $("#firstPeriod");
$("input[type=submit]").on("click", function(event) {
event.preventDefault();
event.stopPropagation();
var data = form.serializeArray();
// where `data[0].value` is `id`; e.g.; `0`
var id = data[0].value;
$.post("data.php", {id:id}, function(result) {
$("#result").html(result[id])
}, "json")
})
})
php
<?php
if (isset($_POST["id"])) {
$id = $_POST["id"];
$file = $id . ".json";
if (file_exists($file)) {
$jsondata = file_get_contents($file);
$id_data = json_decode($jsondata, true);
echo json_encode($id_data);
};
}

jQuery updates DOM, browser does not

I am working on a project where for example field number 3 on the webpage should be updated with values from a database when a user enters data into field number 1. This already works fine without any problems.
But if the user modifies field number 3 first and field number 1 at a later time, just the DOM gets updated (as I can tell from Firebug) but there isn't any visible change on field number 3 to the user.
I created a very basic version of this problem and still I am not able to tell what's wrong here.
HTML
<div id="container1">
<textarea id="container1.1">Entry 1.1</textarea>
<textarea id="container1.2">Entry 1.2</textarea>
<textarea id="container1.3">Entry 1.3</textarea>
</div>
jQuery
$(document).ready(function() {
$('textarea').change(function() {
var clickedObject = $(this);
var id = $(this).attr('id').substr(9);
var value = $(this).val();
var dataString = "id=" + id + "&value=" + value;
$.ajax({
type: "POST",
url: "update.php",
data: dataString,
cache: false,
success: function(Result)
{
if(Result == '-')
{
console.log('Nothing to do');
} else {
clickedObject.next().next().html(Result);
}
}
});
});
});
PHP
<?php
if ($_POST['id'] == '1.1') {
echo 'Modified string';
} else {
echo '-';
}
?>
You must set values of textarea by .val() method, instead of html().
And maybe it will be more descriptive if you will use only one id of textarea that should call request on changes.

Multiple Ckeditor using javascript Class

I try to use CKEDITOR to edit my website content. But there are a lot of CKEDITOR used, I put all the javascript functions in a Class, but not sure how it works. Anybody could help to see which part i need to change?
There are 2 files associated with my problems:
1) test.php (main page for update the content of website using Ckeditor)
2) CmsAjaxClass.js (Class contains all operation of Ajax and Ckeditor)
test.php
<!DOCTYPE html>
<html>
<head>
<title>A Simple Page with CKEditor</title>
<!-- Make sure the path to CKEditor is correct. -->
<script src="ckeditor/ckeditor.js"></script>
</head>
<script src="assets/js/jquery.js" type="text/javascript"></script>
<body>
<div>
</div>
<form method="post" action="test2.php">
<h1>Editor1</h1>
<textarea name="editor1" id="editor1"><?php
include_once('php/get_cms.php');
echo get_cms(1);
?></textarea>
_____________________________________<br/>
<h1>Editor2</h1>
<textarea name="editor2" id="editor2"><?php
include_once('php/get_cms.php');
echo get_cms(2);
?></textarea>
<script src="assets/js/CmsAjaxClass.js"></script>
<script>
var editor1 = new CmsAjaxClass("editor1", document.getElementById("editor1").value) ;
var editor2 = new CmsAjaxClass("editor2", document.getElementById("editor2").value) ;
</script>
</form>
</body>
</html>
CmsAjaxClass.js
function CmsAjaxClass(editorName, seteditorData)
{
//For nested Class usage
var myClass = this;
//Declare editorName to keep the editor name
this.editorName = editorName;
//Declare dataString to keep the data retrieve from editor
this.seteditorData = seteditorData;
//Function to update the CKEDITOR before it is parsed
this.updateCkeditor = function() {
for ( instance in CKEDITOR.instances )
{
CKEDITOR.instances[instance].updateElement();
}
}
//Function to run the AJAX if the element is blured
this.onBlur = function() {
//Update the Ckeditor data first before retrieve edited data
myClass.updateCkeditor();
//Retrieve edited data from HTML DOM
myClass.seteditorData = seteditorData;
//Call AJAX function to pass the value
myClass.startAjax();
}
//Catch the focus and blur status of inline toolbar
this.editor = CKEDITOR.inline( editorName, {
on: {
//focus: onFocus,
blur: myClass.onBlur,
}
});
//Declare which cms section we currently editing, parse the integer from the id of the textarea
this.setcmsID = parseInt(editorName.replace("editor",""));
//Create an AJAX function
this.startAjax = function() {
alert(this.seteditorData);
$.ajax
({
type: "POST",
url: "test2.php",
data: {editorData: this.seteditorData, cmsID: this.setcmsID},
cache: false,
beforeSend: function()
{
//Loading
},
success: function(result)
{
alert("Successfully updated!");
}
});
}
}
I dont understand your issue clearly.
But still these lines looks like a typo
<script>
var editor1 = new CmsAjaxClass("editor1") ;
var editor1 = new CmsAjaxClass("editor2") ;
</script>
I guess you meant editor2 in second line instead of overwriting editor1
this.onFocus() = function() {
//The CKEDITOR element is focused
}
I guess you want this.onFocus= function(){
You can keep a reference to the editor in your class
this.editor = CKEDITOR.inline( editorName, {
on: {
blur: this.onBlur,
}
});
which can facilitate
this.editor.on('blur', function(){});
this.editor.updateElement();
Thanks #sabithpocker and #DaniƫlKnippers
Finally it works, the Ckeditor update database when "blur" action is triggered.
test.php
<!DOCTYPE html>
<html>
<head>
<title>A Simple Page with CKEditor</title>
<!-- Make sure the path to CKEditor is correct. -->
<script src="ckeditor/ckeditor.js"></script>
</head>
<script src="assets/js/jquery.js" type="text/javascript"></script>
<body>
<div>
</div>
<form method="post" action="test2.php">
<h1>Editor1</h1>
<textarea name="editor1" id="editor1"><?php
include_once('php/get_cms.php');
echo get_cms(1);
?></textarea>
_____________________________________<br/>
<h1>Editor2</h1>
<textarea name="editor2" id="editor2"><?php
include_once('php/get_cms.php');
echo get_cms(2);
?></textarea>
<script src="assets/js/CmsAjaxClass.js"></script>
<script>
var editor1 = new CmsAjaxClass("editor1") ;
var editor2 = new CmsAjaxClass("editor2") ;
</script>
</form>
</body>
</html>
CmsAjaxClass.js
function CmsAjaxClass(editorName)
{
//For nested Class usage
var myClass = this;
//Declare editorName to keep the editor name
this.editorName = editorName;
//Declare dataString to keep the data retrieve from editor
this.seteditorData;
//Function to update the CKEDITOR before it is parsed
this.updateCkeditor = function() {
for ( instance in CKEDITOR.instances )
{
CKEDITOR.instances[instance].updateElement();
}
}
//Function to run the AJAX if the element is blured
this.onBlur = function() {
//Update the Ckeditor data first before retrieve edited data
myClass.updateCkeditor();
//Retrieve edited data from HTML DOM
myClass.seteditorData = document.getElementById(editorName).value;
//Call AJAX function to pass the value
myClass.startAjax();
}
//Catch the focus and blur status of inline toolbar
this.editor = CKEDITOR.inline( editorName, {
on: {
//focus: onFocus,
blur: myClass.onBlur,
}
});
//Declare which cms section we currently editing, parse the integer from the id of the textarea
this.setcmsID = parseInt(editorName.replace("editor",""));
//Create an AJAX function
this.startAjax = function() {
alert(this.seteditorData);
$.ajax
({
type: "POST",
url: "test2.php",
data: {editorData: this.seteditorData, cmsID: this.setcmsID},
cache: false,
beforeSend: function()
{
//Loading
},
success: function(result)
{
alert("Successfully updated!");
}
});
}
}

Form variable does not refresh with ajax call

I'm building a simple email sending form and wanted to make it with ajax. The form submits correctly the first time but if you make any subsequent changes to the text in the form and then submit again then jquery does not pick up on the changes and posts the old data. Whats going on?
<script type="text/javascript">
var $j = jQuery.noConflict();
$j(document).ready(function() {
var submit_url = "mail_submit.php";
var send_email = $j("#sendemail");
send_email.click(function() {
var form = $j("#post");
$j.post(submit_url, form.serialize(), function(data) {
alert(data);
});
});
});
It's working just fine.
Now I would prefer calling the submit event on the form itself, but if you are using a submit input type, remember to return false;
I ran into this problem again.
To solve it you need to use tinyMCE.triggerSave();
The method is outlined here http://maestric.com/doc/javascript/tinymce_jquery_ajax_form
My final code is:
<script type="text/javascript">
var $j = jQuery.noConflict();
$j(document).ready(function() {
var submit_url = "mail_submit.php?action=";
var actions = $j("#sendEmail, a#previewEmail, a#saveEmail, a#updateEmail");
var loading = $j("img#ajax-loading");
var status = $j("span#post-status-display");
actions.click(function() {
tinyMCE.triggerSave();
var form = $j("#post");
var action = $j(this).attr("id");
var update_div = $j("#update-div");
loading.show();
$j.post(submit_url + action, form.serialize(), function(data){
update_div.html(data);
update_div.fadeIn();
loading.hide();
});
});
});

Categories