how to reload a div in jQuery - javascript

I have a div in which I have used submit button as follow :
<div id="collapse2" class="panel-collapse collapse">
<div class="panel-body">
<div class="logininput">
<?php do_action( 'woocommerce_checkout_billing' ); ?>
<button id="sendmail3" class="btn btn-info">Submit</button>
</div>
</div>
</div>
in this when I click on button sendmail3 then a jquery is triggered as follow :
jQuery("#sendmail3").click(function(){
var country = jQuery("#billing_country").val();
var address = jQuery("#billing_address_1").val();
var city = jQuery("#billing_city").val();
var state = jQuery("#billing_state").val();
//alert(state);
var pincode = jQuery("#billing_postcode").val();
var SecondData = "country="+country+"&address="+address+"&city="+city+"&state="+state+"&pincode="+pincode;
var currenturl = jQuery(location).attr('href');
var url = currenturl;
jQuery.ajax({
dataType : 'html',
type: 'GET',
url : url,
data : SecondData,
complete : function() { },
success: function(data)
{
jQuery("#collapse2").hide();
jQuery("#collapse3").show();
}
});
});
I have one more div collapse3 as follow :
<div id="collapse3" class="panel-collapse collapse">
<div class="panel-body">
<form name="checkout" method="post" class="checkout woocommerce-checkout" action="<?php echo esc_url( $get_checkout_url ); ?>" enctype="multipart/form-data">
<div id="hideform">
<?php do_action( 'woocommerce_checkout_billing' ); ?>
</div>
<h3 id="order_review_heading"><?php _e( 'Your order', 'woocommerce' ); ?></h3>
<?php do_action( 'woocommerce_checkout_before_order_review' ); ?>
<div id="order_review" class="woocommerce-checkout-review-order">
<?php do_action( 'woocommerce_checkout_order_review' ); ?>
</div>
<?php do_action( 'woocommerce_checkout_after_order_review' ); ?></div>
</form>
<?php do_action( 'woocommerce_after_checkout_form', $checkout ); ?>
</div>
In this div data is loaded dynamically
What I want is that when I click on sendmail3 button then only the div collapse3 should be reloaded. How can I reload this div only without refreshing the page

I think this will work.
success: function(data)
{
jQuery("#collapse2").hide();
jQuery("#collapse3").append(data); //I change this to .append() or try .html(data);
}
Hope this works.

You can use the load() method:
Load data from the server and place the returned HTML into the matched element.
$('.myDiv').load('urlToGetUpdatedContent');
A very clean way with built-in jQuery logic. See full documentation: http://api.jquery.com/load/

