jQuery: $.post not loading data from external php file - javascript

I'm trying to create a script that calculates data from a form loaded using jQuery post but my script is not working as expected.
This is my code:
//main file
function updateForm(monthsunpaid, unpaiddue, nodelay, tpenalty, idpostsave, code) {
$.post("updatedata.php", {
monthsunpaid: monthsunpaid,
unpaiddue: unpaiddue,
nodelay: nodelay,
tpenalty: tpenalty,
idpostsave: idpostsave,
code: code
})
.done(function(data) {
$(".table1").empty().append(data);
$('#myModaledit').modal('hide');
});
}
<script >
// want to make this code work
$(document).ready(function() {
$("#nodelay").change(function() {
var unpaiddue = $("#unpaiddue").val();
var nodelay = $("#nodelay").val();
var result = Number(unpaiddue) * Number(nodelay) * 0.05;
var result = Math.round(result * 100) / 100;
$("#tpenalty").val(result);
});
});
</script>
This data is from a php file load using the updateForm() function:
<form method="post">
<div class="form-group">
<label for="usr">UNPAID MONTHS</label>
<input type="text" class="form-control" id="monthsunpaid" value="<?php echo $delayed_months; ?>">
</div>
<div class="form-group">
<label for="pwd">UNPAID MONTHLY DUES</label>
<input type="text" class="form-control" id="unpaiddue" value="<?php echo $unpaid_monthly; ?>">
</div>
<div class="form-group">
<label for="pwd">NO. OF MONTHS DELAYED</label>
<input type="text" class="form-control" id="nodelay" value="<?php echo $months_delayed; ?>">
</div>
<div class="form-group">
<label for="pwd">TOTAL PENALTY CHARGES EQUITY</label>
<input type="text" class="form-control" id="tpenalty" value="<?php echo $totalpenalty; ?>">
</div>
<input type="hidden" id="idpostsave" value="<?php echo $id; ?>">
<input type="hidden" id="code" value="<?php echo $biscode; ?>">
<div class="form-group">
<button type="button" class="btn btn-primary" id="saveButton"
onclick="updateForm($(monthsunpaid).val(), $(unpaiddue).val(), $(nodelay).val(), $(tpenalty).val(), $(idpostsave).val(), $(code).val())">SAVE</button>
</div>
</form>

Bind your event as delegate. Change your code to this and hope so it will help you.
$(document).ready(function() {
$("document").on("#nodelay", "change", function() {
var unpaiddue = $("#unpaiddue").val();
var nodelay = $("#nodelay").val();
var result = Number(unpaiddue) * Number(nodelay) * 0.05;
var result = Math.round(result * 100) / 100;
$("#tpenalty").val(result);
});
});

