Javascript duplicate ids - php

Hello guys J have problem at Javascript. This is the code,
function reply_click(clicked_id) {
var la = <? php echo json_encode($logOptions_id); ?> ;
var mood = clicked_id;
$.post('msg.php', {
myne: la,
mood: mood
}, function (data) {
$('#nov').html(data);
});
$('#postDiv').on('keydown', '#textarea', function (e) {
if ((e.which == 13) && !event.shiftKey) {
var textarea = $("#textarea").val();
$.post('pst.php', {
mibe: la,
voot: mood,
pst: textarea
}, function (data) {
var textarea = $("#textarea").val('');
});
}
});
}
The problem is when I clicked on item I get clicked_id, after post message, its ok, but then once again I clicking the item, I get second id, and after post enter button it post in to database difference id from first item and second, seems duplicating values, how many times I click on different items , getting different ids and this problem is spamming my DB.

Every time you click the button, you add another keydown binding to #textarea. So if you click the button 5 times, then when you press Enter the keydown binding will be run 5 times.
You should move $('#postDiv').on('keydown', '#textarea', ...) outside the function, and just do it once in the document ready handler.

Related

How to use onclick on a button with an insert function for multiple buttons php

I have a page with several buttons whose values and names are retrieved from the database. I'm trying to run an insert query on any button clicked, my code so far:
<?php
$sqlGetIllness = "SELECT * FROM illnissesandconditions ";
$resultGetIllness = $conn->query($sqlGetIllness);
while ($rowGetIllness= mysqli_fetch_array($resultGetIllness)){
echo "<div class='col-md-3'style='margin-top:20px;'><button onclick='insert(".$rowGetIllness['illness'].");' class='button button1' style=' color:white;' value='".$rowGetIllness['illness']."'>".$rowGetIllness['illness']."</button></div>";
}
function insert($value) {
$value='';
$sqlGetId = "SELECT commonID from common group by commonID DESC LIMIT 1 ";
$resultGetId = $conn->query($sqlGetId);
$r=mysqli_fetch_array($resultGetId);
$id=$r['commonID'];
$sqlGetIllness = "INSERT INTO medicalrecords (CommonID,Medical_Condition) VALUES (".$id.",'".$value."')";
$resultGetIllness = $conn->query($sqlGetIllness);
}
The value passed to the function inside onclick is correct when I inspect it in the browser, however nothing happens. I have a database connection on already, what could be wrong? Is it possible to do it like that in php without refreshing the page? Or do I need to use a client side lang like AJAX? Please note that I've never worked in AJAX btw.
New EDIT:
<script>
$("button").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
data: {
condition: $(this).val(), // < note use of 'this' here
},
success: function(result) {
alert('Condition Inserted!');
},
error: function(result) {
alert('error');
}
});
});
</script>
Solution:
I got it worked out, after writing the script, i retrieved the variable value on top of the page
if (isset($_POST['condition'])) {
$value=$_POST['condition']; }
inside $_SERVER['REQUEST_METHOD'] == 'POST' ) and now it inserts the value when ever any button is clicked, my next step is to give the clicked button a background color
Solution is in the post under Solution, was my first time trying ajax and it did work indeed, gave the button an id, and took its value ( any button clicked ) through this.val and sent via post, retrieved and used the value in a variable for the insert query.

Append old chats before new chats to the div using jQuery

In my online-chat project using Codeigniter, jQuery, AJAX I have a function that runs every 1 second which retrieves chat with delivered status = 0
$.post("<?php echo base_url(); ?>chat/admin_chat/get_chat",
{
user_id : $('.hide_me').text(),
username : $('.username').text()
},
function(data){
if (data != "") {
$('#chat_window').append(data);
$('#chat_window').scrollTop($('#chat_window').prop("scrollHeight"));
}
}
);
and there is another function which is used to get the chats with delivered status = 1 (or old chats),
$(document).on('click','.user',function (e) {
e.preventDefault();
$('.username').html($(this).text());
$('.hide_me').html($(this).attr('id'));
$('.username').show();
$('.log_username').hide();
$("#input").removeAttr("readonly");
var user = $(this).attr('id');
$("#chat_window").html('');
$.post("<?php echo base_url(); ?>chat/admin_chat/get_old_chat",
{
user_id : $('.hide_me').text(),
username : $('.username').text()
},
function(data){
$('#chat_window').append(data);
$('#chat_window').scrollTop($('#chat_window').prop("scrollHeight"));
}
);
});
which is called when clicked on the username. The result of both AJAX calls are appended to a div. The problem I face now is sometimes when I click on the username, the chats that are not delivered is getting appended to the div before the old chats which is not what I want. I need the old chats to be appended to the div before the new chats, when clicked on the username. Could someone please suggest a way to fix the issue?
At last I found a way to fix the issue.
I added a span <span id='old_chat_appended' hidden=""></span>.
Modified the get_old_chat function a little bit by changing the value of span to 0 and 1.
After e.preventDefault(), added
$('#old_chat_appended').text('0')
and after appending data to div using $('#chat_window').append(data), added
$('#old_chat_appended').text('1').
At last in the get_chat function, which runs every 1 second, added
if($('#old_chat_appended').text() == 1)
{
$('#chat_window').append(data);
}
The application is working as expected. The old chats are getting appended to the div before the new chats.

