Insert Only One Record In MYSQL database using php - php

i am working on a project where i want to insert only one record in a specific time.
For Example: in the project client rate a contractor only once.(when the construction is in working) once he rated he cannot rate second time whatsoever.
I checked online but didn't find what i am looking for.
Now I have 2 Ideas.
1- Either insert checkboxes and make them disable permanently, once the rating is done(with server side validation).
2- Rate according to numbers (like 7/10) and display them.
which one is batter strategy to opt.
Code Part:
CheckBox Solution Code(no solution available on google on serverside validation):
Checkbox: <input type="checkbox" id="myCheck">
<p>Click the "Try it" button to disable the checkbox.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("myCheck").disabled = true;
}
</script>
Also checked this on stackoverflow (but this is not i am looking for):
[an example serverside solution link][1]
Number Solution:
<table>
<tr><td>Rate Your Contractor (Out Of 10)</td><td><input id="intLimitTextBox"></td></tr>
</table>
<script>
function setInputFilter(textbox, inputFilter) {
["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop"].forEach(function(event) {
textbox.addEventListener(event, function() {
if (inputFilter(this.value)) {
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
} else {
this.value = "";
}
});
});
}
// Install input filters.
setInputFilter(document.getElementById("intLimitTextBox"), function(value) {
return /^\d*$/.test(value) && (value === "" || parseInt(value) <= 10); });
</script>
Is There any php way(or both ways) to implement the solution of my problem?
PS: i am not very expert in web devolepment, sorry if any mistake i am doing.

