Replace HTML content via jQuery AJAX request - javascript

I am trying to create an AJAX filter using jQuery and PHP. When my user selects an ingredient from the dropdown I look to see in my database if a recipe exists with that ingredient and if the user created the recipe. This query works perfectly and allows me to loop through and create HTML for each recipe. I want to update the HTML via AJAX. At the moment I have this for my AJAX:
$(document).ready(function() {
$('#filterButton').click(function(e) {
e.preventDefault();
// When the filter button is clicked, grab the ingredient ID and the cuisine ID
var mainIngred = $('#sel1').val();
var cuisine = $('#cuisine').val();
var userID = $('#userIDHidden').val();
var data = {
"ingredID" : mainIngred,
"tagID" : cuisine,
"userID" : userID
}
var filterajaxurl = '/recipe-project/filter-ajax.php';
$.ajax({
url: filterajaxurl,
type: "POST",
data: data,
success:function(data) {
$("#cookbook-recipe").html(data);
}
});
});
});
This is the PHP script I call, when it's called I want to replace the default data in the div with the ID cookbook-recipe with the HTML below after the PHP has looped through and got each recipe.
include_once('classes/class-database-functions.php');
$db_functions = new Database_Functions();
$ajax_recipes = $db_functions->ajax_filter_search(23,6);
$recipes_array = array();
foreach ($ajax_recipes as $ajax_recipe) {
$search_recipes = $db_functions->get_single_recipe($ajax_recipe);
$rows = mysqli_fetch_array($search_recipes, MYSQL_ASSOC);
array_push($recipes_array,$rows);
} ?>
<?php
if (isset($recipes_array) ) {
foreach ( $recipes_array as $single_recipe ) { ?>
<div class="col-md-4 portfolio-item">
<a href="single-recipe.php?id=<?php echo $single_recipe['recipe_id'];?>">
<?php if ( $single_recipe['recipe_image'] == '' ) { ?>
<img class="img-responsive" src="http://placehold.it/300x200" alt="">
<?php } else { ?>
<img class="img-responsive" src="<?php echo $single_recipe['recipe_image']; ?>" alt="">
<?php } ?>
</a>
<h4>
<a href="#">
<?php echo $single_recipe['recipe_name']; ?>
</a>
</h4>
</div>
<?php } } else { ?>
<div class="col-md-4 portfolio-item">
<h4>Please Add Some Recipes</h4>
</div>
<?php } ?>
Below is my default HTML
<button id="filterButton" class="btn btn-lg active" role="button">Filter Recipes</button>
<div id="cookbook-recipes" class="col-md-9">
<?php
if (isset($recipes_array) ) {
foreach ( $recipes_array as $single_recipe ) { ?>
<div class="col-md-4 portfolio-item">
<a href="single-recipe.php?id=<?php echo $single_recipe['recipe_id'];?>">
<?php if ( $single_recipe['recipe_image'] == '' ) { ?>
<img class="img-responsive" src="http://placehold.it/300x200" alt="">
<?php } else { ?>
<img class="img-responsive" src="<?php echo $single_recipe['recipe_image']; ?>" alt="">
<?php } ?>
</a>
<h4>
<a href="#">
<?php echo $single_recipe['recipe_name']; ?>
</a>
</h4>
</div>
<?php } } else { ?>
<div class="col-md-4 portfolio-item">
<h4>Please Add Some Recipes</h4>
</div>
<?php } ?>
</div>
However the HTML doesn't get replaced when I click the button and I get no console errors, can anyone see why?

