What I am doing is loading contents from a php file in json format
products.php
<?php
$stmt = $mysqli->prepare("SELECT * FROM products LIMIT 10");
$stmt->execute();
$products = $stmt->get_result();
$product_array = array();
while($product = $products->fetch_assoc()){
$product_array[] = $product;
}
echo json_encode($product_array);
?>
home.php
<style>
.product
{
width: 100px;
height:100px;
margin-bottom: 10px;
}
</style>
<div class="product_area">
<div class="product">
<h3>Product 1</h3>
<p>Price: $10</p>
</div>
<div class="product">
<h3>Product 2</h3>
<p>Price: $10</p>
</div>
<div class="product">
<h3>Product 3</h3>
<p>Price: $10</p>
</div>
<div class="product">
<h3>Product 4</h3>
<p>Price: $10</p>
</div>
</div>
I have already 4 products in a product_area now I want to fetch the other products as soon as the document is loaded so I used ajax
$(document).ready(function()
{
$.ajax(
{
url: 'product.php',
dataType: 'JSON',
success: function(data)
{
//This is where I am stucked. How do I append the new data beneath the current data in `product_area`.
for(i=0; i<=data.length; i++)
{
}
window.History.pushState({urlPath:'&view=products'},"",'&view=product');
}
});
});
Also I am trying to push the state in the url with this window.History.pushState({urlPath:'&view=products'},"",'&view=product') but it doesn't push it means it doesn't show the url appended.
How it should be
Before pushState url index.php?store=abc
After pushState url index.php?store=abc&view=products
Can some one help me with this?
Try to do this:
products.php
<?php
header('Content-Type: application/json');
$stmt = $mysqli->prepare("SELECT * FROM products LIMIT 10");
$stmt->execute();
$products = $stmt->get_result();
$product_array = array();
while($product = $products->fetch_assoc()){
$product_array[] = $product;
}
echo json_encode($product_array);
?>
javascript - just clone the first div and then replicates
$(document).ready(function() {
$.ajax({
url: 'product.php',
dataType: 'JSON',
success: function(data) {
//This is where I am stucked. How do I append the new data beneath the current data in `product_area`.
data.forEach(function (product) {
var newProductBox = $('.product:first').clone();
newProductBox.find('h3').text(product.nameInYourColumnDb);
newProductBox.find('p').text('Price: $' + product.priceInYourColumnDb);
$('.product_area').append(newProductBox);
});
window.History.pushState({urlPath:'&view=products'},"",'&view=product');
}
});
});
About the "pushState" take a look at this examples:
https://developer.mozilla.org/en-US/docs/Web/API/History_API#Example_of_pushState()_method
Parse Json Data and Append It To product_area class
<script>
$(document).ready(function()
{
$.ajax(
{
url: 'product.php',
dataType: 'JSON',
success: function(data)
{
var json = $.parseJSON(data);
for(i=0; i<=json .length; i++)
{
$('.product_area').append('<div class="product"><h3>Product Name: '+json[i].product_name+'</h3><p> Price :'+json[i].product_price+'</p></div>');
}
window.History.pushState({urlPath:'&view=products'},"",'&view=product');
}
});
});
</script>
Related
I'm creating a website and I want to load different queries onto a page depending on which button is clicked.
Can I do it like this?
The HTML :
<div id="Proceed">
4 Projects have been suggested to proceed.
</div>
<div id="result">
<!-- The title of the projects will be loaded here -->
</div>
<button id="foo"> Search </button>
The javascript:
$('#foo').on('click' function(){ //the button
var x = $(this).find('div').attr('id'); // get the id
$.ajax({
url: 'profile/inbox',
type: 'POST',
data: { id: x },
success: function(res){
('#result').html(res);
}
})
})
On profile.php:
function Inbox(){
$id = $_POST['id'];
$query = $this->db->query("SELECT `title` FROM `table` WHERE id=?",$id);
$load = $query->result_array();
$this->d['load'] = $load;
}
EDIT: I added some html to show where I plan to load the results of the query.
For eg:(This is your code I just slightly modified because for
example)
<div id="Proceed">
<select id="city" name="city">
<option value="">City:</option>
<option value="glasgow">Glasgow</option>
<option value="london">London</option>
</select>
</div>
<div id="result">
</div>
<button id="foo"> Search </button>
Script:(For eg:)
$("#foo").click(function() {
$.ajax({
url: 'profile/inbox', //Pass this value to the corresponding URL
type: 'POST',
dataType: "html",
data: {
"city": $('#city').val(), //Here request the value for id name is city
},
success: function(response){
$("#result").html(response); //Retrieve value form URL to pass the view page and value to set in <div id="result">
}
});
});
This is my url page(you just see what are the process there.. This is
for eg)
$sql = "SELECT * FROM entries";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "success"."id: " . $row["id"]. " - City: " . $row["city"]. "<br>";
}
} else {
echo "0 results";
}
When you want to use a POST variable from PHP side you have to use
$_POST/$_REQUEST method in your case $id = $_POST['id']; this will work
Below code of auto refresh is not giving error but it shows only one record out of multiples when refresh.
But when i include and do not refresh the div it shows all records.
Like this it shows all records
<div class="m-timeline-3__items">
<?php include('orders.php'); ?>
</div>
Like this it shows one record:
<div id="newOrderRefresh" class="m-timeline-3__items">
</div>
orders.php
<?php
include ('inc/db.php');
$sqlx4 = "select distinct(order_id) as order_id from orders_placed where status = 0 ";
$sqlx5 = $dba2->query($sqlx4);
while ($sql6 = $sqlx5->fetch_assoc()){
$sqlx1 = "select count(order_id) as total_items, order_id from orders_placed where status = 0 and order_id in ('".$sql6['order_id']."') ";
$sqlx2 = $dba2->query($sqlx1);
$sqlx3 = $sqlx2->fetch_assoc();
$timeoid = $sqlx3['order_id'];
$totalItems = $sqlx3['total_items'];
?>
<div style="width: 100%;" class="m-timeline-3__item m-timeline-3__item--info">
<div style="margin-left: 41px; " class="m-timeline-3__item-desc">
<div style="" class="m-timeline-3__item-text">
Order # <font color="red"><b><?php echo $timeoid; ?></b></font>,
Total Items <font color="black"><b>( <?php echo $totalItems; ?> )</b></font>
</div>
</div>
</div>
<?php } ?>
.
var cacheData;
var data = $('#newOrderRefresh').html();
var auto_refresh = setInterval(
function () {
$.ajax({
url: 'orders.php',
type: 'POST',
data: data,
dataType: 'html',
success: function(data) {
if (data !== cacheData){
cacheData = data;
$('#newOrderRefresh').html(data);
}
}
})
}, 1000);
if u select on brand that will be checked and also check the price that also filtered but when i selected another brand that will not be selected please suggest me..
i think it will not select multiple array brands.i will used php,jquery and mysqli.
<div class="widget-header">
<h4 class="widget-title">Brand</h4>
</div>
<div class="accordion-group" id="brandname">
<?php
$all_brand=$con->query("SELECT distinct brand FROM `mc_products_tbl` WHERE cat_id = '$_GET[cat_id]' GROUP BY brand");?>
<?php foreach ($all_brand as $key => $new_brand) :
if(isset($_GET['brand'])) :
if(in_array(data_clean($new_brand['brand']),$_GET['brand'])) :
$check='checked="checked"';
else : $check="";
endif;
endif;
?>
<input type="checkbox" value="<?=data_clean($new_brand['brand']);?>" <?=#$check?> name="brand[]" class="sort_rang brand" onchange="filterProducts()"><?=ucfirst($new_brand['brand']); ?>
<?php endforeach; ?>
</div>
<div class="widget-header">
<h4 class="widget-title">Price Range</h4>
</div>
<div class="filter-panel">
<p><input type="hidden" id="price_range" onchange="filterProducts()" value="50,50000"/>
</p>
</div>
function filterProducts() {
var cat_id = $("#cat_id").val();
var subcat_id = $("#subcat_id").val();
var brand = check_box_values('brand');
var price_range = $("#price_range").val();
alert(cat_id);
alert(subcat_id);
alert(brand);
alert(price_range);
var dataString='price_range='+price_range+'&cat_id='+cat_id+'&subcat_id='+subcat_id+'&brand='+brand;
alert(dataString);
$.ajax({
type: "POST",
url: "left_listing_ajax_filter.php",
data: dataString,
cache: false,
// beforeSend: function () {
//$('.container').css("opacity", ".5");
//},
success: function (data) {
if (data != "") {
$('#results').html(data);
//$('.container').css("opacity", "");
}
}
});
function check_box_values(check_box_class){
var values = new Array();
$("."+check_box_class+":checked").each(function() {
values.push($(this).val());
});
return values;
}
$('.sort_rang').change(function(){
$("#search_form").submit();
return false;
});
}
please suggest me....if you select second time that will not move to left_listing_ajax_filter file..please suggest me...i am trying to resolve this problem please help me..
The following code consists of drop-down "(id=name" which populates from "listplace.php" through ajax call which works correctly.
Now I am trying to make another ajax call using the change function. when I select the particular item already populated on dropdown box it has to pass the selected item name1 in 'where' query to dataprod.php and has to display the products by clearing the existing products list available.
I am doubtful over the $name1 response from dataprod.php. Please help!!
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$.ajax({
type: "POST",
data: {place: '<?= $_GET['place'] ?>'},
url: 'listplace.php',
dataType: 'json',
success: function (json) {
if (json.option.length) {
var $el = $("#name");
$el.empty(); // remove old options
for (var i = 0; i < json.option.length; i++) {
$el.append($('<option>',
{
value: json.option[i],
text: json.option[i]
}));
}else {
alert('No data found!');
}
}
});
</script>
ajax 2
$(document).ready(function(){
$("#name").change(function(){
var name1 = this.value;
$.ajax ({
url: "dataprod.php",
data: {place: '<?= $_GET['name1'] ?>'},
success: function (response) {
$('.products-wrp').html('')
$('.products-wrp').html(response);
}
}else {
$('.products-wrp').html('');
}
}
dataprod.php
<?php
include("config.inc.php");
$name1 = $_POST['name1'];
$results = $mysqli_conn->query("SELECT product_name, product_desc, product_code,
product_image, product_price FROM products_list where product_name='$name1'");
$products_list = '<ul id ="products_list" class="products-wrp">';
while($row = $results->fetch_assoc()) {
$products_list .= <<<EOT
<li>
<form class="form-item">
<h4>{$row["product_name"]}</h4>
<div>
<img src="images/{$row["product_image"]}" height="62" width="62">
</div>
<div>Price : {$currency} {$row["product_price"]}<div>
</form>
</li>
EOT;
}
$products_list .= '</ul></div>';
echo $products_list;
?>
Since you are calling ajax event on element which is loaded via ajax action so the change event is not bind and nothing is happend.
For ajax 2 action use below code.
$(document.body).on('change',"#name",function (e) {
//doStuff
var name1 = this.value;
$.ajax ({
url: "dataprod.php",
data: {place: '<?= $_GET['name1'] ?>'},
success: function (response) {
$('.products-wrp').html('')
$('.products-wrp').html(response);
}
}else {
$('.products-wrp').html('');
}
}
I am working on a small social network project where I am using post comment functionality. What I am stuck with is as soon as the use deletes a comment, the comment count should decrease automatically. This can onyl be done using refresh functionality, but the current code does not seem to be working. It deletes the comment but does not display the decreased count. So whenever a comment is deleted, it should show up the decreased count. Here is my code so far.
<div style="border:2px solid red;" class="comment_ui" id="view<?php echo $id; ?>">
<div>
View all <?php echo $comment_count; ?> comments
</div>
<div class="comment_ui">
<div class="comment_text">
<div class="comment_actual_text">
<?php echo $FirstName.' '.$LastName;?>
<a id="<?php echo $c_id;?>" class = "delete_comment" style="position: relative; float:right; right: 20px; text-decoration: none;" href="#">x</a><p/>
<div id="sssss"><?php echo $comment; ?></div>
</div>
</div>
</div>
JQuery
<script type="text/javascript">
$(function(){
$(".delete_comment").click(function(){
var element = $(this);
var comment = element.attr("id");
var commentRow = $(this).closest('.comment_text');
var info = "comment="+comment;
$.ajax({
type: "POST",
url: "delete_comment.php",
data: info,
success: function(){
commentRow.fadeOut('slow', function() {$(this).remove();});
$('.comment_ui').load(url + ' .comment_ui');
}
});
return false;
});
});
</script>
Try Below code
<script type="text/javascript">
$(function(){
$(".delete_comment").click(function(){
var element = $(this);
var comment = element.attr("id");
var commentRow = $(this).closest('.comment_text');
var info = "comment="+comment;
$.ajax({
type: "POST",
url: "delete_comment.php",
data: info,
success: function(){
commentRow.fadeOut('slow', function() {$(this).remove();});
$.post( url + ' .comment_ui', function( data ) {
$( ".comment_ui" ).html( data );
})
},
error: function(){
alert("somthing is wrong")
},
});
});
});
</script>
You cant use .load() like that. The variable url isn't defined and you can't add a jquery selector to the url.
If you cant .load() the exact html you need you must .get() it instead, .find() the part you need in the response and insert it with .html()
EDIT: Added code suggestion
<div style="border:2px solid red;" class="comment_ui" id="view<?php echo $id; ?>">
<div>
<a href="#" class="view_comments" id="<?php echo $id; ?>">View all
<span id="totalCommentsCount"><?php echo $comment_count; ?></span> comments</a>
</div>
<div class="comment_ui">
<div class="comment_text">
<div class="comment_actual_text">
<?php echo $FirstName.' '.$LastName;?>
<a id="<?php echo $c_id;?>" class = "delete_comment" style="position: relative; float:right; right: 20px; text-decoration: none;" href="#">x</a><p/>
<div id="sssss"><?php echo $comment; ?></div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(function(){
$(".delete_comment").click(onDeleteComment);
});
function onDeleteComment() {
var commentElement = this;
var commentId = commentElement.id;
//Start the fade-out even before the delete is committed to create a fast user experience
var commentRow = $(commentElement).closest('.comment_text');
commentRow.fadeOut('slow', function() { commentRow.remove(); });
//Post the delete to the server
$.ajax({
type: "POST",
url: "delete_comment.php",
data: { comment: commentId },
success: function (deleteResponse) {
//USE ONE OF THE ALT. BELOW:
//Alt.1: delete_comment.php returns a json like { count: 12 } which describes number of comments left
$('#totalCount').text(deleteResponse.count);
//Alt.2: you don't care to reload number of comments from server and just decrease by one.
var totalCountSpan = $('#totalCount');
totalCountSpan.text(parseInt(totalCountSpan.text()) - 1);
//Alt.3: get number of comments left on server by reloading the "view" an extra time. Really not optimal!
var viewId = $('.comment_ui').attr('id');
$.get( "get_view.php?id=" + viewId, function( data ) {
var newCount = $(data).find('#totalCount').text();
$( "#totalCount" ).text( newCount );
});
},
error: function(){
//Possibly restore the comment here if this happens often?
alert("somthing is wrong")
},
});
}
</script>