Edit : Question has been totally changed !? This is an answer to the original question.
I'll try to answer your second question, then, but it is somehow vague...
Rendering the form :
Check if a submission exists for this user.
If yes, render the rating read-only with the value.
(If the rating is the only field you have, don't even render the tag)
If no, show the form submittable.
Handling submission :
On handling submission, check if a submission exists for this user.
If it already exists, return an error (user has tried to trick you)
Otherwise, add a new one.

Edit : Question has been totally changed !? This is an answer to the original question.
Maybe I misunderstood; your title is about php, but your question seems to be an ergonomic one.
For a rating, a current presentation is a list of stars, on which the user clicks on the wanted.
Once user has submitted a rating, I suggest you to have the same presentation, without javascript and without :hover rules.
Maybe changing the colors (yellow when submitting, black or gray when submitted and read-only)
$('.star').on('click', function() {
var v = $(this).data('value');
$('input[name="rating"]').val(v);
$('.star').each(function() {
var $this = $(this);
$this.toggleClass('active', $this.data('value') <= v);
});
});
/* remove spaces between stars */
.stars {
font-size:0;
}
.star::after {
content:"☆";
display:inline;
font-size: 14pt;
padding: 0 5px;
}
/* by default, only fills active stars */
.stars:not(:hover) .star.active::after,
.stars:hover .star::after {
content:"★";
}
/* unfill stars following the current hovered */
.stars:hover .star:hover ~ .star::after {
content:"☆";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="stars">
<input type="hidden" name="rating" value="" />
<span class="star" data-value="1"></span>
<span class="star" data-value="2"></span>
<span class="star" data-value="3"></span>
<span class="star" data-value="4"></span>
<span class="star" data-value="5"></span>
</div>

Related

Updating via ajax a DB and show the Answer in a Div

i want a kind Like Button on my Page. I have News and there should be a "hooah!" link (maybe you know it from Battlelog, if you are a gamer) that update my Db via a update.php. Updating is fine but i don´t want the whole page reloaded to show the actual "Hooahs".
At the moment is use a Form to transmit the data - i transformed the Submit-Button that it looks like a Link ...
now my problem :
I want it like "battlelog" you click and then the text shows "5 Persons gave a hooah!"
it is possible to use the Hooah! from "5 Persons gave a hooah!" as link? and when clicked it changes to "6 Persons gave a hooah!".
my script :
<script>
$(document).ready(function () {
$('#ajax_form{newsid}').bind('submit', function() {
var form = $('#ajax_form{newsid}');
var data = form.serialize();
$.post('index.php?hooah_update', data, function(response) {
document.location.reload();
});
return false;
});
});
</script>
the form:
<div style="position: relative; top: -16px; left: 515px;">
<form method="post" id="ajax_form{newsid}" action="#">
<input type="hidden" name="id" value="{newsid}">
<input type="submit" name="submit" value="hooah!" style="background:none; border:0; color:#0099ff; cursor:pointer;">
</form>
</div>
thx for taking a look ;)
You seem to be almost there. Instead of:
document.location.reload();
You would need something like:
$("#your_div").html(response);
The php script would have to echo out the text you want.
I think it's better to add 1 count on the client side rather than show the actual "Hooahs" count.
Imagine that you open the page and it shows "5 Persons gave a Hooah!",
Before you click the "Hooah!" button there's 10 other people gave hooahs.
now you click the button, I think it's better to update the count to 6 than to 16 after just one click by you.
Don't worry about the actual count because it will show 16 when you refresh the whole page.
$.post('index.php?hooah_update', data, function(response) {
if(response.success) {
$('span#count').text(parseInt($('span#count').text()) + 1);
// Change Hooah to Hooahs
if(parseInt($('span#count').text() > 1) {
$('span#hooah').text('Hooahs');
}
}
});

store the option of a selectlist added by jquery into database using PHP

I found a jquery snippet to add and remove options from a select box from box 1 to box 2. This works great. However, when i try to print_r in PHP of the box where the new options are added then it won't show. I cant even see it on the resource after submit. Any solution?
$('#btn-add').click(function(){
$('#select-from option:selected').each( function() {
$('#select-to').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");
$(this).remove();
});
});
$('#btn-remove').click(function(){
$('#select-to option:selected').each( function() {
$('#select-from').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");
$(this).remove();
});
});
});
and html of the two select lists
<select class="gen" name="selectfrom" id="select-from" multiple size="6" style="width: 150px;">
</select>
<input name="" id="btn-add" type="button" class="add_list" style="vertical-align: top;">
<input name="" id="btn-remove" type="button" class="remove_list" style="vertical-align: top;">
<select class="gen" name="selectto" id="select-to" multiple size="6" style="width: 150px;">
</select>
upon submit i check the $_POST['selectto'] from the selectto box. Any idea's?
EDIT: the foreach in php;
$articles_ary = array();
foreach ($_POST['selectto[]'] as $options)
{
if (!empty($options))
{
$articles_ary[] = $options;
}
}
print_r($articles_ary);
when you POST a select the form submits only the selected option and bare in mind that it must be selected.
with your code you are just adding the options to the selectto, but you're not:
a) chosing one of them (if you want a single value posted)
b) chosing all of them to be posted on the PHP page. (if you want multiple values posted)
in the second case (i thought it's the one you need) you can use this simple jQuery function:
$("#buttonusedtosendform").click(function(e){
e.preventDefault();
$('#select-to option').each( function() {
$(this).attr('selected', true); //with this you select all the option
});
$('formname').submit();
});
bare in mind that if you want to retrieve all the options of a select with PHP you will have to use a little trick by naming the select with square bracket at the end (it's a feature that PHP offer, where it will overwrite the former variable with the latest parsing each one separately):
eg. selectto => selectto[]
this way php will handle it as an array and let you retrieve all the value as if it is one:
foreach($_POST['selectto[]'] as $options){}
When you enter data from one select box to second selectbox, you need to have items selected in second select box to show when you do print_r in php.
For this, after items are added to second select box say with id selectbox2, then you could select all items of second selectbox and then submit the form
for (var i = 0; i < selectbox2.options.length; i++) {
selectbox2.options[i].selected = true;
}
//then Submit form like this, assuming your form name is form1
document.form1.submit();
Hope this helps

Allow Users to Select Multiple Options, Aggregate Results and Display

I am having difficulty finding specifically what I'm searching for, most likely because I'm not sure how to express it well in a Google search.
Basically what I would like to do is display 30 or so buttons that users would then be able to select. Once selected a button changes color indicating that the particular option has been chosen. Users are required to select 10 out of 30 options. The results should then be aggregated (basically counting each unique button selected) and displayed to another user who can login and see the results.
Multiple users should be able to select these options and have their results recorded.
I'm not looking to create a drop down list, multi-list, or checkbox solution. In my research so far I have found plenty of references to this type of option. Also, Javascript restricting the min/max number of checkboxes a user can select.
I hope that makes sense. Any assistance with identifying the best method for going about this task would be greatly appreciated.
Thank You,
-Nathan
What you can do, you can create 30 buttons, and connect each button to a hidden check box, then you can post it to server, eg.
<input type="checkbox" value="1" name="chk_one" id="chk_one" style="display: none;">
<input type="button" value="Check Box One" id="btn_one"/>
CSS
input[type="button"].selected { color: red; }
input[type="button"] { color: black; }
then you can write jQuery solution in order to make it change colors:
var _minLength = 10;
var _maxLength = 30;
$(document).ready(function() {
$('#submit_id').click(function() {
if($('#form_id input[type="checkbox"]').is(':checked').length < _minLength)
{
alert('you need to select at least ' + _minLength + ' of buttons'); return false;
};});
$('#form_id input [type="button"]').click(function() {
var _id = $(this).attr('id').toString().split('_')[1];
if(_id != null)
{
var _chckBox = $('#chk_'+_id);
var _newState = _checkBox.attr('checked') ? false, true;
if($('#form_id input[type="checkbox"]').is(':checked').length+1 > _maxLength)
return;
_checkBox.attr('checked', _newState);
if(_checkBox.attr('checked'))
$(this).addClass('selected');
else
$(this).removeClass('selected');
}
});
});
Method from above will attach click event to every button in the area you specified with "#form_id" then when clicked it will toogle state of hidden checkbox and will set or remove class from button, it depends of checkbox state.
And by the way number of checkboxes is not limited.

Collect checkbox values in jQuery and POST them on submit

I've referred to this post:
Post array of multiple checkbox values
And this jQuery forum post:
http://forum.jquery.com/topic/checkbox-names-aggregate-as-array-in-a-hidden-input-value
I am trying to collect an array (or concatenated string with commas, whatever) of checkbox values in a hidden input field using jQuery. Here's the script code I'm using:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
$(form).find("input[name=specialty]").val(function() {
return $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
});
});
</script>
A snippet of the relevant HTML:
<form id="advancedSearchForm" name="advancedSearchForm" method="post" action="<?php echo site_url('/magcm/advancedSearch#results'); ?>">
<input type="checkbox" name="FCM" id="FCM" class="chk" value="FCM" <?php echo set_checkbox('FCM', 'FCM'); ?>/>
<input type="hidden" name="specialty" id="specialty" value="" />
<input class="button" name="submit3" id="submit3" type="submit" value="Search" />
I've tried changing "submit" to "submit3" in the jQuery, which breaks (obviously). When I print_r($_POST), the checkboxes POST correctly but the condensed hidden variable does not. (It posts, but a blank value.) The checkboxes persist correctly using CI's hacked set_value() function (Derek needs to implement this in the main trunk... but that's another story)
I'm sure I'm doing something that is wrong and easy to point out. I've just been banging my head against the wall for the past 2 hours on it, trying various functions and changing a ton of things and analyzing it in Chrome dev tools (which don't show any errors).
Help is appreciated. :)
Let's say you applied an class, maybe "tehAwesomeCheckboxen" to every checkbox. Then
<script>
$("#advancedSearchForm").submit(function() {
var chkbxValues = $(".tehAwesomeCheckboxen").val();
$("#specialty").val( chkbxValues.join(",") );
});
</script>
EDIT:
I don't think the $_POST array is getting populated, since the submit is being handled locally by the JavaScript engine. SO... let's try this:
<script>
var chkbxValues = new Array();
$(".tehAwesomeCheckboxen").live("change", function(e){
var val = $(this).val();
if( $(this).is(":checked") ) {
if( chkbxValues.length == 0 || chkbxValues.indexOf(val) == -1){
// Add the value
chkbxValues.push(val);
}
}
else {
// remove the value
chkbxValues.splice( chkbxValues.indexOf(val), 1 );
}
$("#specialty").val( chkbxValues.join(",") );
});
</script>
This adds an event handler the checkboxes themselves, such that checking/unchecking the box alters the hidden element. Then your form handles its submission as normal.
Is this more in line with what you're trying to do?
P.S. Those who upvoted this, please note I have modified my answer. Please verify whether you still find it useful and adjust your vote accordingly.
I ended up solving it using PHP arrays rather than jQuery:
<input type="checkbox" name="chk[]" id="RET" class="chk" value="RET" <?php echo set_checkbox('chk', 'RET'); ?>/>
I changed the name to an array and POSTed it to my script, where I looped through the array and handled it there. Still not sure what the problem was with the jQuery-based solutions, but I figured I'd post this for everyone to refer to in the future.
You've got lots of nested functions() in your JavaScript, makes it hard to follow what you're doing.
However, it seems that you're just passing a function to .val() rather than an actual value. Try this instead:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
$(form).find("input[name=specialty]").val((function() {
return $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
})());
});
</script>
Or even better, calculate the value first:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
var value = $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
$(form).find("input[name=specialty]").val(value);
});
</script>

