I have a few radio buttons in a page and I need to save their values or whatever value is selected to a file.
Here is a sample code:
<input name="select" type="radio" value="a" />
<input name="select" type="radio" value="b" />
<input name="select" type="radio" value="c" />
<input name="select" type="radio" value="d" />
Whenever the user selects one I need it saved / appended into a file.
Possible?
UPDATE:
Tried this:
<script>
$(document).ready(function () {
$("input[name='select']").change(function(e) {
e.preventDefault();
$.post("zzz.html", { selectedValue : $(this).val() }, function(response) {
// do something with server response
alert('saved');
});
});
});
</script>
Result: No Result. Nothing created / Nothing Saved.
$("button").click(function(){
$.post('save_values.php', $("form").serialize(), function(){
alert('saved');
});
return false;
});
If you want to save the the text to a file on your server, then you can use php.
This example checks to see if a file name has been set, and the text to log has also been set.
It opens the file and appends text to it by specifying "a+".
So visiting
http://websitename.com/myfile.php?filename=test.txt&log=string to write
Will create and append the text to that file on your server.
If then you want to provide the textfile to the user to download you can just use
http://websitename.com/test.txt
This code is untested
<?php
if(isset($_GET["filename"]) == true && isset($_GET["log"]) == true){
$fp = fopen($_GET["filename"], "a+");
if($fp !== null){
fputs($fp, $_GET["log"] . "\r\n");
fclose($fp);
}
}
?>
jquery get method
$.get("myfile.php", { filename: "text.txt", log: "string to write" });
Assuming you want to save the selected value every time the radio group has been changed:
$("input[name='select']").change(function(e) {
e.preventDefault();
$.post("foo.html", { selectedValue : $(this).val() }, function(response) {
// do something with server response
});
});
If it is on server you can submit to a servlet and open a file and write on the file.
if it is in client side you can try using this jQuery plugin http://jquery.tiddlywiki.org/twFile.html and do that...
Related
This is my HTML code
<form class="addtowatchlistform" action="logo/insertwatchlist.php" method="POST">
<input type="hidden" name="tmdb_id" value="'.$result[$x]["tmdb_id"].'"/>
<button id="addtowatchlistbutton" type="submit" name="tmdb_id" value="'.$result[$x]["tmdb_id"].'" data-tooltip="ADD TO YOUR WATCHLIST" class="material-icons" style="color:'.$watchlisticoncolor.'">add_box</button>
</form>
// Same form as above
<form class="addtowatchlistform" action="logo/insertwatchlist.php" method="POST">
<input type="hidden" name="tmdb_id" value="'.$result[$x]["tmdb_id"].'"/>
<button id="addtowatchlistbutton" type="submit" name="tmdb_id" value="'.$result[$x]["tmdb_id"].'" data-tooltip="ADD TO YOUR WATCHLIST" class="material-icons" style="color:'.$watchlisticoncolor.'">add_box</button>
</form>
Jquery Code:
<script>
$(".addtowatchlistform").submit(function(e) {
var data = $(this).serialize();
var url = $(this).attr("action");
var form = $(this); // Add this line
$.post(url, data, function(data) {
try {
data = JSON.parse(data);
$(form).children("button").css('color',data.watchlisticoncolor);
$(form).children("button").data('tooltip', data.addremove + " TO YOUR WATCHLIST"); // This line not working
} catch (e) {
console.log("json encoding failed");
return false;
}
});
return false;
});
</script>
PHP file insertwatchlist.php file
$response = new \stdClass();
$response->addremove = "REMOVE";//you can get the data anyway you want(e.g database)
$response->watchlisticoncolor = "red";
die(json_encode($response));
Output of PHP file insertwatchlist.php file
{"addremove":"REMOVE","watchlisticoncolor":"red"}
Expected Result:
1.)When someone clicks on add_box button, it submits the form without reloading the page (This one works fine)
2.) When someone clicks on add_box button, it's color changes. (works fine too)
3.) When someone click on add_box button, the data-tooltip="" value changes. (this one do not work)
So the 3rd point do not work as expected, what is wrong in my Jquery code? Console tab is empty, it shows nothing.
your jquery code should be like this
$(form).children("button").attr('data-tooltip',data.addremove + "TO YOUR WATCHLIST");
or
$('.material-icons').attr('data-tooltip',data.addremove + "TO YOUR WATCHLIST");
I have a simple form that will show hidden div when category is selected in a select tag.
What I want is when I refresh the page, the contents is still visible and also the checked items is still there.
here is the sample code
HTML
<select class="form-control" name="food_type1" id="food_type1">
<option selected="selected" disabled="disable" value="0">SELECT</option>
<option value="1">Fruits</option>
<option value="2">Meat</option>
</select>
<div id="food1" style="display: none;">
<input type="checkbox" name="food1[]" value="Mango">Mango <br>
<input type="checkbox" name="food1[]" value="strawberry">Strawberry
</div>
<div id="food2" style="display: none;">
<input type="checkbox" name="food2[]" value="Beef">Beef <br>
<input type="checkbox" name="food2[]" value="Pork">Pork <br>
<input type="checkbox" name="food2[]" value="Chicken">Chicken
</div>
SCRIPT
$(document).ready(function(){
$('#food_type1').on('change', function() {
if ( this.value == '1') {
$("#food1").show();
$("#food2").hide();
}
else if ( this.value == '2') {
$("#food2").show();
$("#food1").hide();
} else {
$("#food1").hide();
$("#food2").hide();
}
});
});
FIDDLE
https://jsfiddle.net/bk2ohogj/
The simplest way would be to use Local storage. I've updated your fiddle, however you will not be able to test the refresh while in JSFiddle, so you will have to try the code locally on your machine.
JSFiddle: https://jsfiddle.net/m0nk3y/bk2ohogj/4/
You will have to create a couple functions to implement it. I kept them as simple as possible, so they may not address all your use cases, but this should help you get closer to what you are trying to do:
JS:
$(document).ready(function(){
var storedItems = [];
//Store selected items
function storeItem(item) {
storedItems.push(item);
localStorage.setItem("storage", storedItems);
}
//Remove item
function removeItem(item) {
var index = storedItems.indexOf(item);
storedItems.splice(index, 1);
}
//Show list according to Dropdown
function showList(type) {
var $food1 = $("#food1");
var $food2 = $("#food2");
localStorage.setItem("list", type);
if ( type == '1') {
$food1.show();
$food2.hide();
} else if ( type == '2') {
$food2.show();
$food1.hide();
} else {
$food1.hide();
$food2.hide();
}
}
//Get list type
if (localStorage.getItem("list")) {
showList(localStorage.getItem("list"));
}
//Get stored items
if (localStorage.getItem("storage")) {
storedItems = localStorage.getItem("storage");
$.each(storedItems, function(i, val) {
$('input[type="checkbox"][value="'+val+'"]').prop("checked", true);
});
}
//Dropdown
$('#food_type1').on('change', function() {
showList(this.value);
});
//Checkbox
$('input[type="checkbox"]').on('change', function() {
var $this = $(this);
if ($this.is(':checked')) {
storeItem(this.val())
} else {
removeItem(this.val());
}
});
});
You'll need a mechanism to remember the states and dynamically set them on page re/load. You can use sessions (if you are using a server language to generate the pages) or cookies in your scripts. It depends on your scenario.
You can store the states on the server in the db. Whenever the state changes, send an update to the back end which will store the state and return the state. You should use this state to populate the form.
You can use HTML5 Local storage on the browser to retain the states. However, ensure you handle this carefully, per user. Whenever the page reloads, read the state from the local storage and populate the form. In case you have security concerns, be aware that users of the browser can see the content of the local storage.
I'm a newbie Javascript learner and I want to post serialized data of input checkboxes. The data are sent to the server in order to update the corresponding field in SQL table. Later, the user can review the selections he made the first time and deselect some checkboxes. If I understand well, only the selected items will be sent, not the unselected ones. How can I send all the info I need to update the newly selected items and the newly unselected ones?
The only solution I found is to make 2 updates: the first resets to 0 all the rows and the second one sets to 1 the selected items (newly selected or not) that are sent in the serialized array. Is there a more optimal way to do the job? Ideally, I would update only the data that have changed. Is it possible?
Regards,
Patrick
If I understand it correctly you can filter the checkboxes and then you can add the unselected boxes to the parameters too.
I've found the code for that here at SO. See this question.
The demo below and here a jsfiddle is doing a ajax post only if the user changed the data. Not sure if this is what you want.
(The demo at SO is a bit modified because JSONP is required to get no CORS error.)
var data = "";
$('form').submit(function (evt) {
evt.preventDefault();
//console.log($(this).serialize());
var formData = $(this).serialize();
// source from this SO question https://stackoverflow.com/questions/10147149/how-can-i-override-jquerys-serialize-to-include-unchecked-checkboxes
// include unchecked checkboxes. use filter to only include unchecked boxes.
$.each($('form input[type=checkbox]')
.filter(function (idx) {
return $(this).prop('checked') === false
}),
function (idx, el) {
// attach matched element names to the formData with a chosen value.
var emptyVal = "off";
formData += '&' + $(el).attr('name') + '=' + emptyVal;
});
console.log(formData);
if ( data != formData ) { // check if user changed the data.
$.ajax({
url: 'http://jsfiddle.net/echo/jsonp/',
type: 'POST',
//data: formData, // this will work but for jsfiddle echo the code below is required.
dataType: "jsonp",
data: {
json: JSON.stringify({
serialized: formData
}),
delay: 1
},
success: function(res) {
console.log('posted: ', res);
}
});
}
data = formData;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label for="first">check1</label>
<input name="first" id="first" type="checkbox" />
<label for="second">check2</label>
<input name="second" id="second" type="checkbox" />
<label for="third">check3</label>
<input name="third" id="third" type="checkbox" />
<label for="fourth">check4</label>
<input name="fourth" id="fourth" type="checkbox" />
<input type="submit" value="update" />
</form>
What I want to be able to is on button click I want to check a Server-Side directory for the existence of certain files.
If they exist I wish to display a checkbox corresponding to that file.
So far I have managed to use PHP and AJAX to check if the files exist or not and write to and array: 1 if the file exists, and a 0 if not.
Now...what I need to do at this stage is call upon this array, from my PHP file, or write this array to a div on my main HTML page. However when I go to echo it navigates away from my Main.html, opening a new page and writing on that.
Big question is can I write the array on my main html page from my PHP_Function.php file.
I have the following HTML code:
<form action="PHP_Function.php">
<input type="submit" class="learnButton" name="insert" value="Find Available Evidence" />
</form>
<form action="available_evidence">
<input type="checkbox" name="vehicle" value="Bike"> Facebook<br>
<input type="checkbox" name="vehicle" value="Car" checked> Facebook Messenger<br>
<input type="checkbox" name="vehicle" value="Bike"> Twitter<br>
</form>
With the following array within PHP_function.php file:
if(in_array("Facebook.xml", $dirArray)){
$IfPresentArray[0]="1";
}else {
$IfPresentArray[0]="0";
}
foreach ($IfPresentArray as $value) {
echo "$value<br />\n";
}
I am very new to PHP and HTML, and I have been banging my head off the wall with this for a while now.
Any help would be greatly appreciated.
You are using AJAX so all your communication will need to go back and forth over that medium. In brief, your PHP script (the one called by ajax) will echo JSON values (typically created by json_encode($myarray)) and this will then be available to your javascript over on your client-side.
A quick google for "jquery ajax json example" should get you some good, helpful ideas of how it fits together.
Here's the client-side from one of those google links above - note the .done part
<script type="text/javascript">
$(document).ready(function(){
$(':submit').on('click', function() { // This event fires when a button is clicked
var button = $(this).val();
$.ajax({ // ajax call starts
url: 'serverside.php', // JQuery loads serverside.php
data: 'button=' + $(this).val(), // Send value of the clicked button
dataType: 'json', // Choosing a JSON datatype
})
.done(function(data) { // Variable data contains the data we get from serverside
$('#wines').html(''); // Clear #wines div
if (button == 'all') { // If clicked buttons value is all, we post every wine
for (var i in data.red) {
$('#wines').append('Red wine: ' + data.red[i] + '<br/>');
}
for (var i in data.white) {
$('#wines').append('White wine: ' + data.white[i] + '<br/>');
}
}
else if (button == 'red') { // If clicked buttons value is red, we post only red wines
for (var i in data) {
$('#wines').append('Red wine: ' + data[i] + '<br/>');
}
}
else if (button == 'white') { // If clicked buttons value is white, we post only white wines
for (var i in data) {
$('#wines').append('White wine: ' + data[i] + '<br/>');
}
}
});
return false; // keeps the page from not refreshing
});
});
</script>
You can store your array inside a $_SESSION variable, but you'll have to use a session_start(); on both pages.
On your php page, use: $_SESSION['array'] = $array; and then on your main page retrieve the array by the inverse: $array = $_SESSION['array'];.
You can now use said array on your main page.
To retrieve a specific value: $value1 = $_SESSION['array'][0];
For further reference:
Array as session variable
I have two text boxes and i want to send these two text box names to one jsp page. By getting these two names in check.jsp i will do some calculation and will return the result by json to third text box, but i think i am doing wrong somewhere. Can anybody give me an idea?
<script type="text/javascript">
$(document).ready(function() {
$("#textbox").keyup(function () {// do i need to write another onkey up for another text box?
$.getJSON('check.jsp', {
textboxname: this.value// here how can i send another text box name to check.jsp?
},function(data){
// get data
});
});
});
</script>
html
<input type="text" id="textbox" name="textboxname"/>// name goes to check.jsp
<input type="text" id="textbox1" name="textboxname1"/>// how can i send this text box's
name to that same check.jsp
<input type="text" id="textbox2" name="textboxname2"/>// here i want to display the
result received from check.jsp
server side(check.jsp)
String firsttextboxname=request.getParameter("firsttextboxname");
String firsttextboxname1=request.getParameter("firsttextboxname1");
JSONObject jsonObj= new JSONObject();
jsonObj.put("isTrue","true");
response.setContentType("application/json");
response.getWriter().write(jsonObj.toString());
<input type="text" id="textbox" class="submitme" name="textboxname"/>// name goes to check.jsp
<input type="text" id="textbox1" class="submitme" name="textboxname1"/>// how can i send this text box's
<script type="text/javascript">
$(document).ready(function() {
$(".submitme").keyup(function () {
$.getJSON('check.jsp', {
textboxname: jQuery("#textbox").val(), textboxname2: jQuery("#textbox1").val()
},function(data){
if (data.textboxname != "" && data.textboxname2 != "") {
jQuery("#textbox2").val(JSON.stringify(data));
}
else {
jQuery("#textbox2").val("");
}
}
});
});
});
</script>
------OR AS A POST-----------
$.ajax({
type: 'POST',
url: 'check.jsp',
data: { textboxname: jQuery("#textbox").val(), textboxname2: jQuery("#textbox1").val() },
success: function(data) {
jQuery("#textbox2").text(JSON.stringify(data));
},
dataType: 'JSON'
});
I'll comment to say your doing a couple things I wouldn't.
1) Why not send this data via a POST
2) Why send data everytime a key is pressed, why not bind this to a submit button?