The idea is to fetch your page in specific div , like what you mentioned in your question by ajax call and then return the data to same div .
for example :
$("#sendmail3").click(function(){ var getdata= $("#collapse3").html(); ...
then make ajax call and put in the :
success: function(whatever-result) { $("#collapse3").html(getdata);...
that will only refresh the div with id
UPDATE
I think you are looking to send your form through this mentioned div then reload the div to show the form again , here is another solution :
$("yourform").submit(function(event){
var target =$(this).attr('action');
event.preventDefault();
$.post( target, $(this).serialize(), function(data){
$("#supposed-div").html(data);// this will force submitting this form only through this div
});
});
Then you can use JavaScript , JQuery or AJAX call ,it could be through the above code ,to let form come into div as it is .
At the beginning of this answer i used to suggest to get the $("div").html(); and put it as var getdata to be easy to put again into div.html after submission.

Related

getting the div which handles the post of my categories in wp jquery/ajax

I have a wp_list_categories which displays my categories of wordpress site. Now I manage to display the post of my wordpress categories from the wp_list_categories by enabling the user to onClick which category will be displayed by not reloading/refreshing the page. I have the code but i cannot get the specific div which contains my post, where it returns my wholepage to be displayed. The output of my code is the ajax/jquery returns the wholepage and put it inside my div id="inside". I want only to get the part of div id = "inside" which there is the post from the onclick category selected.
Here is my code:
$(document).ready(function(){
$.ajaxSetup({cache:true});
var $mainCategory = $('#inside'),
$cat_links = $('ul.categories-filters li a');
$cat_links.on('click', function (e) {
e.preventDefault();
$el = $(this);
var value = $el.attr("href");
$mainCategory.animate({opacity: "0.5"});
$mainCategory.load(value + "#inside", function() {
$mainCategory.animate({opacity: "1"});
});
});
});
my wp_list_categories and inside the div id="#inside" where the posts are there to be displayed.
<ul class="categories-filters">
<?php
$args2 = array(
'exclude' => array( 6,7,9 ),
'order' => 'DESC',
'title_li' => __(''),
);
wp_list_categories($args2);
?>
</ul>
</div>
<div class="col-md-8">
<div id="main-category" class="row row-left">
<?php if(have_posts()) :
$count = 0;
while(have_posts()) : the_post(); ?>
<div div id="inside" class="col-xs-3 col-box2">
<?php the_post_thumbnail('thumbnail'); ?>
</div>
<?php if($count==2) :
echo '</div>';
echo '<div class="row row-left">';
endif;
$count++; endwhile;
endif;
wp_reset_postdata();
?>
</div>
</div>
The issue is with how you use the jquery .load function
$mainCategory.load(value + "#inside", function() {
the documentation states that there needs to be a space between the URL and the "selector" to partially load the retrieved html
so, it's simply
$mainCategory.load(value + " #inside", function() {

After ajax passing data to php, page will not loading for the first entry, but still loading for the rest

In my webpage, I want to show all the items fetched form server, and under each item, their is a "Complete" button. When press the compete button, the id of the item will be send to a php file. The code for my form is:
<?php
$x = $NumberofItems;
while ($x > 0) :
?>
<p><i class="fa fa-question" style="color:#ffff00"></i> On <?php echo htmlspecialchars($date_Quest[$x])?>: <?php echo htmlspecialchars($desc_Quest[$x])?></p>
<form id="formQuestComplete" action="quest-complete.php" method="post" style="display: inline-block;">
<input type="hidden" name="QuestID" value="<?php echo $id_Quest[$x]; ?>"/>
<button id="subQuestComplete" class="btn btn-default btn-xs">Complete</button>
</form>
<?php
$x--;
endwhile;
?>
And my jquery code is :
$("#subQuestComplete").click( function() {
$.post( $("#formQuestComplete").attr("action"),
$("#formQuestComplete :input").serializeArray(),
function(info){ $("#result").html(info);
});
});
$("#formQuestComplete").submit( function() {
return false;
});
For example, when I have 10 items listed by the form, only the first item will send data and stay on the same page. All the rest will send data, but then redirect to the php page.
Change your PHP code to make sure item is given a class, instead of an id (because id's must be unique or they will not be handled correctly) -
<?php
$x = $NumberofItems;
while ($x > 0) :
?>
<p><i class="fa fa-question" style="color:#ffff00"></i> On <?php echo htmlspecialchars($date_Quest[$x])?>: <?php echo htmlspecialchars($desc_Quest[$x])?></p>
<form class="formQuestComplete" action="quest-complete.php" method="post" style="display: inline-block;">
<input type="hidden" name="QuestID" value="<?php echo $id_Quest[$x]; ?>"/>
<button class="subQuestComplete" class="btn btn-default btn-xs">Complete</button>
</form>
<?php
$x--;
endwhile;
?>
Then change your jQuery to handle the clicks appropriately (you do not have a submit, so eliminate the last function you show)-
$(".subQuestComplete").click( function(e) { // handle the button click
e.preventDefault(); // prevent the click's default action
var thisForm = $(this).parent('form'); // get this form
var thisData = $(this).parent('form').find('input').val();
$.post(
$(thisForm).attr("action"),
{QuestID: thisData}, // no need to serialize for a one value form
function(info){
$("#result").html(info);
});
});
Since the elements are now identified by class with can traverse the DOM tree to find the form value(s) for each form respctively - regardless of how many there may be in the page.
You have to modify your code like this:
.click( function(e) { e.preventDefault();
after this, the rest of your code.
If you dont do this, then the original click event handler also will run. after a time.
So your code should look like this:
$("#subQuestComplete").click( function(e) {
e.preventDefault();
$.post( $("#formQuestComplete").attr("action"), $("#formQuestComplete :input").serializeArray(),function(info){
$("#result").html(info);
});
});

inserting an ajax response into div

First time AJAX attempt.....
I am attempting to update a based on a selection made with a button.
I am currently just alerting the ID back, as that is all I can figure out what to do.
Is it possible to put the file my_page.php into the div with class "populated_info"?
Then when I press a different button, the page will function will run again, and populate the div with the new result. I have the my_page.php already built and running based on the ID, just can't get it to render in the correct place.
HTML:
<form name="gen_info">
<div class="body">
<div class="row">
<div class="col-md-2">
<table width="100%" class="border_yes">
<tr>
<td>
Last Name, First Name
</td>
</tr>
<?php
$result = mysqli_query($conn,"SELECT * FROM general_info");
while($row = mysqli_fetch_array($result))
{
$CURRENT_ID = $row['ID'];
$firstName = $row['firstName'];
$lastName = $row['lastName'];
?>
<tr>
<td>
<button type="button" class="btn btn-default custom" onclick="function1('<?php echo $CURRENT_ID;?>')"><?php echo $lastName.', '.$firstName; ?></button>
<!-- button that will run the function -->
</td>
</tr>
<?php
}
?>
</table>
</div>
<div class="col-md-10 populated_info"> <!-- WHERE I WOULD LIKE THE UPDATED INFORMATION -->
</div>
</div>
</div>
</form>
AJAX:
<script>
function function1(ID) {
$.ajax({
type: "POST",
url: "functions/my_page.php",
data: "ID="+ID,
success: function(resp){
alert(resp); //how to get this to put the page back into the right spot?
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>
Your approach:
With regards to your button, I'd suggest separating the inline Javascript handler to keep your HTML and Javascript separate. I'll use a custom data attribute to store the ID here:
<button type="button" class="btn btn-default custom mybutton" data-id="<?php echo $CURRENT_ID;?>">
<?php echo $lastName . ', ' . $firstName; ?>
</button>
Then jQuery:
$('.mybutton').click(function() {
var ID = $(this).data('id');
function1(ID);
});
Your AJAX request:
You can shorten that whole function and use $.load() to get the data into your div:
function function1(ID) {
// Get the output of functions/my_page.php, passing ID as parameter, and
// replace the contents of .populated_info with it
$('.populated_info').load('functions/my_page.php', { ID: ID });
}
Doesn't look like you need a callback function here, but if you do you can put it in after the data parameter. A useful application of a callback here might be for your error handler. See here how to implement one.
An an aside, if you're just getting data, you should probably be using the GET HTTP method instead of POST.
if you successfully get the response from the server just replace alert(resp) with $('.populated_info').html(resp);
<script>
function function1(ID) {
$.ajax({
type: "POST",
url: "functions/my_page.php",
data: "ID="+ID,
success: function(resp){
$('.populated_info').html(resp);
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>

Codeigniter: Retrieving data on button click with Ajax

I have a simple webpage which generates a random quote from my database upon refreshing the page. I wish to implement some AJAX and JQuery in order to generate quotes via the button rather than having to refresh the page. I have done some research but I am not sure how to implement this in Codeigniter. My current code is below...
Page controller:
public function index() {
$this->load->model('quote_model', '', TRUE);
$data['quotes'] = $this->quote_model->getRandom();
$this->load->view('home', $data);
}
The view:
<?php include ('layout/header.php'); ?>
<div class="container-fluid">
<div class="row">
<div class="col-md-4 quote-holder">
<img src="application/assets/alan1.jpg" alt="..." class="img-circle img-responsive">
<br>
<blockquote class="text-center">
<p><?php echo $quotes[0]['quote']; ?></p>
<footer class="text-center"><?php echo $quotes[0]['character_name']; ?> in <cite title="Source Title"><?php echo $quotes[0]['series_name']; ?></cite></footer>
</blockquote>
<button type="button" class="btn btn-default center-block">Generate quote</button>
</div>
</div>
<?php include ('layout/footer.php'); ?>
Here is the function in the model I am retrieving the data from:
function getRandom() {
$query = $this->db->query("
SELECT * FROM quotes, characters, series
WHERE quotes.series_id = series.series_id AND quotes.character_id = characters.character_id
ORDER BY rand()
LIMIT 1
");
return $query->result_array();
}
Should I simply be using something like this?
$("button").click(function(){
$.get( "Page/index", function( data ) {
//output data to page element...
}
});
getI would do something like: controller:
public function callme()
{
$this->load->model('quote_model);
$data['quotes'] = $this->quote_model->getRandom();
}
Then in my footer:
condole.log("click button")
var_url = "controller/callme" // the url to the controller and method
$.get({
url: url
})
But meh, im bad at programming and even worse at jquery :D
Make hidden input for offset
<button onclick="showmore()" value="showmore" />
<input type="hidden" name="offset" id="offset" value="15"/>
Now Your Ajax Call
function showmore(){
$.ajax({
url:my_controller/showmore,
data:{
offset :$('#offset').val()
},
type:json,
success :function(data){
$('#show-more').prepand(data.view)
$('#offset').val(data.offset)
}
})
}
Your Controller
function showmore(){
$limit = '10';
$offset = $this->input->get('offset');
$result = $this->yourmodel->getdata($offset,$limit);
$data['view'] = $result;
$data['offset'] =$offset +10;
echo json_encode($data);
}
Your Model
$query = $this->db->get('your_table', $limit, $offset);
$data=$query->result_array();
return $data;

Getting value from contenteditable div

Up to this point, I've been using a textarea as the main input for a form. I've changed it to use a contenteditable div because I wanted to allow some formatting.
Previously, when I had the textarea, the form submitted fine with Ajax and PHP. Now that I've changed it to use a contenteditable div, it doesn't work anymore and I can't tell why.
HTML:
<form>
<div name="post_field" class="new-post post-field" placeholder="Make a comment..." contenteditable="true"></div>
<input name="user_id" type="hidden" <?php echo 'value="' . $user_info[0] . '"' ?>>
<input name="display_name" type="hidden" <?php echo 'value="' . $user_info[2] . '"' ?>>
<ul class="btn-toggle format-post">
<button onclick="bold()"><i class="fa-icon-bold"></i></button>
<button onclick="italic()"><i class="fa-icon-italic"></i></button>
</ul>
<div class="post-buttons btn-toggle">
<button class="btn-new pull-right" type="submit">Submit</button>
</div>
</form>
JQuery Ajax:
$(document).ready(function() {
$(document).on("submit", "form", function(event) {
event.preventDefault();
$.ajax({
url: 'php/post.php',
type: 'POST',
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
alert(data.message);
}
});
});
});
PHP (post.php): Just your typical checks and echo a message back. This is just a snippet of the code.
<?php
$user_id = $_POST["user_id"];
$display_name = $_POST["display_name"];
$post_content = $_POST["post_field"];
$array = array('message' => $post_content);
echo json_encode($array);
?>
For some reason, it's not sending back the post content anymore ever since I added the contenteditable div.
Please help!
The contents of the div are not serialized. You would have to add them on your own.
var data = $(this).serialize();
data += "post_field=" + encodeURIComponent($("[name=post_field]").html());

Categories