It may help you.
Setting all HTML in a variable and finally echoing it:
$html_reponse = "";
<?php
if (isset($recipes_array) ) {
foreach ( $recipes_array as $single_recipe ) {
$html_reponse .= "<div class='col-md-4 portfolio-item'>";
$html_reponse .= "<a href='single-recipe.php?id=".$single_recipe['recipe_id']."'>";
if ( $single_recipe['recipe_image'] == '' ) {
$html_reponse .= "<img class='img-responsive' src='http://placehold.it/300x200' alt=''>";
} else {
$html_reponse .= "<img class='img-responsive' src='".$single_recipe['recipe_image']."' alt=''>";
}
$html_reponse .= "</a>";
$html_reponse .= "<h4>";
$html_reponse .= "<a href='#'>".$single_recipe['recipe_name']."</a>";
$html_reponse .= "</h4>";
$html_reponse .= "</div>";
}
}else{
$html_reponse .= "<div class='col-md-4 portfolio-item'>";
$html_reponse .= "<h4>Please Add Some Recipes</h4>";
$html_reponse .= "</div>";
}
echo $html_reponse;exit;
In your JS:
success:function(data) {
// remove this alert after your testing.
// It is just to placed that we successfully got the reponse
alert("We got Response");
// Just showing response in Browser console 'press F12 shortcut to open console in your browser'
console.log(data);
// removing existing HTML from the container and then entering new one!
$("#cookbook-recipe").empty().html(data);
}
If it still doesn't work, you might have some problem in getting response. Make sure that it comes to your Ajax success callback event.

Related

How can I create an infinite scroll (lazy loading) grouped per day and showing date?

Situation
I'm creating a custom Wordpress website where I want to show the most recent articles grouped by day and have it scroll infinitely when you've reached the bottom of your screen.
Problem
I don't know how to continue with the date you were on without breaking the layout.
I've seen many code that involve having infinite scroll, but none of them really worked for me since it also needs to match the design.
Here is the design:
The image pretty much explains what I need to create and so I've written the following code:
<div class="recent">
<?php
$args = array(
'posts_per_page' => -1,
'orderby' => 'date'
);
$myQuery = new WP_Query($args);
$date = '';
$postCount = 0;
$newDay = false;
if ( $myQuery->have_posts() ) : while ( $myQuery->have_posts() ) : $myQuery->the_post();
$postCount++;
if ( $date != get_the_date() ) {
if ( $postCount != 1 ) {
$newDay = false;
if (!$newDay) {
?></div><?php
}
?>
</div>
<?php
}
?>
<div class="recent__articles">
<?php
$newDay = true;
$date = get_the_date();
?>
<div class="recent__header">
<img class="header__icon" src="<?php echo get_home_url() ?>/wp-content/themes/insane/assets/images/time.svg" alt="time-icon">
<?php echo $date; ?>
</div>
<?php
if ($newDay) {
?>
<div class="articles__wrapper"><?php
}
}
?>
<div class="recent__article">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<figure class="article__image">
<?php if ( has_post_thumbnail() ) :
the_post_thumbnail();
else : ?>
<img src="<?php echo get_home_url() ?>/wp-content/themes/insane/assets/images/article-placeholder.png" alt="image-placeholder">
<?php endif ?>
</figure>
<div class="article__meta">
<span class="article__cat">
<?php
foreach((get_the_category()) as $category){
echo $category->name;
}
?>
</span>
<h2 class="article__title"><?php echo get_the_title() ?></h2>
<div class="article__date">
<?php echo esc_html( time_difference( get_the_time('U'), current_time('timestamp') ) ); ?>
</div>
</div>
</a>
</div>
<?php
endwhile; endif;
wp_reset_postdata();
?>
</div>
Top part where I check the date and increment the postCount is so I can group the articles of that day in separate div and style it accordingly.
Now all I need is to check wether I've reached the bottom and continue with where I left off.
Any help with the directions I need to be going is much appreciated.
Thank you!
I've fixed my problem in combination with the Ajax Load More plugin.
I hope this will help others facing the same problem as I did.
If anybody sees improvement in my code, I'd much appreciate it.
Tested on: MacOS - Chrome/Safari/Firefox & iOS - Chrome/Safari
I've installed the Ajax Load More plugin
They have a Repeat Templates section which is basically the while loop in php and I've added the following code (a bit stripped from what I've showed here above).
<?php $postCount++;
if ( $date != get_the_date() ) {
if ( $postCount != 1 ) {
$newDay = false;
if (!$newDay) {
?></div><?php
}
?>
</div>
<?php
}
?>
<div class="recent__articles">
<?php
$newDay = true;
$date = get_the_date();
?>
<div class="recent__header">
<img class="header__icon" src="<?php echo get_home_url() ?>/wp-content/themes/insane/assets/images/time.svg" alt="time-icon">
<?php echo $date; ?>
</div>
<?php
if ($newDay) {
?>
<div class="articles__wrapper"><?php
}
}
?>
<div class="recent__article">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<figure class="article__image">
<?php if ( has_post_thumbnail() ) :
the_post_thumbnail();
else : ?>
<img src="<?php echo get_home_url() ?>/wp-content/themes/insane/assets/images/article-placeholder.png" alt="image-placeholder">
<?php endif ?>
</figure>
<div class="article__meta">
<span class="article__cat">
<?php
foreach((get_the_category()) as $category){
echo $category->name;
}
?>
</span>
<h2 class="article__title"><?php echo get_the_title() ?></h2>
<div class="article__date">
<?php echo esc_html( time_difference( get_the_time('U'), current_time('timestamp') ) ); ?>
</div>
</div>
</a>
</div>
I've a .php file that I load in somewhere els that looks like this:
<div class="recent">
<?php
$date = '';
$postCount = 0;
$newDay = false;
echo do_shortcode("[ajax_load_more post_type='post' posts_per_page='2' scroll_distance='0']");
?>
</div>
Now for the last part I've written the following in jQuery:
// Ajax load more fix
function ajaxShowMore() {
var oldXHR = window.XMLHttpRequest;
function newXHR() {
var realXHR = new oldXHR();
realXHR.addEventListener("readystatechange", function() {
if (realXHR.readyState === 4) { // When the Ajax call is finished new content is loaded
var oldRecentHeaders = $('.recent__header'); // Store all previous recent headers in variable
setTimeout(function() { // Set a timeout, since it goes a bit to fast to store the data
var newRecentHeaders = $('.recent__header'); // Store all the headers in a variable
newRecentHeaders.splice(0, oldRecentHeaders.length); // Splice it, so you only get the new added headers
if (newRecentHeaders.first().text() === oldRecentHeaders.last().text()) { // Check if the first of new header date is the same as the last of the old header date
var newArticles = newRecentHeaders.first().parent().find('.articles__wrapper').children(); // Store all the articles
newRecentHeaders.first().parent().remove(); // Remove the first new added articles
oldRecentHeaders.last().parent().find('.articles__wrapper').append(newArticles); // Add them here
}
}, 10);
}
}, false);
return realXHR;
}
window.XMLHttpRequest = newXHR;
}
So for me this specific solution works, based on the classes and structure of my project I've set.
I hope this helps

