Specific Form submit on onChange event in CodeIgniter - javascript

I am working on POS web.
creating form for each item in cart/order i.e multiple forms in loop and giving them unique ids ('id'=>'cart_'.$line )(cart_1,cart_2).
and created an update link in loop for each form. code below
echo form_open($controller_name."/edit_item/$line", array('class'=>'form-horizontal', 'id'=>'cart_'.$line));
echo form_input(array('name'=>'quantity','value'=>$item['quantity'],'size'=>'2', 'id'=>'quantity','class'=>'form-control'));
echo form_input(array('name'=>'discount','value'=>$item['discount'],'size'=>'3', 'id'=>'discount', 'class'=>'form-control'));?>
<a href="javascript:document.getElementById('<?php echo 'cart_'.$line ?>').submit();" id="anchor" title=<?php echo $this->lang->line('sales_update')?> >
This fulfils the update requiremnt like when I update a quantity and click the link it updates the price.
But now the problem is that I want my form to submit on onChange event of quantity field.
1) First Try
<script type="text/javascript">
$("#quantity,#discount").on('change',function(){
var quantity=$("#quantity").val();
var discount=$("#discount").val();
if(quantity!=""&&discount!=""){
document.getElementById('anchor').click();
console.log('form send');
}
});
</script>
this is what I tired but it only works if there is only one item in order
2)Second try
function updateQuantity(anchorID){
if(anchorID != ""){
document.getElementById(anchorID).click();
}
}
echo form_input(array('name'=>'quantity','value'=>$item['quantity'],'size'=>'2', 'onChange'=>'updateQuantity(HERE I WANT TO PASS "anchorID_LOOP VALUE")' 'id'=>'quantity','class'=>'form-control'));
<a href="javascript:document.getElementById('<?php echo 'cart_'.$line ?>').submit();" id='<?php echo 'anchorID_'.$line ?>' title=<?php echo $this->lang->line('sales_update')?> >

Rather than triggering a button.click() You should try the following:
echo form_open($controller_name."/edit_item/$line", array('class'=>'form-horizontal line-item', 'id'=>'cart_'.$line));
echo form_input(array('name'=>'quantity','value'=>$item['quantity'],'size'=>'2', 'id'=>'quantity','class'=>'form-control cartline', 'data-form' => $line));
echo form_input(array('name'=>'discount','value'=>$item['discount'],'size'=>'3', 'id'=>'discount', 'class'=>'form-control cartline', 'data-form' => $line));?>
<a href="javascript:document.getElementById('<?php echo 'cart_'.$line ?>').submit();" id="anchor" title=<?php echo $this->lang->line('sales_update')?> >
Notice I gave the form control an extra class and a data- attribute to hold the $line variable
So now I can catch the event and submit the form
$(function(){
$('.cartline').change(function(){
var line = $(this).attr('data-form');
$('#cart_' + line).submit();
});
});
To send the form via AJAX, you have to handle the form submit function (I gave the form a new class line-item)
$(".line-item").submit(function(event) {
event.preventDefault();
var line_form = $( this ),
url = line_form.attr( 'action' );
//Make your data
$.post( url, { data-field1: $('text1').val(), data-field1: $('text2').val() }, function(data){
alert('Form Posted')
});
});

Related

AJAX POST Success div upload disappears after a few seconds