Select only one checkbox (and deselect rest) and show input field if checkbox selected

I have a form with "Yes" and "No" as two checkboxes. These come in unselected at first. I'd like the user to only select one of these with the option to deselect their choice if they don't want to make a decision (which is why I didn't use radio buttons). Selecting Yes should deselect No and vice versa. I'm not sure how to do this. I'm using PHP (codeigniter), Javascript and JQuery.
Secondly, after either Yes or No is selected, an input field needs to be displayed. I've got this setup but it toggles on the "onclick" action, which means selecting Yes twice shows and hides the input field! I want the input field to show if Yes or No are selected and disappear if the both Yes and No are unselected.
$do_toggle = "onClick=\"javascript:toggle('togglenote');\"";
echo form_radio('decision'.$key,'y',FALSE,$do_toggle)."Yes ";
echo form_radio('decision'.$key,'n',FALSE,$do_toggle)."No";
echo form_input($mytext);
// I put a div tag around the form_input above
// but it's not showing in the StackOverflow question...
// but it's there for the toggle to work.
Assuming your html is like this (i think it is):
<input type="checkbox" name="decisionY" value="y" /> Yes
<input type="checkbox" name="decisionN" value="N" /> Yes
<input type="text" id="togglenote" name="togglenote" />
Your js would be:
$(document).ready(function(){
$(":checkbox[name^='decision']").change(function(){
if($(this).is(":checked")){
$(":checkbox[name[^='decision']").attr("checked", false); //Uncheck the other
$(this).attr("checked", true);
$("#togglenote").show();
}
if($(":checkbox[name^='decision']:checked").size() == 0){
$("#togglenote").hide();
}
});
});
Hope this helps. Cheers.
This should do what you want:
$("#checkbox1").change(function() {
if ($(this).attr("checked") && $("#checkbox2").attr("checked")) {
$("checkbox2").removeAttr("checked");
} else if ($(this).attr("checked")) {
$("#inputfield").show();
} else {
$("#inputfield").hide();
}
});
$("#checkbox2").change(function() {
if ($(this).attr("checked") && $("#checkbox1").attr("checked")) {
$("checkbox1").removeAttr("checked");
} else if ($(this).attr("checked")) {
$("#inputfield").show();
} else {
$("#inputfield").hide();
}
});
select one of them as jQuery or javascript
Dont think that this is 100% garantee that some hacker can't set up both and post :)
Analise $_REQUEST array against setted up both yes/no values
Make decision.
PS. JQuery works not at my nokia 6303c :) device, hard coded - will work ... so application must have 2 parts.

Categories