tree view display data using jquery javascript in yii2

I have display data like treeview using javascript, jquery in yii2.
I have done my code like this:
$this->registerJs(
'
function videoShow(id){
var url = "' . Url::to(['test/get-videos-from-category']) . '?id="+id;
$.ajax({
type: "GET",
url: url,
beforeSend: function() {
blockBody();
},
success:function(data){
var hidden = $(data).find(".hidden")[0];
var parent_id = $(hidden).find(".category_parent_id").text();
var category_id = $(hidden).find(".category_uuid").text();
$("span").one("click", function() {
$(".category_video #myTab5").hide();
$(this).parent().children().css("display","inline");
$(this).addClass("caret-down");
$(this).parent().parent().children().children().not($(this)).removeClass("caret-down");
$(this).parent().children().css("display","inline").not($(this));
$(this).parent().children().addClass("active");
});
var category = $(".hidden").children(".category_name").text();
var category_uuid = $(".hidden").children(".category_uuid").text();
var category_parent_id = $(".hidden").children(".category_parent_id").text();
if(category == "") {
$(".datatable-search-div").css("display","inline");
unblockBody();
$("#myTabContent5").css("display","inline");
$(".showVideo").html(data);
} else {
if(".hidden") {
var hidden = $(data).find(".hidden")[0];
var hidden_category = $(hidden).find(".category_name").text();
var hidden_parent_id = $(hidden).find(".category_parent_id").text();
var hidden_category_uuid = $(hidden).find(".category_uuid").text();
category = hidden_category;
category_uuid = hidden_category_uuid;
category_parent_id = hidden_parent_id;
var html = "<a href=\'"+category_uuid+"\' id=\'video_search\' data-uuid=\'"+category_uuid+"\' data-parentid=\'"+category_parent_id+"\' data-name=\'"+category+"\' data-toggle=\'tab\' class=\'caret\' onclick=videoShow(\'"+category_parent_id+"\'); style=\'margin-left: 20px;\'>"+category+"</a>";
html += "<ul class=\'category_nested\' id=\'"+category_uuid+"\' role=\'tablist\'>";
html += "<li class=\'category_sub_child\'>";
html += "</li>";
html += "</ul>";
unblockBody();
$("#myTabContent5").css("display","inline");
$(".showVideo").html(data);
}
var html = [];
$(".hidden").each(function(cat) {
$("#video_search").addClass("caret-down");
$(".category_child").parent().addClass("caret-down");
var category = $(this).children(".category_name").text();
;
var category_uuid = $(this).children(".category_uuid").text();
var category_parent_id = $(this).children(".category_parent_id").text();
var category_uuid_array = [];
var category_array = [];
var category_parent_id_array = [];
category_uuid_array.push(category_uuid);
category_array.push(category);
category_parent_id_array.push(category_parent_id);
var html_new = "<li class=\'category_child\' data-id=\'"+category_uuid+"\'>";
html_new += "<a href=\'"+category_uuid+"\' id=\'video_search\' data-uuid=\'"+category_uuid+"\' data-parentid=\'"+category_parent_id+"\' data-name=\'"+category+"\' data-toggle=\'tab\' class=\'caret\' onclick=videoShow(\'"+category_uuid+"\'); style=\'margin-left: 20px;\'>"+category+"</a>";
html_new += "<ul class=\'category_nested\' id=\'"+category_uuid+"\' role=\'tablist\'>";
html_new += "<li class=\'category_sub_child\'>";
html_new += "</li>";
html_new += "</ul>";
html.push(html_new);
});
$(".category_child").click(function(){
console.log("category_child clicked");
$(this).children(".category_nested").children().html(html);
});
if($(".nested").length) {
console.log("nested");
$(".nested").children().html(html);
}
unblockBody();
$("#myTabContent5").css("display","inline");
$(".showVideo").html(data);
}
},
error:function(e){
unblockBody();
showErrorMessage(e.responseText);
}
});
}
', View::POS_END
);
?>
And html code like this:
<html>
<body>
<div class="content-body">
<div class="row ">
<div class="col-lg-12 col-md-12 col-12 ">
<ul id="myUL" class="datatable-search-div" style="display: none;">
<?php
if (!empty($model)) {
foreach ($model as $key => $value) { ?>
<li class="category_video">
<span class="caret">
<a href="<?= $value['uuid']; ?>" id="video_search" data-uuid="<?= $value['uuid']; ?>" data-parentid="<?= $value['parent_id']; ?>" data-name="<?= $value['name']; ?>" data-toggle="tab" onclick="videoShow('<?= $value['uuid']; ?>');">
<?= $value['name']; ?>
</a>
</span>
<ul class="nested" data-id="<?= $value['uuid']; ?>" id="myTab5" role="tablist" style="display:none;">
<li class="category_child" data-id="<?= $value['uuid']; ?>">
<ul class="category_nested" id="<?= $value['uuid']; ?>" role="tablist">
<li class="category_sub_child">
</li>
</ul>
</li>
</ul>
</li>
<?php
}
}
?>
</ul>
</div>
</div>
</div>
<div class="tab-content float-left vertical col-xl-12 col-lg-12 col-md-3 col-3 left-aligned" id="myTabContent5" style="display:none;">
<?php
if (!empty($model)) { ?>
<div id="<?= $value['uuid']; ?>" class="tab-pane showVideo fade active show">
</div>
<?php
}
?>
</div>
</body>
</html>
[![enter image description here][1]][1]
In this code category_child class element then that data display in that not children class.
In this code, I have tried to Cat-1.1.1 in after Cat-1.1 category.
But not display like that. Cat-1.1.1 display after Category1 and Cat-1.1 remove.
This is an image I have to explain in the last step:
Please help if anyone have an idea for that.
This is answer for my question:
public function getCategoryTreeHtml($level = null, $prefix = '') {
$rows = InstrumentCategory::find()->where(['parent_id' => $level])->asArray()->all();
$category = '';
if (count($rows) > 0) {
foreach ($rows as $row) {
$sub_count = InstrumentCategory::find()->where(['parent_id' => $row['uuid']])->count();
if($sub_count > 0){
$category .= '<li style="padding: 5px;"><span class="caret"><a href="'.$row['uuid'].'" id="video_search" data-uuid="'.$row['uuid'].'" data-parentid="'.$row['parent_id'].'" data-name="'.$row['name'].'" data-toggle="tab" onclick=videoShow("'.$row['uuid'].'");>' . $row['name'] . "</a></span>";
$category .= '<ul class="nested">';
$category .= self::getCategoryTreeHtml($row['uuid'], $prefix . '-');
$category .= '</ul>';
$category .= '</li>';
}else{
$category .= '<li><a href="'.$row['uuid'].'" id="video_search" data-uuid="'.$row['uuid'].'" data-parentid="'.$row['parent_id'].'" data-name="'.$row['name'].'" data-toggle="tab" onclick=videoShow("'.$row['uuid'].'")>' . $row['name'] . "</a></li>";
// Append subcategories
//$category .= $this->getCategoryTree($row->id, $prefix . '-');
}
}
}
return $category;
}