I am having issue after a successful AJAX post, where the updated div disappears after a few moments
Below are the jquery/PHP/POST data in succession.
Button On Click Function:
function Delete_ID(clickBtnValue,clickBtnID,clickBtnName) {
var my_data = {"passvalue": clickBtnValue, "passid":clickBtnID, "passname":clickBtnName};
$.ajax({
type: 'POST',
url: '../Programs/Programs.php',
data: my_data,
success: function (data) {
$('#ProgramsTable').load("../Programs/ProgramChange.php");
$('#update-div').html(data);
}
});
}
PHP DIV display:
$list_programs = DB_Get_Program_List();
if (!is_null($list_programs)) {
$html = '<br><div id="ProgramsTable"><div class="TABLE">';
for ($ii=0; $ii < count($list_programs); $ii++) {
$html .= <<<HTML
<div class="CELL">
<form method="post" action>{$list_programs[$ii]["Program_Name"]}
<button onclick="Delete_ID('Delete','{$list_programs[$ii]["Name_Hash"]}', '{$list_programs[$ii]["Program_Name"]}')" class="button">Delete</button>
<button onclick="Delete_ID('Edit','{$list_programs[$ii]["Name_Hash"]}', '{$list_programs[$ii]["Program_Name"]}')" class="button">Edit</button>
</form>
</div>
HTML;
}
}
echo $html;
echo "</div></div><div id='update-div'></div>";
POST in Programs.php:
if (!empty($_POST)) {
if ($_POST['passvalue'] == "Delete"){
DB_Delete_Program_list($_POST['passid']);
echo $_POST['passname'] . " has been deleted";
}
if ($_POST['passvalue'] == "Edit"){
echo ' <div class="form_div"><form class="Edit_form" method="post">';
echo ' <div style="margin-top:5px"><input type="text" style="height:20px;" id="'.$_POST['passid'].'" value="'.$_POST['passname'].'" size="40" maxlength="253"></div>';
echo ' <div style="margin-top:10px"></div>';
echo ' <div ><input class="form_submit" type="Submit" name="Edit_button"></div>';
echo ' </form></div>';
}
return true;
}
When I press delete, it will display for example "Program 1 has been deleted" and then disappear
When I press edit, the new form table and display and then disappear
Here is a screen record of my issue
What do I need to change, to make it so my div data "table" refreshes with the latest SQL data while also keeping the success text message?
DSICLAIMER
Yes I am aware that the EDIT POST option is not how it's supposed to be, as I am just testing the success message return.
Yes there is SQL mitigation in place
I believe what's happening is when you click your button, you're submitting the form while also triggering your Delete_ID function. So, what happens is the JS function executes and displays your div, but the page also reloads, so you only see it for a moment. What you need to do is to call preventDefault() on the event that is generated by the onclick event.
As a tangent, to make passing the data to your Delete_ID function easier, I'd recommend using data attributes rather than passing the data as properties to the function itself.
This is how I'd redo your code.
For your form buttons, remove the onclick attribute, and use the data- attributes for relevant properties. I also added delete-button and edit-button classes to each button to distinguish them.
$list_programs = DB_Get_Program_List();
if (!is_null($list_programs)) {
$html = '<br><div id="ProgramsTable"><div class="TABLE">';
for ($ii=0; $ii < count($list_programs); $ii++) {
$html .= <<<HTML
<div class="CELL">
<form method="post" action>{$list_programs[$ii]["Program_Name"]}
<button data-name-hash="{$list_programs[$ii]["Name_Hash"]}" data-program-name="{$list_programs[$ii]["Program_Name"]}" class="button delete-button">Delete</button>
<button data-name-hash="{$list_programs[$ii]["Name_Hash"]}" data-program-name="{$list_programs[$ii]["Program_Name"]}" class="button edit-button">Edit</button>
</form>
</div>
HTML;
}
}
echo $html;
echo "</div></div><div id='update-div'></div>";
Then in your javascript, assign the on-click function to buttons with the matching class. This allows you to access the click event in that function.
$('.delete-button').click(Delete_ID);
Now, update the function definition to use the click event and pull the data from data attributes:
function Delete_ID(event) {
event.preventDefault(); // Stop the form from submitting so the page doesn't reload
const clickedBtn = event.target; // This is a reference to the <button> itself.
const clickBtnValue = 'Delete'; // You could pass this via data attributes too; I assume you'll probably have a separate Edit_ID function though.
// Pull the values from the `data-` attributes on the clicked button
// Note that JS converts the kebab-case attribute names (eg: data-name-hash) to camelCase with "data" removed (eg: nameHash).
const clickBtnID = clickedBtn.dataset.nameHash;
const clickBtnName = clickedBtn.dataset.programName;
var my_data = {"passvalue": clickBtnValue, "passid":clickBtnID, "passname":clickBtnName};
$.ajax({
type: 'POST',
url: '../Programs/Programs.php',
data: my_data,
success: function (data) {
$('#ProgramsTable').load("../Programs/ProgramChange.php");
$('#update-div').html(data);
}
});
}
Here's a very basic JSFiddle example of using preventDefault with data attributes.
you need to prevent your form to be submitted when you press Delete/Edit button, you can do it by remove form tag
$list_programs = DB_Get_Program_List();
if (!is_null($list_programs)) {
$html = '<br><div id="ProgramsTable"><div class="TABLE">';
for ($ii=0; $ii < count($list_programs); $ii++) {
$html .= <<<HTML
<div class="CELL">
{$list_programs[$ii]["Program_Name"]}
<button onclick="Delete_ID('Delete','{$list_programs[$ii]["Name_Hash"]}', '{$list_programs[$ii]["Program_Name"]}')" class="button">Delete</button>
<button onclick="Delete_ID('Edit','{$list_programs[$ii]["Name_Hash"]}', '{$list_programs[$ii]["Program_Name"]}')" class="button">Edit</button>
</div>
HTML;
}
}
echo $html;
echo "</div></div><div id='update-div'></div>";
or return false on button click event
$list_programs = DB_Get_Program_List();
if (!is_null($list_programs)) {
$html = '<br><div id="ProgramsTable"><div class="TABLE">';
for ($ii=0; $ii < count($list_programs); $ii++) {
$html .= <<<HTML
<div class="CELL">
<form method="post" action>{$list_programs[$ii]["Program_Name"]}
<button onclick="Delete_ID('Delete','{$list_programs[$ii]["Name_Hash"]}', '{$list_programs[$ii]["Program_Name"]}'); return !1" class="button">Delete</button>
<button onclick="Delete_ID('Edit','{$list_programs[$ii]["Name_Hash"]}', '{$list_programs[$ii]["Program_Name"]}'); return !1" class="button">Edit</button>
</form>
</div>
HTML;
}
}
echo $html;
echo "</div></div><div id='update-div'></div>";

