I am trying to do update "refresh" div after click Submit button and also every 5 seconds. I checked some questions, but I could not find what I was looking for.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<?php
echo '<div id="refresh">';
while ($r = $q->fetch()):
echo 'Sender: ';
if($r['senderid'] == $a) {echo $query1['username'];}
elseif($r['senderid'] == $b) {echo $query2['username'];}
echo '</br>';
echo $r['message'];
echo '</br></br>';
endwhile;
echo '</div>';
?>
<form method="post">
<input type="hidden" name="a" value="<?php echo $a;?>">
<input type="hidden" name="b" value="<?php echo $b;?>">
<textarea name="message" rows="3" cols="30"></textarea><br><br>
<input id="submit" type="submit" value="Submit" />
</form>
<script>
$(document).ready( function() {
$("form").on("submit", function(e) {
e.preventDefault(); // Prevent default form submission action
$.post("submit.php", $("form").serialize()); // Post the data
$('textarea[name=message]').val('')
});
});
</script>
Please make some rudimentary investigation on $.post and setTimeout
Here is an example - there are a few questions you need to consider
var val = "";
function refreshDiv() {
var $text = $('textarea[name=message]');
val = $text.val() || val; // what to do if user clears the field?
if (val == "") return; // stop if nothing there
$.post("submit.php", $("form").serialize(),function(data) {
$("#refresh").html(data)); // show the data
setTimout(refreshDiv,5000); // call it again in 5 secs
// $text.val(''); // not sure about this...
});
}
$(function() {
$("form").on("submit", function(e) {
e.preventDefault(); // Prevent default form submission action
refreshDiv();
});
});
Related
I have a javascript code to call a confirm alert of javascript when check box is selected or deselected. If the user click on ok of the alert it will call another php file where in it will update the result to the database, But When I click on Cancel the check box will be clicked which should not be performed.
If I click on cancel there should not be action performed on check box.
<script>
function ConfirmActiveInactive(){
return confirm("Activate/Deactivate user?");
}
</script>
<script>
$(document).ready(function(){
$("#activeinactive").on("change", "input:checkbox", function(){
$("#activeinactive").submit();
});
});
</script>
<form method="post" id="activeinactive" action="activeInactive.php" onsubmit="return ConfirmActiveInactive()">
<?php
while($userdetails = mysqli_fetch_array($user_details, MYSQLI_ASSOC)){
echo '<tr>';
echo '<td>
<span class="custom-checkbox">';
if($userdetails['is_active']==true){
echo '<input type="checkbox" name="options[]" value="'.$userdetails['member_id'].'" checked=checked>
<label></label>';
}
else{
echo '<input type="checkbox" name="options[]" value="'.$userdetails['member_id'].'">
<label></label>';
}
echo '</span>
</td>';
echo '</tr>';
}
?>
</form>
Change code to this:
<script>
$(document).ready(function(){
$("#activeinactive").on("change", "input:checkbox", function(e){
if(ConfirmActiveInactive())
{
$("#activeinactive").submit();
}
else
{
if($(this).is(':checked'))
$(this).prop('checked', false);
else
$(this).prop('checked', true);
}
});
});
</script>
I have multiple form like this:
<?php for ($i = 0; $i > $n; $i++) { ?> // n is no. of value (no limit)
<form>
<input name="<?php echo $i; ?>venue" type="text">
<input name="roster" type="text">
<input type="submit" name="btn_venue">
</form>
<?php } ?>
<form>
<input name="hospitality" type="text">
<input name="template" type="text">
<input type="submit" name="btn_hospitality">
</form>
...
...
<form>
<input name="element" type="text">
<input name="alignment" type="text">
<input type="submit" name="btn_xyz">
</form>
I want validate(field should not be blank) in all form so, how can I use validation ?
I tried jQuery validation:
<script>
$('document').ready(function () {
$('form').each(function (key, form) {
$(form).validate({
rules: {
hospitality: {
required: true
},
//...
//...
alignment: {
required: true
}
});
});
});
</script>
I have manage static name field validation but I don't idea about dynamic venue name validation.Can anyone help me ?
if only one form the easily maintain but dynamically multiple form submit validate how to validate.
at a time only one form submit but particular form field validate how it is possible?
Try this. It goes through each form and for each of them through each input (of type text) and builds a required rule for each of them. Then feeds the dynamically built rules to the validate function.
$('document').ready(function () {
$('form').each(function (key, form) {
// build the rules object dynamically
var rules = {};
// loop through each input in the form
$(form).find('input[type="text"]').each(function(idx, obj) {
// make a rule for this input
rules[obj.name] = {"required": true};
});
$(form).validate({
"rules": rules
});
});
});
Okey this is not for sure the cleanest way to do this but its the first that cross my mind.
First, edit your html, so form has id="form$i", input has id="input$i", and submit has id="$i". Also add class to submit class="validate"
<?php for ($i = 0; $i > $n; $i++) { ?> // n is no. of value (no limit)
<form id="form<?php echo $i; ?>">//so id="form2" for example
<input id="input<?php echo $i; ?>" name="<?php echo i; ?>venue" type="text">// id="input2"
<input name="roster" type="text">
<input id="<?php echo $i; ?>" class="validate" type="submit" name="btn_venue">//id="2"
</form>
<?php } ?>
JQuery which should work, I'll explain each line in code
<script>
$(function () {
$(".validate").click(function () { //this is call for each click button with class validate
var id = $(this).attr('id');//getting id of the clicked element which is $i
var formid = 'form' + id;//creating new var formid which will target formid (for example: in first loop $i=1, so id=1, and formid=form1)
var input = 'input' + id;//creating input which value will be input$i
$('#' + formid).on('submit', function (e) {//on form submit validate function
if ($(#input).value == '') {
return false;
} else {
return true;
}
});
});
});
</script>
hope you understand logic, it might be I made mistake somewhere so take a close look..
I have an evaluation bar(progress bar generated by javascript), users can select a value and click to submit it. The issue is that I'm using PHP to generate the evaluation bars dynamically (using a do-while loop).
I can't figure out how to setup AJAX to recognized and submit any of the forms. Now it's submitting only the first one, even though I submit any of others.
My PHP code:
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);}
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form3")) {
$insertSQL = sprintf("INSERT INTO tblpersonalidad (idUser, idPost, intEvaluacion, dateFecha) VALUES (%s,%s,%s,%s)",
GetSQLValueString($_POST['idUser'], "int"),
GetSQLValueString($_POST['idPost'], "int"),
GetSQLValueString($_POST['intEvaluacion'], "int"),
GetSQLValueString($_POST['dateFecha'], "timestamp"),
);
mysql_select_db($database_conexionproject_poll, $conexionproject_poll);
$Result1 = mysql_query($insertSQL, $conexionproject_poll) or die(mysql_error());
$insertGoTo = "";
if (isset($_SERVER['QUERY_STRING'])) {
$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
$insertGoTo .= $_SERVER['QUERY_STRING'];
}
header(sprintf("Location: %s", $insertGoTo));
}
do {
<form id="form3" name="form3">
<div class="progress-user">
<div class="progress-bar-user progress-bar-danger-user"></div>
<div class="progress-bar-user progress-bar-warning-user"></div>
<div class="progress-bar-user progress-bar-success-user"><span class="rating">0%</span></div>
</div>
<input class="mi-input" name="intEvaluacion" type="hidden" value="" />
<input type="hidden" name="MM_insert" value="form3" />
<input type="hidden" name="intActivo" value="1" />
<input type="hidden" name="idPost" value="<?php echo $row_Datos_polls['idPost']; ?>" />
<input type="hidden" name="idUser" value="<?php echo $_SESSION['MM_IdUser']; ?>" />
</form>
} while ($row_Datos_polls = mysql_fetch_assoc($Datos_polls));
<script>
$('.progress-user').on('mousemove', function (e) {
var self = this;
var offset = $(self).offset();
var width = $(self).width();
var relX = Math.round(10 * (e.pageX - offset.left)/width) * 10;
setBarRating(self, relX);
$(self).siblings('.mi-input').val(relX);
});
$("#form3").submit(function(a) {
var url = "<?php echo $editFormAction; ?>"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $('#form3').serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
$('.progress-user').click(function() {
$("#form3").submit();
});
var setBarRating = function (self, percentage) {
$(self).find('.progress-bar-success-user span.rating').text(percentage + '%');
if (percentage <= 50) {
$(self).find('.progress-bar-danger-user').width(percentage + '%');
$(self).find('.progress-bar-warning-user').width(0);
$(self).find('.progress-bar-success-user').width(0);
} else if (percentage > 50 && percentage <= 80) {
$(self).find('.progress-bar-danger-user').width('50%');
$(self).find('.progress-bar-warning-user').width((percentage - 50) + '%');
$(self).find('.progress-bar-success-user').width(0);
} else if (percentage > 80) {
$(self).find('.progress-bar-danger-user').width('50%');
$(self).find('.progress-bar-warning-user').width('30%');
$(self).find('.progress-bar-success-user').width((percentage - 80) + '%');
}
};
</script>
I'll really appreciate any help. I haven't could realized what is the modification to the AJAX + PHP code. Many thanks for your time.
You’re generating several forms with id=”form3”. You’re also listening to $(“form3”).submit(). You’re submitting those forms by listening clicks to ‘.progress-user’:
$('.progress-user').click(function() { $("#form3").submit(); });
So, not matter wich .progress-user do you click on, the first #form3 will be the form submitted.
You should generate unique id’s to your forms and bars when creating them inside the loop. I.E;
$i = 0;
do {
<form id="<?php echo 'form' . $i ?>" name="<?php echo 'form' . $i ?>" class="progress-form">
<div class="progress-user" id="<?php 'progress-user' . $i; ?>" data-numer="<?php echo $i; ?>" >
<div class="progress-bar-user progress-bar-danger-user"></div>
<div class="progress-bar-user progress-bar-warning-user"></div>
<div class="progress-bar-user progress-bar-success-user"><span class="rating">0%</span></div>
</div>
<input class="mi-input" name="intEvaluacion" type="hidden" value="" />
<input type="hidden" name="MM_insert" value="form3" />
<input type="hidden" name="intActivo" value="1" />
<input type="hidden" name="idPost" value="<?php echo $row_Datos_polls['idPost']; ?>" />
<input type="hidden" name="idUser" value="<?php echo $_SESSION['MM_IdUser']; ?>" />
</form>
$i++; //dont forget this :-)
} while ($row_Datos_polls = mysql_fetch_assoc($Datos_polls));
Now you have several forms with its own unique id and several progress bars with its unique id and a data-number attribute. Also, the dinamically generated form have that 'progress-form' class.
So now you can listen to clicks on progress bars like before, then caching the data-number of that element:
$('.progress-user').click(function() {
var formNumber = $(this).attr('data-number');
$("#form" + fromNumber).submit();
});
This way, you can be sure the form being submitted is the one whose progress-bar was clicked. Now you should also modify your submit listener:
$('.progress-form').submit(function(e){
var url = "<?php echo $editFormAction; ?>";
var data = $(this).serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault();
});
So now you're serializing and sending only the form whose progress bar was clicked, and not the first '#form3' in the document.
Hope this helps.
I'm developing a web application and I want to get the answer(yes or no) from user when the deactivate button is pressed. I want to ask him if you want or not to deactivate the account. I'm using PHP to set active status to = 1 when deactivated and 0 to activated.
I want to get the result and verify in PHP if the query runs or not.
I would appreciate if someone helps me, thanks. Here is the code:
if(isset($_POST['desativar']))
{
$login = $_SESSION['login'];
mysqli_query($conexao,"UPDATE usuarios SET ativo_usuario = 1 WHERE login_usuario='$login'");
}
You can use onsubmit attribute.
Example
function confirmDesactiv()
{
return confirm("Are you sure ?")
}
<form method="POST" action="yourphp.php" onsubmit="return confirmDesactiv()">
<button type="submit">Delete my account</button>
</form>
try it.
function confirm_delete(){
if(confirm("Are you sure you want to delete this..?") === true){
return true;
}else{
return false;
}
}
<input type="button" Onclick="confirm_delete()">
You can use PHP to make something like a confirmation box. Below is a little smaple code to show you how:
<?php
session_start();
if (isset($_POST['submit'])) {
$_SESSION['postdata'] = $_POST;
header("Location: ".$_SERVER['PHP_SELF']);
exit;
} else if (isset($_POST['confirm']) && $_POST['confirm'] == 'yes') {
// Do stuff that should only be done after confirming
} elseif (isset($_POST['confirm']) && $_POST['confirm'] == 'no') {
// Cancelled, redirect back to page
header("Location: ".$_SERVER['PHP_SELF']);
exit;
}
?>
<?php if (isset($_SESSION['postdata']) && !isset($_POST['confirm'])): ?>
<form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>">
Are you sure you want to do this?<br />
<input type="submit" name="confirm" value="yes">
<input type="submit" name="confirm" value="no">
</form>
<?php else: ?>
<!-- Your form here -->
<?php endif; ?>
If you don't want to use AJAX, and assuming your page is called index.php:
<?
$deactivateStatusDisplay = "display: none"; // Initially, do not display a status.
$deactivateStatusMsg = ""; //Status message is initialized as blank.
$queryRan = false; // Just a flag to know if the user clicked deactivation link.
if( 1 === $_GET['deactivate'] ){
$deactivateStatusDisplay = "display: block";
$deactivateStatusMsg = "Your account will be deactivated.";
$queryRan = true;
}
?>
<!DOCTYPE html >
<html>
<head>
<!-- ALL YOUR METADATA -->
</head>
<body>
<div>Do you want to deactivate your account?</div>
DEACTIVATE
<div id="status" style="<? echo $deactivateStatusDisplay ?>"><? echo $deactivateStatusMsg ?></div>
</body>
</html>
**JS**
<script type="text/javascript">
function confirmDesactiv()
{
var flag = confirm("Are you sure ?");
if(flag)
window.open("yourphp.php?id=" + 1);
else
window.open("yourphp.php?id=" + 0);
}
</script>
**HTML**
<form method="POST" action="">
<button type="submit" onclick="confirmDesactiv()">Desactiv my account</button>
</form>
**PHP**
<?php
echo $_GET['id'];
if(isset($_GET['id']) && $_GET['id'])
{
//your update query will come here
}
?>
I have a product page whos products are created dynamically from mysql along with "add to cart" buttons and quantity inputs on each item. These items are submitted via AJAX. I'm able to submit the correct product but the success message returned from ajax uses a hidden div which hides the add to cart button then displays text that your item in now in the cart. It hides ALL of the cart button and shows the hidden div containing the success message in every form. Any help to solve this is appreciated!
My PHP/HTML
//inside while loop
?>
<div class="form">
<form action="cart_action.php" method="post" name="form" id="form_<?php echo $item_no; ?>">
<input type="hidden" class="text" name="order_code" value="<?php echo $item_no; ?>" id="order_code<?php echo $item_no; ?>" />
<input type="hidden" class="text" name="minorder" value="<?php echo $min; ?>" id="min_<?php echo $item_no; ?>" />
<br><br><div style="float:left; padding:5px;"><b>Qty</b>: <input class="text" type="text" name="quantity" value="<?php echo $min; ?>" size="3" id="quan_<?php echo $item_no; ?>" ?></div>
<div id="status"></div>
<input type="image" src="images/add_to_cart.png" class="psubmit" alt="submit" name="submit" id="submit_<?php echo $item_no; ?>" />
</div><div class="added"><b><div style="color: rgb(85, 176, 90);"><br /><b>Added to Cart </b>(View Cart)</div></b></div>
</form>
<?php
} //end loop
JAVASCRIPT:
$(document).ready(function() {
$('form').submit(function(){
// Catching the DOM element which trigger the event
var $form = $(this);
var orderCode = $form.find('input[name=order_code]');
var quantity = $form.find('input[name=quantity]');
var minOrder = $form.find('input[name=minorder]');
if (quantity.val() == '') {
quantity.addClass('hightlight');
$form.find("#status").html('<font color="red">Please Enter A Quantity!</font>');
return false;
} else quantity.removeClass('hightlight');
if (quantity.val() % minOrder.val()) {
quantity.addClass('hightlight');
$form.find("#status").html('<font color="red">Invalid Multiple!</font>');
return false;
} else quantity.removeClass('hightlight');
//organize the data properly
var data = 'order_code=' + orderCode.val() + '&quantity=' + quantity.val();
//disabled all the text fields
//$('.text').attr('disabled','true');
//show the loading sign
$('.loading').show();
//start the ajax
$.ajax({
//this is the php file that processes the data and send mail
url: "cart_action.php",
//GET method is used
type: "GET",
//pass the data
data: data,
//Do not cache the page
cache: false,
//success
success: function (html) {
//if process.php returned 1/true (send mail success)
if (html==1) {
//hide the form
$('.form').fadeOut('slow');
//show the success message
$('.added').fadeIn('slow');
//if process.php returned 0/false (send mail failed)
} else
//hide the form
$('.form').fadeOut('slow');
//show the success message
$('.added').fadeIn('slow');
}
});
//cancel the submit button default behaviours
return false;
e.preventDefault();
});
});
In your success handler, change the selectors to start from $form:
$form.fadeOut('slow');
$form.children('.added').fadeIn('slow');