Using ajax in for each loop to refresh a div content - javascript

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>';
?>

Related

Differentiate multiple form on AJAX

I have a php page with multiple form inside.
<form id="form_<?php echo $rowProduct['Product_ID'];?>">
<a id="wh_<?php echo $rowProduct['Product_ID'];?>"><i class="fal fa-heart"></i></a>
<input type="hidden" name="PID_<?php echo $rowProduct['Product_ID'];?>" value="<?php echo $rowProduct['Product_ID'];?>">
<input type="hidden" name="mail_<?php echo $rowProduct['Product_ID'];?>" value="<?php echo $rowProduct['Mail'];?>">
Those form generate from looping through all data on MySQL.
Every form and input has their unique id by Product_ID.
Below is ajax script to submit data to database.
<script>
$('[id^=wh_]').click(function(e) {
$.ajax({
url: 'submit.php',
type: 'POST',
data: $("[id^=form_]").serialize(),
success: function(data) {
alert('Success add item');
}
});
e.preventDefault();
});
</script>
Currently this code successfull to insert data to MySql, but the submited data always be the last form only whatever which submit button clicked.
I'm using AJAX to submit those forms to achieve a form submit without refreshing the php page.
Much appreciate for every help.
Try by changing this data: $("[id^=form_]").serialize(), to
data: $(this).closest('form').serialize()

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

Specific Form submit on onChange event in CodeIgniter

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')
});
});

Best way to submit multiple input fields jQuery/PHP?

I'm trying to upgrade my like-system to something more practical.
Currently I have it like Like then in the PHP have something like: if $_GET['like'] is set, then grab the user's ID and the post ID and call a function called like_status($post_id,$user_id);
However, I've been working on something like this:
The main part that shows on the statuses:
<script src="https://mysite/stuff/jquery.min.js"></script>
<script src="https://mysite/stuff/js/global.js"></script>
<input type="hidden" id="postid" value="<? echo $postid; ?>">
<input type="hidden" id="userid" value="<? echo $session_user_id; ?>">
<span id="like-button" style="color:red;">Like</span>
The Javascript/jQuery:
$('span#like-button').on('click', function(){
var postid = $('input#postid').val();
var userid = $('input#userid').val();
if (postid != ''){
$.post('https://mysite/stuff/ajax/like.php', {postid: postid, userid: userid}, function(data){
document.getElementById('like-button').innerHTML = data;
});
}
});
and finally,
My like.php script:
<?php
if(isset($_POST['postid']) === true && empty($_POST['userid']) === false){
include $_SERVER['DOCUMENT_ROOT'].'/stuff/init.php';
if(is_liked($_POST['postid'],$_POST['userid']) === true){
unlike_status($_POST['postid'],$_POST['userid']);
echo 'Like';
} else {
like_status($_POST['postid'],$_POST['userid']);
echo 'Unlike';
}
}
?>
My unlike/like functions work fine. I have a working like system now, but it makes the user refresh and everything every time, and it's very inconvenient. I'd like to use this method to automatically update the like button without having to refresh the page or anything. This way, users can like multiple things on the page, and not have to refresh the page every time. I also think it's more secure since the $_GET['like'] can be changed to any id, even if user's aren't friends with other users, or the status doesn't exist.
My issue:
Okay, so whenever I click the like button, nothing happens. I tried this in a separate page as well (changing the type from hidden to text, and manually inputting the data) and it didn't work either. It seems the javascript doesn't execute. I've opened up console in google chrome, and when I click the button, nothing happens. The like doesn't get posted to the database, and the button doesn't get updated.
Can anyone explain what I'm doing wrong? Possibly point me in the right direction to fixing this?
UPDATE
I tried combining the Javascript/HTML in one page to have dynamic variables.
This is what shows up for each status:
<script src="https://mysite/stuff/jquery.min.js"></script>
<script type="Javascript">
$(document.body).on('click','#like-button', function(
var postid<? echo $status_id; ?> = $('input#postid<? echo $status_id; ?>').val();
var userid<? echo $status_id; ?> = $('input#userid<? echo $status_id; ?>').val();
$.post('https://mysite/stuff/ajax/like.php', {postid: postid<? echo $status_id; ?>, userid: userid<? echo $status_id; ?>}, function(data){
document.getElementById('like-button').innerHTML = data;
});
));
</script>
<input type="hidden" id="postid<? echo $status_id; ?>" value="<? echo $status_id; ?>">
<input type="hidden" id="userid<? echo $status_id; ?>" value="<? echo $session_user_id; ?>">
<span id="like-button" style="color:red;"><? if(isliked($status_id,$session_user_id) === true){ ?>Unlike<? } else { ?>Like<?}?></span>
I still can't get it to execute the script.
You can always just use $('#fomrm_id').serialize(), to get all the form fields at once in POST data. It refreshes page because you have to add return false; to the end of jQuery.click event.
If those elements are being created dynamically (or as in your case script is being executed before they are created), you need to set proper .on event, this one is not good, as it binds to the element that may not be there.
Should be rather:
$(document.body).on('click','#like-button', function(){..}); - that will bind it to document body, that is always there, but will check for selector in second argument if it matches.
It's not exactly what I wanted to do, but it's good enough. I managed to get the like button to work/update without refreshing and such. Thanks to everyone for the help if it wasn't for your suggestions I would've never found this out.
<input type="hidden" id="postid" value="<? echo $status_id; ?>"><br>
<input type="hidden" id="userid" value="<? echo $session_user_id; ?>"><br>
<span id="like-button" style="color:red;"><? if(isliked($status_id,$session_user_id) === true){ ?>Unlike<? } else { ?>Like<? } ?></span>
<script>
$('span#like-button').on('click', function(){
var postid = $('input#postid').val();
var userid = $('input#userid').val();
<? if(isliked($status_id,$session_user_id) === true){ ?>
$.get('https://mysite/dash', {unlike: postid, userid: userid}, function(data){
document.getElementById('like-button').innerHTML = 'Like';
});
<? } else { ?>
$.get('https://mysite/dash', {like: postid, userid: userid}, function(data){
document.getElementById('like-button').innerHTML = 'Unike';
});
<? } ?>
});
</script>