Dynamically created script not working

I am trying to dynamically create a script but it is not working.
I tried:
echo '<script type="text/javascript">alert("hello!");</script>';
echo '<script>alert("hello!");</script>';
echo '<script type="text/javascript">$( document ).ready(function() {alert("hello!");});</script>';
please help
Upon request here is the full code where the script is dynamically created at:
In fact , there is a php page that has a javascript file that calls an ajax function on press of a button that sends the type and calls this php page , this one will dynamically create the bootstrap carousel with the right pictures (give the right category)
<?php
//the login database info goes here too
$_type= $_POST['Type'];
$_category= $_POST['Category'];
if($_type == "adult")
{
$title = "FOR THE ADULTS";
}
else
$title = "FOR THE KIDS";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT image,imagealt FROM gallery where type='".$_type."' AND category='".$_category."' ";
$result = $conn->query($sql);
$result1 = $conn->query($sql);
?>
<tr>
<td class="GalleryImageInfo">
<div id="parent_back" >
<h1>GALLERY</h1>
<p class="ForAdults"> <?php echo $title ?> </p>
<p class="ButtonGalleryPreview" style="text-align:center"> <?php echo $_category ?> </p>
<?php
$countit = 0;
if ($result->num_rows > 0) {
// output data of each row
?>
<div id="slider_caption" > <div>
<?php
while($row = $result->fetch_assoc()) {
$image_description = $row["imgdesc"];
echo "
<div class=\"carousel-caption caption-".$countit."\">
<h3>Description</h3>
<p>".$image_description."</p></div>";
$countit++;
}
echo "</div></div>";
echo "<p class=\"GalleryImageBack\" style=\"font-family:BandaBold; color:#6c555e; font-size:15px;\"><i class=\"fa fa-arrow-circle-left\" style=\"margin-right:10px; font-size:15px;\" ></i>BACK</p>
</div>
</td>
<td style=\"width:100%\">
<div class=\"container\" style=\"width:100% ; padding:0px !important;\">
<div id=\"myCarousel2\" class=\"carousel slide\" data-ride=\"carousel\">
<!-- Wrapper for slides -->
<div class=\"carousel-inner\">";
$firstitem = true;
while($row = $result1->fetch_assoc()) {
//echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
$image_url = $row["image"];
$image_alt = $row["imagealt"];
if($firstitem)
{ echo"<div class=\"item active\">
<img src=\" $image_url \"
alt=\".$image_alt.\" style=\"width:100%;\">
</div>";
$firstitem= false;
}
else
echo"<div class=\"item\">
<img src=\" $image_url \"
alt=\".$image_alt.\" style=\"width:100%;\">
</div>";
}
echo " </div>
<!-- Left and right controls -->
<a class=\"left carousel-control\" href=\"#myCarousel2\" data-slide=\"prev\">
<span class=\"glyphicon glyphicon-chevron-left\"></span>
<span class=\"sr-only\">Previous</span>
</a>
<a class=\"right carousel-control\" href=\"#myCarousel2\" data-slide=\"next\">
<span class=\"glyphicon glyphicon-chevron-right\"></span>
<span class=\"sr-only\">Next</span>
</a>
</div>
</div>
</td>
</tr>";
echo "<script type=\"text/javascript\">$(document).ready(function() {
alert(\"hello!\");
});</script>";
}
else {
echo "0 results";
}
$conn->close();
?>
check if you added the jquery script in this page or not.