I would suggest the following changes to your code to avoid issues that can be caused by mixing inline javascript and jquery. Consider delegating all event binding logic to jquery (rather than using on onclick in your forms HTML) by doing the following:
//main file
function updateForm(monthsunpaid, unpaiddue, nodelay, tpenalty, idpostsave, code){
$.post( "updatedata.php", {
monthsunpaid:monthsunpaid,
unpaiddue:unpaiddue,
nodelay:nodelay,
tpenalty:tpenalty,
idpostsave:idpostsave,
code:code
})
.done(function( data ) {
$( ".table1" ).empty().append( data );
$('#myModaledit').modal('hide');
});
}
// Shorthand for JQuery is now ready
$(function(){
$(document).on('change', "#nodelay", function(){
var unpaiddue = $("#unpaiddue").val();
var nodelay = $("#nodelay").val();
var result = Number(unpaiddue) * Number(nodelay) * 0.05;
var result = Math.round(result * 100) / 100;
$("#tpenalty").val(result);
});
// Attach a submit handler to your form, which is called
// when the user submits the form
$(document).on('submit', 'form', function() {
updateForm(
$('#monthsunpaid').val(),
$('#unpaiddue').val(),
$('#nodelay').val(),
$('#tpenalty').val(),
$('#idpostsave').val(),
$('#code').val()
);
// Prevent default form submit behaviour
return false;
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<form method="post">
<div class="form-group">
<label for="usr">UNPAID MONTHS</label>
<input type="text" class="form-control" id="monthsunpaid" value="<?php echo $delayed_months; ?>">
</div>
<div class="form-group">
<label for="pwd">UNPAID MONTHLY DUES</label>
<input type="text" class="form-control" id="unpaiddue" value="<?php echo $unpaid_monthly; ?>">
</div>
<div class="form-group">
<label for="pwd">NO. OF MONTHS DELAYED</label>
<input type="text" class="form-control" id="nodelay" value="<?php echo $months_delayed; ?>">
</div>
<div class="form-group">
<label for="pwd">TOTAL PENALTY CHARGES EQUITY</label>
<input type="text" class="form-control" id="tpenalty" value="<?php echo $totalpenalty; ?>">
</div>
<input type="hidden" id="idpostsave" value="<?php echo $id; ?>">
<input type="hidden" id="code" value="<?php echo $biscode; ?>">
<div class="form-group">
<!-- replace button with input, leave event binding to jquery -->
<input type="submit" value="SAVE" class="btn btn-primary" id="saveButton" />
</div>
</form>

Related

how to set unique id for multiple form using JQuery and PHP

i have more than 1 form in my page. i submit this forms using ajax to database. the problem is each of this form should have unique id in order to submit with ajax(JQuery id selector), and the first form always get submitted using ajax and other form submitted with php. how can i have unique id for each form and submit all forms with AJAX?
<form action="inc/new.comment.php" method="post" id="new_comment_answer_form">
<textarea name="new_answer" id="new_answer" cols="30" rows="10" placeholder="enter your new answer"></textarea>
<!-- <input type="text" name="comment_author" id="comment_author" placeholder="author name"> -->
<input type="hidden" name="post_id" id="post_id" value="<?php echo $post_id ?>">
<input type="hidden" name="comment_id" id="comment_id" value="<?php echo $comment_id ?>">
<input type="submit" name="submit_answer" value="send" id="submit_answer">
</form>
<p id="new_answer_result"></p>
jQUERY:
$("#new_comment_answer_form").submit(function (e) {
e.preventDefault();
var new_answer = $("#new_answer").val();
var submit_answer = $("#submit_answer").val();
var post_id = $("#post_id").val();
var comment_id = $("#comment_id").val();
$(document).ajaxStart(function () {});
$(document).ajaxComplete(function () {});
$.post("./inc/new.comment.php", {
new_answer: new_answer,
submit_answer: submit_answer,
post_id: post_id,
comment_id: comment_id
}, function (data, status) {
$("#new_answer_result").html(data);
$("#new_answer").val("");
});
});
use of this code is comment on other comments in a blog site.(if that helps)
You can give for each your form unique IDs, but set the same class, for example class="submit_form". Next you should call the function by this class. Other fields you can call by names.
$(".submit_class").submit(function (e) {
e.preventDefault();
var new_answer = $(this).find("[name=new_answer]").val();
var submit_answer = $(this).find("[name=submit_answer]").val();
var post_id = $(this).find("[name=post_id]").val();
var comment_id = $(this).find("[name=comment_id]").val();
$(document).ajaxStart(function () {});
$(document).ajaxComplete(function () {});
$.post("./inc/new.comment.php", {
new_answer: new_answer,
submit_answer: submit_answer,
post_id: post_id,
comment_id: comment_id
}, function (data, status) {
$("#new_answer_result").html(data);
$(this).find("[name=new_answer]").val("");
});
});
I am guessing you have the form creation code in loop.
try this..
<?php i=0; // take post_id, if you want ?>
<form action="inc/new.comment.php" method="post" id="new_comment_answer_form_<?php echo ++i; ?>">
<textarea name="new_answer" id="new_answer" cols="30" rows="10" placeholder="enter your new answer"></textarea>
<!-- <input type="text" name="comment_author" id="comment_author" placeholder="author name"> -->
<input type="hidden" name="post_id" id="post_id" value="<?php echo $post_id ?>">
<input type="hidden" name="comment_id" id="comment_id" value="<?php echo $comment_id ?>">
<input type="submit" name="submit_answer" value="send" id="submit_answer">
</form>
<p id="new_answer_result"></p>
You will have different id as "new_comment_answer_form_1", "new_comment_answer_form_2".
You can submit multiple forms with php as well.
at the top of your file.php
if(isset($_POST['btnName1'])){
... manipulate form's content
}elseif(isset($_POST['btnName2'])){
... manipulate another forms content
}
then later on in your file have the forms, they don't even need ID, php will recognise form by button name tag
<form method="POST">
<input type="text" name="inputField">
<input type="submit" name="btnName1">
</form>
<form method="POST">
<input type="text" name="inputField">
<input type="submit" name="btnName2">
</form>

Opencart 2.0 Product Quantity add/minus not working

I have a website, however the +/- buttons don't seem to work. I've not changed any of the code from the theme (Zorka), but I can't figure out how to fix the issue. Can someone please help?
Here's the website page: Webiste
The product.tpi looks like this:
<div class="quantity-form form-group">
<?php if (!$kuler->getSkinOption('show_number_quantity')) { ?>
<button type="button" id="qty-dec" class="quantity__button">-</button>
<input type="text" name="quantity" size="2" value="<?php echo $minimum; ?>" />
<button type="button" id="qty-inc" class="quantity__button">+</button>
<?php } else { ?>
<button type="button" id="qty-dec" class="quantity__button">-</button>
<input type="text" name="quantity" size="2" class="dynamic-number" value="<?php echo $minimum; ?>" data-min="<?php echo $minimum; ?>"/>
<button type="button" id="qty-inc" class="quantity__button">+</button>
<?php } ?>
<input type="hidden" name="product_id" size="2" value="<?php echo $product_id; ?>" />
</div>
and the product.js looks like this:
// Quantity
$('.dynamic-number').each(function () {
var $input = $(this),
$dec = $($input.data('dec')),
$inc = $($input.data('inc')),
min = $input.data('min');
$dec.on('click', function () {
var val = parseInt($input.val());
if (val > min) {
$input.val(val - 1);
}
});
$inc.on('click', function () {
$input.val(parseInt($input.val()) + 1);
});
If you need more information, please let me know!

Javascript - change input value on click not working

Here's a div which represents cart item qty field:
<div class="cart_quantity_div">
<form action="cart.php" method="post">
<button class="cart_qty_controls" onclick="minusOne(qty_field_<?php echo $item_id; ?>)">-</button>
<input type="text" name="cart_item_qty" value="<?php echo $each_item['quantity']; ?>" size="1" maxlength="3" id="qty_field_<?php echo $item_id; ?>"/>
<input type="submit" name="qty_adjust_cart<?php echo $item_id; ?>" value="change" class="cart_qty_adjust_btn"/>
<input type="hidden" name="cart_item_to_adjust_qty" value="<?php echo $item_id; ?>"/>
</form>
</div>
It is a draft version so don't pay attention to submit and hidden inputs
And JS code:
function minusOne (input_id){
var subtracted_qty = document.getElementById(qty_field_id).value = document.getElementById(qty_field_id).value - 1;
document.getElementById(qty_field_id).value = subtracted_qty;
}
I want to change value of input text field by clicking minus button by -1. But for some reason it's not working.
Can you, please, review my code and find whats wrong with it. Or maybe there is some better ways to do such qty change..
Your code does not set the variable qty_field_id, nor does it use the variable input_id. If input_id is referring to the same value as PHP’s $item_id, then try adding the following line to the top of the JavaScript function:
var qty_field_id = "qty_field_" + input_id;
You shouldn't use inline javascript and you aren't referencing the correct element. Try this instead:
HTML:
<div class="cart_quantity_div">
<form action="cart.php" method="post">
<button class="cart_qty_controls" data-productId="<?php echo $item_id; ?>">-</button>
<input type="text" name="cart_item_qty" value="<?php echo $each_item['quantity']; ?>" size="1" maxlength="3" id="qty_field_<?php echo $item_id; ?>"/>
<input type="submit" name="qty_adjust_cart<?php echo $item_id; ?>" value="change" class="cart_qty_adjust_btn"/>
<input type="hidden" name="cart_item_to_adjust_qty" value="<?php echo $item_id; ?>"/>
</form>
</div>
JS:
[].slice.call(document.getElementsByClassName('cart_qty_controls')).forEach(function(el){
el.addEventListener('click', function(e) {
var id = e.target.getAttribute('data-productId');
document.getElementById('qty_field_' + id).value -= 1;
})
})

I am trying to auto update mysql database using ajax and no click button

My database is not updating dynamically. Am I missing something?
It was working before removing some field names and also it was updating the user records automatically. But now it seems some issue in updating dynamically.
Form javascript used for updating
<script type="text/javascript">
// JQUERY: Plugin "autoSumbit"
(function($) {
$.fn.autoSubmit = function(options) {
return $.each(this, function() {
// VARIABLES: Input-specific
var input = $(this);
var column = input.attr('name');
// VARIABLES: Form-specific
var form = input.parents('form');
var method = form.attr('method');
var action = form.attr('action');
// VARIABLES: Where to update in database
var where_val = form.find('#where').val();
var where_col = form.find('#where').attr('name');
// ONBLUR: Dynamic value send through Ajax
input.bind('blur', function(event) {
// Get latest value
var value = input.val();
// AJAX: Send values
$.ajax({
url: action,
type: method,
data: {
val: value,
col: column,
w_col: where_col,
w_val: where_val
},
cache: false,
timeout: 10000,
success: function(data) {
// Alert if update failed
if (data) {
alert(data);
} else { // Load output into a P
$('#notice').text('Updated');
$('#notice').fadeOut().fadeIn();
}
}
});
// Prevent normal submission of form
return false;
})
});
}
})(jQuery);
// JQUERY: Run .autoSubmit() on all INPUT fields within form
$(function(){
$('#ajax-form INPUT').autoSubmit();
});
</script>
<script type="text/javascript" src="materialise/js/jquery-1.8.0.min.js"></script>
<form id="ajax-form" class="autosubmit" method="POST" action="./php_parsers/ajax-update.php">
<div class="row">
<div class="input-field col s8">
<i class="mdi-editor-mode-edit prefix"></i>
<input type="text" name="firstname" >
<label for="firstname">Firstname: * <?php echo $firstname; ?></label>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<i class="mdi-editor-border-color prefix"></i>
<input type="text" name="lastname" value="<?php echo $lastname; ?>">
<label for="lastname">Lastname: *</label>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<i class="mdi-action-accessibility prefix"></i>
<input type="date" name="age" class="datepicker validate">
<label for="age">D.o.B *</label>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<i class="mdi-editor-mode-edit prefix"></i>
<label for="gender"><?php echo $sex; ?></label>
</div>
</div>
<input id="where" type="hidden" name="<?php echo $uname; ?>" value="<?php echo $uname; ?>" />
</form>
update php used
<?php
// DATABASE: Connection variables
include_once("../php_includes/check_login_status.php");
// DATABASE: Clean data before use
function clean($value) {
global $db_conx;
$value = preg_replace('#[^a-z0-9. ]#i', '', $value);
$value = mysqli_real_escape_string($db_conx, $value);
return $value;
}
// FORM: Variables were posted
if (count($_POST)) {
// Prepare form variables for database
foreach($_POST as $column => $value)
${$column} = clean($value);
// Perform MySQL UPDATE
$result = "UPDATE users SET ".$col."='".$val."' WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $result);
}
?>
below is the updated code working on my local...hope it will help you
did it without creating jquery plugin
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$('input').blur(function() {
var input = $(this);
var column = input.attr('name');
// VARIABLES: Form-specific
var form = input.parents('form');
var method = form.attr('method');
var action = form.attr('action');
// VARIABLES: Where to update in database
var where_val = form.find('#where').val();
var where_col = form.find('#where').attr('name');
var value = input.val();
// AJAX: Send values
$.ajax({
url: action,
type: method,
data: {
val: value,
col: column,
w_col: where_col,
w_val: where_val
},
cache: false,
timeout: 10000,
success: function(data) {
// Alert if update failed
if (data) {
alert(data);
} else { // Load output into a P
$('#notice').text('Updated');
$('#notice').fadeOut().fadeIn();
}
}
});
});
});
</script>
</head>
<body>
<form id="ajax-form" class="autosubmit" method="POST" action="./php_parsers/ajax-update.php">
<div class="row">
<div class="input-field col s8">
<i class="mdi-editor-mode-edit prefix"></i>
<input type="text" name="firstname" value="<?php echo $firstname; ?>">
<label for="firstname">Firstname: * </label>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<i class="mdi-editor-border-color prefix"></i>
<input type="text" name="lastname" value="<?php echo $lastname; ?>">
<label for="lastname">Lastname: *</label>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<i class="mdi-action-accessibility prefix"></i>
<input type="date" name="age" class="datepicker validate">
<label for="age">D.o.B *</label>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<i class="mdi-editor-mode-edit prefix"></i>
<label for="gender"><?php echo $sex; ?></label>
</div>
</div>
<input id="where" type="hidden" name="<?php echo $uname; ?>" value="<?php echo $uname; ?>" />
</form>
</body>
</html>
**Here’s the code example of a POST method call and AJAX database update –**
<div id="c">
<input id="text1" type="text" name="text1" />
<input id="submit" type="submit" name="submit" value="SAVE IT" />
</div>
<div id="cn">
</div>``
**Now we declare the JQuery code to make a POST call**
<script type="text/javascript">
$(document).ready(function () {
$('#submit').click(function(){
var ths = this;
var str = $(ths).siblings("#text1").val();
$.post("saveData.php", {t:str}, function(value){
$(ths).parent("#c").fadeOut("fast");
$(ths).parent("#c").siblings("#cn").html(value);
});
});
});
</script>
**This code block receive value and update database**
$t = $_POST['t'];
$link = mysql_connect(servername, username, password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(databasename, $link);
// Insert the data
$query2="INSERT INTO p_a_j(scrap) VALUES('$t')";
$results2 = mysql_query($query2, $link)
or die(mysql_error());
if(mysql_affected_rows()>=1){
echo '<span>You entered'.$t.'</span>'.
'Database updated'.
'Try this again'; }

how to append data returned from ajax call to a dynamically created div, among many divs of same class name

How do I append data returned from ajax call to a dynamically created div, which is among many divs of the same 'class name' ?
My HTML:
<div class="post_area">
<?php
$connObj = new Connection();
$conn = $connObj->getConnection();
$sql = ("select * from posts ");
$result = mysqli_query($conn, $sql);
if ( $result ) {
echo "<br><br>";
$rowcount = mysqli_num_rows($result);
for($i = 0; $i<$rowcount; $i++){
$row = mysqli_fetch_assoc($result);
?>
<h3>
<?php
echo $row['title']."<br>";
?>
</h3>
<?php
echo $row['description']."<br>";
?>
<div class="post_comments">
<div class="comments_only_box" id="cb">
//displaying comments dynamically
</div>
</div>
<input type="text" name="comment" class="form-control" class="input_comment">
<input type="button" value="comment" name="submit_comment" class="comm" data-id="<?php echo $present_id; ?>">
</div>
<?php $present_id = $row['id']; ?>
My ajax call:
<script>
$(document).ready(function () {
$(".comm").on('click', function () {
var id = $(this).data('id');
var comment = "helloworld";//example
$.ajax({
url: 'comment.php',
method: 'GET',
data: {
comment: comment,
id: id,
},
dataType: 'html',
success: function (data) {
console.log(data);
$('#cb').append(data);
}
});
});
});
</script>
When I append the data it's appended to all divs--but I want to append it only to the presently clicked div
When someone clicks your comment button, the click handler receives a reference to that specific element as this. Since that button is inside the div, you can use closest to find the div that contains the button, then update that div. E.g.:
$(".comm").on("click", function() {
var $div = $(this).closest("div.post_area");
// Do something with `$div`...
});
Live example:
$(".comm").on("click", function() {
var $div = $(this).closest("div.post_area");
var $input = $div.find("input[name=comment]");
var comment = $input.val();
$("<p>").text(comment).appendTo($div);
$input.val("").focus();
});
.post_area {
border: 1px solid #ddd;
height: 6em;
overflow: auto;
}
<p>Type in any of the comment boxes and click the button following it:</p>
<div class="post_area">
<input type="text" name="comment" class="form-control" class="input_comment">
<input type="button" value="comment" name="submit_comment" class="comm" data-id="...">
</div>
<div class="post_area">
<input type="text" name="comment" class="form-control" class="input_comment">
<input type="button" value="comment" name="submit_comment" class="comm" data-id="...">
</div>
<div class="post_area">
<input type="text" name="comment" class="form-control" class="input_comment">
<input type="button" value="comment" name="submit_comment" class="comm" data-id="...">
</div>
<div class="post_area">
<input type="text" name="comment" class="form-control" class="input_comment">
<input type="button" value="comment" name="submit_comment" class="comm" data-id="...">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Categories

Resources