how to show a user the values he chose in some drop-down menus on the submit event in case of mistake

I need some help because I modified a jQuery script to obtain some drop-down menus that are linked together, from a form of mine. I have a PHP script with 3 different tables on my MySQL database, to let a user choose his region, then with a Ajax call that I do with the jQuery script, I show him only the provinces that belong to that chosen region, and once he chooses the province, I show him only the towns that belong to this province in a similar way.
All is ok up to that, but I'd like to do something more: that's to say, if the user forgets to fill in some obligatory fields, (I control all the fields with PHP) when he clicks on submit, I would manage to show him also these three drop-down menus that maybe he has filled, with the choices he has made, without forcing him to fill in the three selects once again.
I got no problem in doing that for all the other fields with PHP, but here I use a Ajax call with a jQuery script and I'd like to do it just inside this jQuery script.
Here is my script and I miss the final part, as you can see, on the submit event:
$(document).ready(function(){
var scegli = '<option value="0">Scegli...</option>';
var attendere = '<option value="0">Attendere...</option>';
$("select#province").html(scegli);
$("select#province").attr("disabled", "disabled");
$("select#comuni").html(scegli);
$("select#comuni").attr("disabled", "disabled");
$("select#regioni").change(function(){
var regione = $("select#regioni option:selected").attr('value');
$("select#province").html(attendere);
$("select#province").attr("disabled", "disabled");
$("select#comuni").html(scegli);
$("select#comuni").attr("disabled", "disabled");
$.post("select.php", {id_reg:regione}, function(data){
$("select#province").removeAttr("disabled");
$("select#province").html(data);
});
});
$("select#province").change(function(){
$("select#comuni").attr("disabled", "disabled");
$("select#comuni").html(attendere);
var provincia = $("select#province option:selected").attr('value');
$.post("select.php", {id_pro:provincia}, function(data){
$("select#comuni").removeAttr("disabled");
$("select#comuni").html(data);
});
});
$("#form_registrazione").submit(function(){
var reg = $("select#regioni option:selected").attr('value');
var prov = $("select#province option:selected").attr('value');
var com = $("select#comuni option:selected").attr('value');
if ( reg > 0 && prov > 0 && com > 0 )
// I miss here the final part
});
Here's the link to my page of website: it's only in Italian, but nonetheless you can see the undesired behavior I described above, if you make a mistake filling in an obligatory field of the form and you try to send it out.
Thanks for your help.
Bye.
Hello I updated the code
$('#submit').on('click', function(event) {
event.preventDefault();
if ($('#username').val() == '' || $('#password').val() == '') {
alert('alert - Required fields');
$('#username').css('border-color','red');
$('#password').css('border-color','red');
} else {
$('#form_registrazione').submit();
}
});
jQuery.each($('.required'), function () {
$(this).on('click', function (event) {
event.preventDefault();
$(this).addClass('glowing-border').removeClass('red');
});
});
Here is jsFiddle
OR you can use a jQuery validation Plugin

Variables not sent when pressing back button

I have a javascript that runs on a set of checkboxes to filter some items shown via PHP.
When someone filters the information and then clicks on an item, he is directed to that item's description. My issue is when that user clicks on the BACK button in the browser, since my filtering is already gone.
This happens because my script loads a .php but only inside a DIV (so I don't need to reload the whole page). This means my sent variables are just loaded at the DIV level and not at the URL level, so when they go to the description of a specific product and then go back, those variables are not there anymore and the filtering is gone.
Here is my JS:
$(function() {
$("input[type='checkbox']").on('change', function() {
var boxes = [];
// You could save a little time and space by doing this:
var name = this.name;
// critical change on next line
$("input[type='checkbox'][name='"+this.name+"']:checked").each(function() {
boxes.push(this.value);
});
if (boxes.length) {
$(".loadingItems").fadeIn(300);
// Change the name here as well
$(".indexMain").load('indexMain.php?categ=<?php echo $category; ?>&'+this.name+'=' + boxes.join("+"),
function() {
$(".indexMain").fadeIn('slow');
$(".loadingItems").fadeOut(300);
});
} else {
$(".loadingItems").fadeIn(300);
$(".indexMain").load('indexMain.php?categ=<?php echo $category; ?>', function() {
$(".indexMain").fadeIn('slow');
$(".loadingItems").fadeOut(300);
});
}
});
});
Any idea to solve this?
Either open the item description in a new window, or (more elegantly) open the item description in a modal dialog (e.g. using jQuery UI dialog).

jquery skip a block

I have a jquery game that you can view here link text
The game starts by you entering a number in a text field.
then you click the play button.
After clicking the play button a set of square appear each rotating random numbers, click on the square that has your number to build up your score, miss 3 times and you are done.
I added the game to my site, you can view it here link text
the problem I'm having is that my site members will just keep the cursor on one box and wait for their number to appear in that one box. Which ruins the game.
Is there a way to make it so they can't click on the same box more than once in a row. They'll have to go click another box before they can come back to this one.
here's my complete script
var hitCount = 0,
missCount = 0;
function IsNumeric(n) {
return !isNaN(n);
}
$("#getit").click(function() {
var hitCount = 0,
missCount = 0;
$('#hitcount').text(0);
$('#misscount').text(0);
$('#message').hide(100);
var li = [],
intervals = 0,
n = parseInt($('#MyNumber').val());
var intervalId = -1;
if (IsNumeric(n)) {
intervalId = setInterval(function() {
li[intervals++ % li.length].text(Math.random() > .1 ? Math.floor(Math.random() * (10 + n) + (n / 2)) : n).attr('class', '') ;
}, <?php echo $time ?>);
}
$('#randomnumber').empty();
for (var i = 0; i < 7; i++) {
li.push($('<li />').appendTo('#randomnumber'));
}
$('#randomnumber').delegate("li", "click", function() {
var $this = $(this);
if (!$this.hasClass('clicked')) {
if (parseInt($this.text(), 10) === n) {
$this.addClass('correct');
$('#hitcount').text(++hitCount);
} else {
$this.addClass('wrong');
$('#misscount').text(++missCount);
}
//New code If the missCount > 3 stop the game and save the value
if(missCount>=<?php echo $limit ?>){
clearInterval(intervalId);
$('#randomnumber').undelegate("li", "click");
// Use a ajax request to save the values
$.ajax({
type : 'POST',
url : 'FBhighscore_hwnd.php',
dataType : 'json',
data: {
tgameid: $('#tgameid').val(),MyNumber: $('#MyNumber').val(),totalHits: hitCount
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(500);
if (data.error === true)
$('#loginForm').show(500);
else
$('#send').hide(500);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#loginForm').show(500);
}
});
}
}
$this.addClass('clicked');
});
return false;
});
Have you tried using .one() to bind your click events, instead of .click()? Here's the documentation for it: http://api.jquery.com/one/
If you bind the click event with .one() then you could ensure that the function will only be triggered once. Then, inside that function, rebind the events for all other boxes, thus ensuring that they have to click another box before click the same one again.
Alternately:
Use a combination of .hover() and setTimeout() (and possibly hoverIntent) to disable a box when the user hovers their mouse over it for too long.
EDIT
Have a look at this modified version of your jsFiddle: http://jsfiddle.net/Ender/9ffTA/
Clicking on the same box twice in a row is disallowed. Hopefully you can use that as a guide.
Inside of your click you can mark that box as "locked" and just disable it until the next click.
That will not solve your problem. The user can still just move to another box and wait for their number to appear in that box. I just did it myself on your site. I don't believe there is a solution to your problem with the current game design.
I don't think the problem is with clicking, but with scoring.
Your proposed solution doesn't really defeat "waiting" as a strategy, as Drew points out. To really fix waiting, you need to give it a penalty.
Were it my game, I'd have three scoring metrics — correctly clicked boxes (what you're currently calling "hits"), incorrectly clicked boxes (... "misses"), and unclicked boxes (not in your current game). In other words, if my number is 5 and a box containing a 5 fades (is replaced by another number) before I click it, that's counted against me.
With this scoring system in place, anyone who simply hovers over a box and waits — even if they switch boxes between clicks — will watch their score get lower and lower as they miss boxes.

Categories