PHP forms through loop doesn't send specific session against checked radio button

I am working on an e-testing system in which when a candidate login the test for which he/she was register will be shown to him/her.
I am getting the specific test through session to show the questions containing in that test. This was successfully done with the help of some "if" checks and two while loops(1 for questions and 2nd for answers against that question) having the form of radio buttons for selecting an answer.
Now each time when loop execute it create a form for single question and its answer, that way for multiple questions it results in multiple.
I am getting the checked radio buttons through ajax and posting it to another php file but I need a question id of checked answer as well to be passed to the 2nd php file
I used session but it only get the id of 1st checked and not for the others.
The 2nd php file name is answers.php for the time being i just want to post and get all values and session in answers.php file.
the main problem is with $_SESSION ['qid'] = $id; session
Note: i have used unset and destroy session to free the session and tried to re start it but i am field to do so..
<?php
include ("connection.php");
// $mysql_row = '';
$query_run = null;
$test = $_SESSION ['id'];
var_dump ( $_SESSION ['id'] );
$query1 = "SELECT * FROM question where testid = '" . $_SESSION ['id'] . "'";
if ($query_run = mysql_query ( $query1 )) {
if (mysql_num_rows ( $query_run ) == null) {
print "No result";
} else {
// echo'<form action="ss.php" method="post">';
while ( $mysql_row = mysql_fetch_assoc ( $query_run ) ) {
$id = $mysql_row ['qid'];
$_SESSION ['qid'] = $id;
echo ' <div class="panel-heading" style="background: black; font-weight:bold;">Question </div>';
$data = $mysql_row ['questions'];
?>
<form>
<br>
<div class=" form-control well well-sm">
<?php echo'<div style="font-weight:bold;"> Q: '.$data.' </div> '; ?>
<br>
</div>
<?php
$query1 = "SELECT * FROM `answer` where id='" . $id . "'";
if ($query_run1 = mysql_query ( $query1 )) {
if (mysql_num_rows ( $query_run ) == null) {
} else {
while ( $mysql_row1 = mysql_fetch_assoc ( $query_run1 ) ) {
$data1 = $mysql_row1 ['ans1'];
$data2 = $mysql_row1 ['ans2'];
$data3 = $mysql_row1 ['ans3'];
$data4 = $mysql_row1 ['ans4'];
echo "\n";
?>
<?php
echo '<div class="panel-heading" style="font-weight:bold;">Option1</div>';
?>
<div class="form-control ">
<?php
echo "<input type='radio' value='$data1' name='opt1' onclick='OnChangeRadio (this)'> $data1<br />";
?>
<br>
</div>
<?php
echo '<div class="panel-heading" style="font-weight:bold;">Option2</div>';
?>
<div class="form-control ">
<?php
echo "<input type='radio' value='$data2' name='opt1' onclick='OnChangeRadio (this)'> $data2<br />";
?>
</div>
<?php
echo '<div class="panel-heading" style="font-weight:bold;">Option3</div>';
?>
<div class="form-control ">
<?php
echo "<input type='radio' value='$data3' name='opt1' onclick='OnChangeRadio (this)'> $data3<br />";
?>
</div>
<?php
echo '<div class="panel-heading" style="font-weight:bold;">Option4</div>';
?>
<div class="form-control ">
<?php
echo "<input type='radio' value='$data4' name='opt1' onclick='OnChangeRadio (this)'> $data4<br />";
// echo'</form>';
?>
</div>
<?php
echo '</form>';
}
}
}
// $view_id1 = $view_id;
// echo $view_id1;
}
}
} else {
print mysql_error ();
}
// unset($_SESSION['qid']);
?>
connection.php
<?php
session_start ();
if (! $_SESSION ['user']) {
header ( "Location: index.php" );
// redirect to main page to secure the welcome
// page without login access.
}