Submit ajax request form on select change wordpress

I have a select option to filter posts by category. On select change I want the ajax request to be sent and load the posts of the category selected. I currently have this working using a submit button, but I need this to work on select option change, but I cannot get it to work just using a select.
Below is the script and form i'm working with that works on submit using a button.
<form action="<?php echo site_url(); ?>/wp-admin/admin-ajax.php" method="POST" id="filter" class="ghost-select">
<?php
if( $terms = get_terms( 'category', 'orderby=name' ) ) :
echo '<select id="categoryfilter" name="categoryfilter"><option>Select category...</option>';
foreach ( $terms as $term ) :
echo '<option value="' . $term->term_id . '">' . $term->name . '</option>';
endforeach;
echo '</select>';
endif;
?>
<!-- <button>Apply filter</button> -->
<input type="hidden" name="action" value="myfilter">
<!-- onchange="this.form.submit();" -->
</form>
$('#filter').submit(function(){
var filter = $('#filter');
$.ajax({
url:filter.attr('action'), // ajax
data:filter.serialize(), // form data
type:filter.attr('method'), // POST
beforeSend:function(xhr){
// filter.find('button').text('Processing...'); // changing the button label
},
success:function(data){
// filter.find('button').text('Apply filter'); // changing the button label back
$('#response').html(data); // insert data
}
});
return false;
});
});
I have tired changing the initial submit function to the following, but it doesn't do anything:
$('#filter select').on('change', function() {
I've also tried adding onchange="this.form.submit();" to the select itself, but this submits the form and takes you away from the page to the url of the form action so I now know this isn't the right way to go.
I'm not sure what i'm missing so any help with this would be greatly appreciated!
Thanks

Page is refreshing and query won't take place - Ajax, PHP

function add_comment(ele) {
event.preventDefault();
var username = "<?php echo $current_user; ?>";
var user_id = "<?php echo $current_user_id; ?>";
var post_id = $(ele).data('id');
var comments = $(ele).parent(".comment-section").find(".comment").val();
alert(comments);
if (username == "") {
alert("Please Log in to Star the Post");
window.location = "http://tobbyandscooby.com/log.php";
return;
}
$.ajax({
type: 'POST',
url: 'add_comment.php',
data: {
postid: post_id,
uname: username,
uid: user_id,
comment: comments
},
success: function(response) {
//alert("Successfully Comment is Added! ");
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="comment-section">
<textarea id="<?php echo $post_id; ?>" class="comment" value="" data-id="<?php echo $post_id; ?>"></textarea>
<button id="btn" class="btn-default" data-id="<?php echo $post_id; ?>" onclick="add_comment(this);">Comment</button>
<div class="comment-show"></div>
</div>
<?php
include("connect.php");
$username = $_POST['uname'];
$post_id = $_POST['postid'];
$user_id = $_POST['uid'];
$comments = $_POST['comment'];
$sql = "INSERT INTO comments (user_id,username,post_id,comment) VALUES ($user_id,'$username',$post_id,'$comment')";
$result = $db->query($sql);
?>
I am trying to make a comment system with Ajax. I have done similar thing like favourite, down vote, upvote with Ajax. But now with this above code, I couldn't enter the data into the DB and also on clicking comment button the page refreshes even though I have used *preventDefault();
I know I have made some mistake but couldn't debug it. Also please suggest me how to add the entered comment into div .comment-show using the success in ajax.
**NOTE: I could get the alert(comments); working when preventDefault(); function is removed! I have added the XHR requests for other elements which are working fine! **
The problem is the preventDefault().
You now pass this with that function call in onClick.
To solve it, make the button a submit-button by adding <button type="submit" ..
and pass event with your function call: ...onClick="add_comment(event);"
// complete line:
<button type="submit" id="btn" class="btn-default" data-id="<?php echo $post_id; ?>" onclick="add_comment(event);">Comment</button>
But now you need to rewrite pieces of the function, because ele is now the event, not the element anymore:
Change every $(ele) to $('#id')
And obviously in the beginning of the function the variable name for the passed-in event needs to match:
function add_comment(e) { // whatever you wanna name it, e has to be the same
e.preventDefault(); // as this e
Another solution would be to keep the button just a normal button, remove the onClick there, and add onSubmit="add_comment(event);" to your <form..>

Like system: Looping forms unique id, getting these id's with jQuery/Javascript to post Individually

I'm just messing arround with simple PHP and Java by building my own Like system IP based.
Tryed looking for a solution, but no luck so far.
HTML generated forms in a while loop in php EOT obviously with every form unique id's. There are 25 forms with a Like button present. These forms are within a Bootstrap Modal. So because it is in a Modal, I do not want it to refresh the page and reset my Show More list. There for I'm trying to get all forms to be able to submit a Like by id by item using javascript. Code below.
Any suggestions or different approaches?
HTML - PHP While loop (forms within Modals):
<p id="result{$itemID}"></p>
<form enctype="multipart/form-data"
action="{$postLike}"
id="myform{$itemID}"
name="{$itemID}"
method="post">
<input type="hidden"
name="itemids"
value="{$itemID}">
<input type="hidden"
name="ips"
value="{$ips}">
<button id="submit-btn{$itemID}"
class="btn btn-{$optionLikeColor}" {$optionLikeDisabled}>
<span class="glyphicon glyphicon-thumbs-up glyphr"
aria-hidden="true">
</span> {$optionILikeText} {$likes}
</button>
</form>
PHP:
<?php
require 'init.php';
if($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['itemids'])){
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$itemsid = mysqli_real_escape_string($link, $_POST['itemids']);
$itemsip = $_SERVER['REMOTE_ADDR'];
if ($result = mysqli_query($link, "SElECT * FROM likes WHERE itemID='$itemsid' AND ip='$itemsip'")) {
$row_cnt = mysqli_num_rows($result);
if($row_cnt > 0){
echo 'You\'ve have already liked this item.';
} else {
$sql = "INSERT INTO likes (itemID, ip) VALUES ('$itemsid', '$itemsip')";
if(mysqli_query($link, $sql)){
echo 'Thank you!';
} else {
echo 'Something went wrong, try again later!';
}
}
}
} else {
echo 'Something went wrong, try again later!';
}
mysqli_close($link);
?>
Javascript working, but only for the first form:
So i'm guessing I need to pass the form / id variable into: $('#myform'), $('#insert'), $('#myform :input') and $('#result')
$('#myform').submit(function(){
return false;
});
$('#insert').click(function(){
$.post(
$('#myform').attr('action'),
$('#myform :input').serializeArray(),
function(result){
$('#result').html(result);
}
);
});
Javascript concept not working obviously:P Suggestions?
$("[id^='myform']").submit(function(){
var ID = $(this).attr('name');
return false;
});
$(document).ready(function(){
$(document).on('click','#submit-btn'+ID,function(){
$.post(
$('#myform'+ID).attr('action'),
$('#myform${ID} :input').serializeArray(),
function(result){ $('#result'+ID).html(result); }
);
});
});
Give all your forms the same class, or have some way to uniquely select those forms. You don't need unique ids for all those elements.
Then:
$(".myFormClass").on("submit", function () {
var $f = $(this); // the form that got submitted
$.post(
$f.attr('action'),
$f.find('input').serializeArray(),
function(result){
// not sure where you wanted the result.
// The point is that you should select it relative to the form $f that you already know.
$f.find('span').html(result);
}
);
});
Works like a charm! Thanks!
$('.myFormClass').submit(function(){
return false;
});
$('.myFormClass').click(function() {
var $f = $(this);
$.post(
$f.attr('action'),
$f.find('input').serializeArray(),
function(result){
$f.find('#submit-btn').remove(),
$f.find('#result').html(result);
}
);
});

Using ajax in for each loop to refresh a div content

Jquery/Ajax rookie here
This is how my code should work...
When the submit button is clicked, JavaScript handles the form and post the values to the same page. The values are used in a SQL query to update a column in the database. The value from the column is echoed out and updated each time the button is clicked (SQL UPDATE QUERY), all this would be done without refreshing the page using ajax (i.e "ONLY" the value from the database would be refreshed when the button is clicked and the page shouldn't scroll back to the top). The problem is my JavaScript isn't handling the form submission as i expect it to. The div around the value isn't refreshing, i have to redirect to a different page and back to see the changes (SQL query works). How do i solve my problem to achieve this?
file.php
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1
/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#ajaxform').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: "POST", // POST
url: "file.php", // the file to call
success: function(response) { // on success..
$('#emailform').html("Thank you!"); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
});
</script>
</head>
<body>
<?php
...................
foreach($stmt as $obj){
$id = $obj['id'];
$likes = $obj['like1'];
echo '<form action="" method="post" id="ajaxform"
enctype="multipart/form-data">';
echo '<input type="hidden" name="lkcv[]" value="'.$id.'">';
echo '<input type="hidden" name="like" value="">';
echo '<input type="image" src="images/like.png" id="lksub" width="15"
value="som" height="15" style="float:right;position:relative;
margin-right:290px;"/><div class="ld">'.$likes.'</div>';
echo '</form>’;
echo '<div id="emailform"></div>';
}
?>
</body>
</html>
query.php
<?php
if( isset( $_POST['lkcv'] ) && is_array( $_POST['lkcv'] ) )
{
$idArray = array();
foreach( $_POST['lkcv'] as $value )
{
$idArray[] = intval( $value );
}
$db->query( "UPDATE comment SET like1 = like1 + 1 WHERE id IN (".implode(
',', $idArray ).")" );
}
?>
NOTE: file.php always has a dynamic url such as "file.php?post=1"
I don't know php, so apologies if some of this is wrong.
does file.php write out a full html page? If so, it should only be sending out a fragment as ajax deals with partial updates rather than pulling in an entire page.
In your success handler, you are only updating the #emailForm div, when really you also want to be replacing the content on the page with the new version.
2nd, in html, tags with an id are expected to be unique. You output
<div id="emailForm"></div>
in a loop, therefore, it isn't unique on the page, so you might not get the right one being updated
There is a parameter for $.ajax called cache, setting that will append a timestamp to your query, ensuring it is unique, no need to manually create a unique url.
$.ajax({
cache: false,
....
Lastly, to make sure that you are getting fresh content, check your web server logs to look for a http response, which means that the content hasn't changed, so the webserver sent a cached copy
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1
/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#content').on("submit", "form", function(e) { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: "POST", // POST
cache: false,
url: "file.php?=" + $(e.currentTarget).find("name=lkcv[]").val(), // the file to call
success: function(response) { // on success..
$(e.currentTarget).html(response); // only replace the form that caused the submit
$('#emailform').html("Thank you!"); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
});
</script>
</head>
<body>
<?php
...................
echo '<div id=content>';
foreach($stmt as $obj){
$id = $obj['id'];
$likes = $obj['like1'];
echo '<form action="" method="post" enctype="multipart/form-data">';
echo '<input type="hidden" name="lkcv[]" value="'.$id.'">';
echo '<input type="hidden" name="like" value="">';
echo '<input type="image" src="images/like.png" id="lksub" width="15"
value="som" height="15" style="float:right;position:relative;
margin-right:290px;"/><div class="ld">'.$likes.'</div>';
echo '</form>’;
}
echo '</div>';
echo '<div id="emailform"></div>';
?>

Categories