External PHP data not passing through AJAX

I'm working on creating a simple online booking system using PHP and AJAX.
The current layout is:
Each booking grabs a preset list of items then users can add additional items that they need.
To do this I have set up an AJAX button that calls a new drop down list each time its clicked. (This means a page could have 1 additional item or even 20, depending on how many they need.)
Once the additional items have been selected, they can then submit the form and will be guided to a confirmation page that is meant to list what they have chosen.
The issue:
None of the data is being carried through from any of the drop down lists that get added.
My AJAX script and php code on page 1 is:
<script>
function changeIt()
{
$.ajax({
type: "POST",
url: "details.php"
}).done(function( result ) {
$("#msg1").append( "" +result);
});
}
</script>
<form name ="addequip" id="addequip" action="confirmbooking.php" method="post">
<input type='button' value="Add Item" onClick="changeIt()"/>
<div id="msg1"></div>
<input type='submit' value='submit'/>
details.php:
<?php
require_once("dbconn.php");
$sql = "SELECT REFERENCE, DESCRIPTION FROM descEquip";
$result = mysql_query($sql,$conn);
?>
<select name="equip">
<?php while ($row = mysql_fetch_array($result)) { ?>
<option value="<?php echo $row["REFERENCE"];?>"><?php echo $row["DESCRIPTION"];?></option><?php } ?>
</select>
And lastly my confirmation page is:
<?php $item = $_POST['equip']; ?>
<?php echo $item ?>
I'm not too sure if i need to add something to the AJAX script in order for this to work as intended or if something needs to be changed in the details.php? (I'm very new to AJAX)
I have viewed a previous question 'passing form data to mySQL through AJAX' and I couldn't make it work for me.
Lastly, for additional lists (when more than 1 item is required) do I need to have a feature that states each equip list have a different name? likename="equip<?php echo $i ?> where $i = 1++;
Any tips or examples would be appreciated,
thanks.
Never assume all will work as you want it - check if sth goes wrong in your code:
var jqxhr = $.ajax(
{
type: 'GET',
async: false,
url: 'details.php',
success: function(data, textStatus /* always 'success' */, jqXHR)
{
// ok if we are here it means that communication between browser and apache was successful
alert( 'on_ajax_success data=[' + data + '] status=[' + textStatus + ']' );
$("#msg1").innerHTML( result );
}
,
error: function(jqXHR, textStatus, errorThrown)
{
alert( 'ERROR: [operation failed]' );
}
});
Moreover - use Firefox with Firebug installed so that you can see your ajax queries/responces.

Categories