In my page there is a div element containing a MetroUI listview :
...
<div id="listSalles" class="listview">
<?php
$ret = ReservationSalle::lireParCritere([]); // database SELECT query
if ($ret->count() > 0) {
$html = '';
foreach ( $ret as $key => $val ) {
$html .= '<div class="list" id="salle_'.$ret[$key]->salle_code.'_'.$ret[$key]->flag_reserver.'">
<span class="mif-bookmarks list-icon"></span>
<span class="list-title">'.$ret[$key]->salle_lib.'</span>
<span class="place-right"><button id="reservS_'.$ret[$key]->salle_code.'" class="button default">Réserver</button></span>
<br/>
<span class="sub-title">'.$ret[$key]->reserver.'</span>
</div>';
}
echo $html;
}
else {
echo '<br/><div class="sub-header">Aucun enregistrement</div>';
}
?>
</div>
...
As you can see there is a database SELECT query which populates the listview. I want to "reload" this listview's content when a button , outside of the listview , is pressed. How to do that ?
Use javascript to do so.
In your PHP script put your current code:
$ret = ReservationSalle::lireParCritere([]); // database SELECT query
if ($ret->count() > 0) {
$html = '';
foreach ($ret as $key => $val) {
$html .= '<div class="list" id="salle_' . $ret[$key]->salle_code . '_' . $ret[$key]->flag_reserver . '">
<span class="mif-bookmarks list-icon"></span>
<span class="list-title">' . $ret[$key]->salle_lib . '</span>
<span class="place-right"><button id="reservS_' . $ret[$key]->salle_code . '" class="button default">Réserver</button></span>
<br/>
<span class="sub-title">' . $ret[$key]->reserver . '</span>
</div>';
}
return $html;
} else {
return '<br/><div class="sub-header">Aucun enregistrement</div>';
}
Lets call it data.php.
Then in your page load jQuery (if you havent yet, because it's easier) and add the following JS:
$.ajax({
type: 'GET',
url: 'data.php'
}).done(function (result) {
$("#listSalles").html(data); //Here you replace the current content with the update
}, "html");
And then wrap this JS in $(document).ready(function() {}) and inside a click listener $(btn).click(function(){ });
I suggest using AJAX.
Make a view with the relevant php code for the task, like this:
<?php
$ret = ReservationSalle::lireParCritere([]); // database SELECT query
if ($ret->count() > 0) {
$html = '';
foreach ( $ret as $key => $val ) {
$html .= '<div class="list" id="salle_'.$ret[$key]->salle_code.'_'.$ret[$key]->flag_reserver.'">
<span class="mif-bookmarks list-icon"></span>
<span class="list-title">'.$ret[$key]->salle_lib.'</span>
<span class="place-right"><button id="reservS_'.$ret[$key]->salle_code.'" class="button default">Réserver</button></span>
<br/>
<span class="sub-title">'.$ret[$key]->reserver.'</span>
</div>';
}
echo $html;
}
else {
echo '<br/><div class="sub-header">Aucun enregistrement</div>';
}
?>
Let's call it list-view.php.
Then in your page, add the following jquery:
$("#listSalles").load("list-view.php");
That would load the view inside that div.
If you want to reload that content when you press a button you could add a click handler for that button:
$("#id_of_button").click(function(){ $("#listSalles").load("list-view.php"); });
Related
I have the following code below, that I use to add products to the cart, but every time I add a product to the cart, the product is added to the cart, but i'm getting the error: unexpected end of data at line 1 column 1 of the JSON data is shown in firefox.
Now in chrome, i'm getting the error: Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse () at Object.success
I already tried to use console.log but php is not returning to me any errors. I tried several solutions but I could not solve them, so I came to ask for help here.
jQuery:
$(document).ready(function () {
//add a product in the cart
$('#add-to-cart').click(function () {
$("#addtocartform").submit(function(e) {
var prod_id = $("#add-to-cart").data("id");
var prod_mode = $("input[name=course_mode]:checked").val();
$.ajax
({
url: '/cart/add',
type: 'POST',
data: jQuery.param({ prod_id: prod_id, prod_mode: prod_mode}),
dataType: 'text',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function (data) {
//console.log(data);
var frontend_cart_result = JSON.parse(data);
$('#dropdowncart').html( frontend_cart_result['cart_li'] );
$('.badge').text( frontend_cart_result['cart_item_quantity'] );
$(location).attr('href', '/checkout');
},
error: function () {
alert("error");
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
});
})
PHP: Path /cart/add
public function add() {
//session_destroy();
//$_SESSION['cart'][0]['id'] = 'teste';
$cart_go = true;
if (!empty($_SESSION['cart'])) {
foreach ($_SESSION['cart'] as $valor) {
if ($valor['id'] == $_POST['prod_id']) {
$cart_go = false;
}
}
}
if ($cart_go) {
$db = new productModel();
//check if product has already been added
if (!empty($_SESSION['cart'])) {
$next_key = max(array_keys($_SESSION['cart']));
$next_key++;
} else {
$next_key = 0;
}
$_SESSION['cart'][$next_key] = $db->selecionaproduto(array("prod_id" => $_POST['prod_id']));
//add all the products filds in session
//bought the online course
if ($_POST['prod_mode'] == 1) {
$_SESSION['cart'][$next_key]['classroom_price'] = '';
}
//bought the classroom course
if ($_POST['prod_mode'] == 2) {
$_SESSION['cart'][$next_key]['online_price'] = '';
}
$frontend_cart = '';
foreach ($_SESSION['cart'] as $valor2) {
$frontend_cart = $frontend_cart . '<li>
<span class="item">
<span class="item-left">
<img src="/web-files/img/course/' . $valor2['id'] . '/' . $valor2['top_nav_cart_thumbnail'] . '" alt="">
<img src="/web-files/img/course/' . $valor2['id'] . '/' . $valor2['top_nav_cart_thumbnail'] . '" alt="">
<span class="item-info">
<span>' . $valor2['name'] . '</span>
<span><strong>R$ ' . number_format($valor2['online_price'] . $valor2['classroom_price'], 2, ',', '.') . '</strong></span>
</span>
</span>
<span class="item-right">
<button data-id="' . $valor2['id'] . '" class="btn btn-xs btn-danger pull-right delete-cart-item">x</button>
</span>
</span>
</li>';
}
$frontend_cart = $frontend_cart . '<li class="divider"></li>
<li><a class="text-center" href="/checkout">Cart</a></li>
<li class="divider"></li>
<li><a class="text-center" href="/checkout">Checkout</a></li>';
$frontend_cart_result = array(
"cart_li" => $frontend_cart,
"cart_item_quantity" => count($_SESSION['cart'])
);
echo json_encode($frontend_cart_result);
}
}
here is the console.log
{"cart_li":"<li>\r\n <span class=\"item\">\r\n <span class=\"item-left\">\r\n <img src=\"\/web-files\/img\/curso\/1\/psicofarmacologia-na-infancia-e-adolescencia-top-nav-cart.jpg\" alt=\"\">\r\n <span class=\"item-info\">\r\n <span>Curso de atualização em psicofarmacologia na infância e adolescência<\/span>\r\n <span><strong>R$ 999,00<\/strong><\/span>\r\n <\/span>\r\n <\/span>\r\n <span class=\"item-right\">\r\n <button data-id=\"1\" class=\"btn btn-xs btn-danger pull-right delete-cart-item\">x<\/button>\r\n <\/span>\r\n <\/span>\r\n <\/li><li class=\"divider\"><\/li>\r\n <li><a class=\"text-center\" href=\"\/checkout\">Cart<\/a><\/li>\r\n <li class=\"divider\"><\/li>\r\n <li><a class=\"text-center\" href=\"\/checkout\">Checkout<\/a><\/li>","cart_item_quantity":1}
Tank you!
You are telling your ajax call to expect text as the data type of the response. You are then creating HTML in your PHP script and json encoding it before you output it as a response to the ajax request.
What could possibly go wrong?
I would recommend not to store HTML as values in your json response.
In your AJAX request try:
dataType: 'json',
I am loading the latest news article to my home page, I would like to load the next one on click of a button. However I get this error on click: home.php:353 Uncaught ReferenceError: nextNews is not defined. The code I have written will load another article but will not hide the previous one. Any suggestions for this are also welcome.
<script>
$( document ).ready(function() {
var newsCount = 1;
function nextNews(item){
newsCount = newsCount + 1;
$("#newsHome2").load("load-news.php", {
newsNewCount: newsCount
});
}
});
</script>
<?php
$query = $handler->query('SELECT * FROM articles LIMIT 1');
$results = $query->fetchAll(PDO::FETCH_ASSOC);
if ($_GET['sort'] == 'dateTime')
{
$sql = " ORDER BY dateTime";}
for ($i=0; $i < count($results); $i++) {
echo '<div class="col-lg-6 col-xs-12 col-sm-12 height-news82" id="newsHome2">';
echo '<h2 class="ashu">Lastest News</h2><br>';
echo '<p class="news-title78">'.$results[$i]['headline'].' <br>'.'</p>';
echo '<img class="news-img33" src="data:image/png;base64,' .base64_encode( $results[$i]['logo'] ).'"/>';
echo '<p class="news-time">'.$results[$i]['dateTime'].'< br>'.'</p>';
echo '<p class="news-body56">'.$results[$i]['text'].'</p>' ;
echo '</p><br><button id="solo-buttons67">Read More</button>';
echo '<i id="arrow20" class="fa fa-chevron-left fa-1x"></ i><i id="arrow21" onclick="nextNews(this)" class="fa fa-chevron-right fa-1x"></i></div>';
}
?>
Your function 'nextNews' is defined in the anonymous function passed to .ready(). So it can't be called in your html.
Alternative:
Use jquery click event
Define the function outside of the anonymous function
Try this workout Its working fine :)
view file view.php
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<div id="newsHome2"></div>
<script type="text/javascript">
var newsCount = 1;
$( document ).ready(function() {
nextNews(newsCount)
});
function nextNews(newsCount){
newsCount = newsCount + 1;
$.post("load-news.php", { newsNewCount: newsCount }, function(data, status){
$("#newsHome2").html(data);
});
}
</script>
php file load-news.php
<?php
if(isset($_POST['newsNewCount'])) { $newsCount=$_POST['newsNewCount']; } else { $newsCount=1; }
echo '<div class="col-lg-6 col-xs-12 col-sm-12 height-news82" id="newsHome2">';
echo '<h2 class="ashu">Lastest News</h2><br>';
echo '<p class="news-title78">headline '.$newsCount.' <br>'.'</p>';
echo '<img class="news-img33" src="data:image/png;base64,"/>';
echo '<p class="news-time">dateTime '.$newsCount.'< br>'.'</p>';
echo '<p class="news-body56">text '.$newsCount.'</p>' ;
echo '</p><br><button id="solo-buttons67">Read More '.$newsCount.'</button>';
echo '<i id="arrow20" class="fa fa-chevron-left fa-1x"></ i><i id="arrow21" onclick="nextNews('.$newsCount.')" class="fa fa-chevron-right fa-1x"> click here for next </i></div>';
?>
I have this loop which outputs data:
foreach ($userItems_get as $item => $value) {
if ($value['prefab'] == 'wearable') {
echo $value['name'] . "</br>";
echo "<img src=\"{$value['image_inventory']}.png\" width=\"90\" height=\"60\">" . "</br>";
if (!isset($value['item_rarity'])) {
$rarity = "common";
} else {
$rarity = $value['item_rarity'];
}
echo $rarity . "</br>";
foreach ($userItemsLoad as $key => $values) {
if ($item == $values['defindex']) {
echo $values['id'] . "</br></br>";
break;
}
}
}
}
I want it to display like this: http://puu.sh/l7gyH/afe812c4f3.jpg
for which i have this html:
<div class="item-container">
<div id="item-box">
<img src="http://lorempixel.com/output/technics-q-c-95-60-9.jpg" alt="">
<div id="rarity">
rare
</div>
</div>
Which ever items the user selects i want to gets it values['id'], the user maybe select multiple items at once.
I can create a normal checkpoint type input table but the user might have 1000's of items so it needs to this way like in the picture.
Is there a simple way to accomplish this? Thanks
<div class="item-container">
<div class="item-box" data-id="1234">
<img src="http://lorempixel.com/output/technics-q-c-95-60-9.jpg" alt="">
<div id="rarity">
rare
</div>
</div>
</div>
<script>
var selectedItems = [];
$('.item-box').on('click', function(e){
$(this).toggleClass('selected');
var selectedItems = []
$('.item-box.selected').each(function(i,o){
selectedItems.push($(this).data('id'))
})
});
</script>
Personally thought I would think about using AngularJS (https://angularjs.org/) for something like this, it will make your life a lot easier.
I'm having trouble with a jQuery script for voting on posts. I have a "frontpage" with a list of posts from a mysql db. On each post there is a little votebox you can either vote up or down.
jQuery/ajax script:
<script type="text/javascript">
$(document).ready(function() {
$('.plus-button').click(function(){
var postid = <?php echo $postloopid; ?>;
$('.minus-button').removeClass('disliked');
$(this).toggleClass('liked');
alert(postid);
$.ajax({
type:"POST",
url:"php/votesystem.php",
dataType : 'html',
data:'act=like&postid='+postid,
success: function(data){
$('.plus-button').html(data);
}
});
});
$('.minus-button').click(function(){
var postid = $(this).attr('id');
$('.plus-button').removeClass('liked');
$(this).toggleClass('disliked');
$.ajax({
type:"POST",
url:"php/votesystem.php",
dataType : 'html',
data:'act=dislike&postid='+postid,
success: function(data){
$('.minus-button').html(data);
}
});
});
});
</script>
Votebox.php
<?php
// If postid is from frontpage use $postloopid as $postid
if(isset($postloopid)){
$postid = $postloopid;
}
$postid = htmlentities($postid, ENT_QUOTES);;
include("connect.php");
//For test purposes
echo $postid;
// If user logged in show votebox
if(isset($_SESSION['username'])){
$userid = $_SESSION['userid'];
$sql2 = mysqli_query($connect,"SELECT * FROM posts WHERE id='$postid' AND deleted=0");
if($sql2){
$voterow = mysqli_fetch_assoc($sql2);
$checkupvote = $voterow['upvoters'];
$checkdownvote = $voterow['downvoters'];
$checkupvote = explode(" ",$checkupvote);
$checkdownvote = explode(" ",$checkdownvote);
if($checkupvote = array_search($userid,$checkupvote) == true){
echo '<div class="plus-button liked" name="like">+ ' . $voterow['totalupvotes'] . '</div>';
echo '<div class="minus-button" name="dislike">- ' . $voterow['totaldownvotes'] . '</div>';
}
elseif($checkdownvote = array_search($userid,$checkdownvote) == true){
echo '<div class="plus-button" name="like">+ ' . $voterow['totalupvotes'] . '</div>';
echo '<div class="minus-button disliked" name="dislike">- ' . $voterow['totaldownvotes'] . '</div>';
}
else{
echo '<div class="plus-button" name="like">+ ' . $voterow['totalupvotes'] . '</div>';
echo '<div class="minus-button" name="dislike">- ' . $voterow['totaldownvotes'] . '</div>';
}
}
else {
echo 'No result <br />';
}
}
else {
echo 'Cant find user';
}
?>
Frontpage:
<?php
$sql1 = mysqli_query($connect,"SELECT * FROM posts WHERE totalupvotes < $trendmin AND deleted=0 ORDER BY added DESC LIMIT 0,10");
if($sql1){
while($row = mysqli_fetch_array($sql1)){
$postloopid = $row['id'];
?>
<div id="postlist">
<div style="width:400px; font-size:18px; font-weight:bold;">
<a target="_blank" href="post.php?id=<?php echo $row['id']; ?>"><?php echo $row['title']; ?></a>
</div><br />
<article class="slide"><?php echo nl2br($row['post']); ?></article>
<br />
<?php include("php/votebox.php"); ?>
<br />
by <a style="font-size:18px;" href="profile.php?id=<?php echo $row['submittedby']; ?>"><?php echo $row['submitteduser']; ?></a>
at <span style="font-size:12px;"><?php echo $row['added']; ?></span><span style="float:right; margin-right: 10px;"><a target="_blank" href="post.php?id=<?php echo $row['id']; ?>#commentfield"><?php echo $row['totalcomments']; ?> comments</a></span>
</div>
<?php
}
}
?>
The problem now is that when I click the votebox buttons it turns out I only get the postid from the first loaded post from the while loop. Another problem I have is that my total up- and downvotes changes in all the posts on the list, not the specific post.
Any ideas?
The Javascript code isn't in the loop, it can't reference postloopid. Or if it is, you're binding all buttons of the class every time through the loop, and clicking on them will run all the handlers, incrementing all the posts.
You should put the post ID as a data field in the button, and then access that from the Javascript:
echo '<div class="plus-button liked" data-postid="'+$postid+'" name="like">+ ' . $voterow['totalupvotes'] . '</div>';
echo '<div class="minus-button" data-postid="'+$postid+'" name="dislike">- ' . $voterow['totaldownvotes'] . '</div>';
Then your Javascript can do:
$('.plus-button').click(function(){
var postid = $(this).data('postid');
$(this).siblings('.minus-button').removeClass('disliked');
$(this).toggleClass('liked');
alert(postid);
$.ajax({
type:"POST",
url:"php/votesystem.php",
dataType : 'html',
data:'act=like&postid='+postid,
context: this,
success: function(data){
$(this).html(data);
}
});
});
I made the following changes to the JS:
Use $(this).data('postid') to get postid.
Only remove the disliked class from the sibling minus button, not all minus buttons on the page.
Put the returned HTML just in this element, not in all plus buttons. I pass this in the context: parameter, so that the success function can refer to it.
Alright lets go through your jQuery code(just the like function):
Bind click handler to all elements with the class plus-button
$('.plus-button').click(function(){
var postid = <?php echo $postloopid; ?>;
Remove disliked class from all elements with class minus-button
$('.minus-button').removeClass('disliked');
$(this).toggleClass('liked');
alert(postid);
$.ajax({
type:"POST",
url:"php/votesystem.php",
dataType : 'html',
data:'act=like&postid='+postid,
success: function(data){
Set inner html of all elements with class plus-button
$('.plus-button').html(data);
}
});
});
What you want is to store the postid as an attribute on the posts, then use
var postid = $(this).attr('postid')
only remove the disliked class from the current element
$(this)
.parents('{element containing plus and minus button}')
.find('.minus-button')
.removeClass('disliked')
;
store reference to the clicked element
var $this = $(this); // Cool guys do this right in the beginning and use only this variable instead of $(this)
then in your ajax success handler you want to set only the html of the button you clicked, so you may use the reference you stored in the parent function scope
$this.html(data);
EDIT in regards to infinite scroll script
When parts of your page are dynamic, you want to bind the click handler to a static parent element of the dynamic content using:
$("#postsParent").on('click', '.plus-button', function () {/*handler*/})
I have been struggled with one sticky issue regarding to set default li.
what I try to achieve is that set a li and its related page as default one. And when users click on others links, it would load other pages.
HTML Markup:
<div id="productIntro">
<div id="leftNav">
<ul>
<li class="head">
Pictures</b>
</li>
<li class="head">
<b>Comments</b>
</li>
<li class="head">
<b>Others</b>
</li>
</ul>
</div>
<div class="main">
</div>
</div>
JS:
function show(id, page) {
$('.main').load("loadProDetail.php?id=" + id + "&page=" + page, true);
}
jQuery(document).ready(function () {
$(document).on('click', '.head', function () {
$(".head").removeClass("selected");
$(this).toggleClass("selected");
});
});
loadProDetail PHP
<?php
$id = $_GET['id'];
$sql = "select * from product where id=$id ";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$page = $_GET['page'];
if($page == 1)
{
$html .= '<img src="./product_images/' . $row["name"] . '.jpg" width="150" border="2">';
}
if($page == 2)
{
$html .= 'No comments so far';
}
if($page == 3)
{
$html .= 'This page is under construction';
}
echo $html;
CSS:
.selected{background-color:red;}
In my case, I want to set the "Picutre" li as default page, and when user click on comments, it would load corresponding page. And also the background colour should also be changed.
Your page logic lives in your PHP, so specifying which page should display by default can be added there by modifying your if statements and making them into if...else instead:
if ($page==2) {
$html .= 'No comments so far';
} else if ($page==3) {
$html .= 'This page is under construction';
} else {
$html .= '<img src="./product_images/'.$row["name"].'.jpg" width="150" border="2">';
}
The logic implemented above goes like this: if the "Comments" or "Others" pages are requested, serve them, but if not then just serve the "Pictures" page.
Since you also want to load the "Picture" content when the page is initially loaded, you can call the show() function in your Javascript on pageload. Adding the following line to your existing jQuery(document).ready(function () { ... } should work as long as $row["id"] is properly set:
show($row["id"], 1);