Bug when I .load in opencart

I edited my checkout/cart.tpl and initially everything looks fine, but then when I "add cart" something the code changes automatically and everything be strange.
EXAMPLES
1- when I enter in website and look to cart, everything looks fine:
2- THE BUG/MISTAKE. When I update my cart, when I click in "Add cart" only appear this part of my cart, without prices and checkout etc:
HTML/cart.TPL
<div id="cart">
<img src="images/bag.png" alt="Bag" />Cart: <span id="cart-total"><?php echo $text_items; ?></span>
<div class="cart_menu">
<?php if ($products || $vouchers) { ?>
<div class="cart_items">
<?php foreach ($products as $product) { ?>
<div class="c_item_img floatleft">
<?php if ($product['thumb']) { ?>
<img src="<?php echo $product['thumb']; ?>" alt="<?php echo $product['name']; ?>" title="<?php echo $product['name']; ?>" />
<?php } ?>
</div>
<div class="c_item_totals floatleft">
<div class="c_item_totals_detail floatleft">
<h5><?php echo $product['name']; ?></h5>
<span><?php echo $product['quantity']; ?> x <?php echo $product['total']; ?></span>
</div>
<div class="close_icon_cart floatleft">
<img src="images/close.png" onclick="cart.remove('<?php echo $product['key']; ?>');" title="<?php echo $button_remove; ?>" alt="" />
</div>
</div>
<?php } ?>
</div>
<div class="cart_totals">
<?php foreach ($totals as $total) { ?>
<div class="c_totals_left floatleft">
<p></p>
</div>
<div class="c_totals_right floatleft">
<p><?php echo $total['title']; ?> <?php echo $total['text']; ?></p>
</div>
<?php } ?>
</div>
<div class="cart_view_bottom">
<div class="c_totals_left floatleft">
<?php echo $text_cart; ?>
</div>
<div class="c_totals_right floatleft">
<?php echo $text_checkout; ?>
</div>
</div>
<?php } else { ?>
<div class="cart_items">
<p class="text-center"><?php echo $text_empty; ?></p>
</div>
<?php } ?>
</div>
</div>
.JS
<script type="text/javascript"><!--
$('#button-cart').on('click', function() {
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: $('#product input[type=\'text\'], #product input[type=\'hidden\'], #product input[type=\'radio\']:checked, #product input[type=\'checkbox\']:checked, #product select, #product textarea'),
dataType: 'json',
beforeSend: function() {
$('#button-cart').button('loading');
},
complete: function() {
$('#button-cart').button('reset');
},
success: function(json) {
$('.alert, .text-danger').remove();
$('.form-group').removeClass('has-error');
if (json['error']) {
if (json['error']['option']) {
for (i in json['error']['option']) {
var element = $('#input-option' + i.replace('_', '-'));
if (element.parent().hasClass('input-group')) {
element.parent().after('<div class="text-danger">' + json['error']['option'][i] + '</div>');
} else {
element.after('<div class="text-danger">' + json['error']['option'][i] + '</div>');
}
}
}
if (json['error']['recurring']) {
$('select[name=\'recurring_id\']').after('<div class="text-danger">' + json['error']['recurring'] + '</div>');
}
// Highlight any found errors
$('.text-danger').parent().addClass('has-error');
}
if (json['success']) {
$('.breadcrumb').after('<div class="alert alert-success">' + json['success'] + '<button type="button" class="close" data-dismiss="alert">×</button></div>');
$('#cart-total').html(json['total']);
$('html, body').animate({ scrollTop: 0 }, 'slow');
$('#cart > div').load('index.php?route=common/cart/info .cart_menu .cart_items');
}
}
});
});
//--></script>
I already tried put all div classes in JavaScript but it didn't work, unfortunately.
I'm almost positive that your problem is due to the fact that you have used the id "cart" in your checkout/cart template which is already in use by the cart module handled by module/cart. It's important to understand that these are two different things and the cart id needs be unique - especially when you are using javascript to update it's contents.
Try changing the id in checkout/cart.tpl to something other than "cart".

Categories

Resources