How to Append image using Json - php

I am creating an e-commerce site. i ran into the problem of displaying image on home page. all relevant data have displayed success. the only image couldn't be displayed.I didn't get any errors while checking the console.
what i tried so far i attached below.
Json **$("#Products").append("<img id='theImg' src='images/' + data[i].image + ' />'");** this is image append code i written.
function getProducts(){
$.ajax({
type: 'GET',
url: 'all_product.php' ,
dataType: 'JSON',
success: function (data) {
console.log(data);
for (var i = 0; i < data.length; i++)
{
$("#Products").append("<img id='theImg' src='images/' + data[i].image + ' />'");
$('#Products').append('<h5>' + data[i].description + '</h5>');
$('#Products').append('<p>' + data[i].price + '</p>');
}
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
}
all_product.php
<?php
include("db.php");
$stmt = $conn->prepare("select id,cat_id,brand_id,price,description,image,keywords from products order by id DESC");
$stmt->bind_result($id,$cat_id,$brand_id,$price,$description,$image,$keywords);
if($stmt->execute())
{
while($stmt->fetch())
{
$output[] = array("id"=>$id, "cat_id" =>$cat_id, "brand_id"=> $brand_id,"price"=> $price, "description"=> $description,
"image"=> $image, "keywords"=> $keywords);
}
echo json_encode($output);
}
$stmt->close();
?>
Design
<div class="card" style="width: 18rem;" id="Products">
<img id="theImg">
<div class="card-body">
<h5></h5>
<p class="card-text"></p>
Go somewhere
</div>
</div>

You have to change the code as following. You are missing a a double qoutes which makes variable as stirng.
$("#Products").append("<img id='theImg' src='images/" + data[i].image + "' class='your-css-class' />");

Related

Select the Category and relavent Brand Product didn't displayed on my ecommerce website

I am creating a small e-commerce website.
If I click the category the relevant products displayed successfully.
If I click the brand relevant product brand displayed successfully so far did.
My problem is if I click the category as TV and choose the brand as LG the relevant product should display. but I couldn't do the stuff what I tried so I attached below.
Category
function getCategory(){
$.ajax({
type: 'GET',
url: 'get_category.php' ,
dataType: 'JSON',
success: function (data)
{
for (var i = 0; i < data.length; i++) {
var catname = data[i].catname;
var id = data[i].id;
$('#categories').append('' + '<b>'+ data[i].catname + '<b>' + '');
}
},
error: function (xhr, status, error)
{
console.log(xhr.message)
}
});
}
Brand
function getBrand(){
$.ajax({
type: 'GET',
url: 'all_brand.php' ,
dataType: 'JSON',
success: function (data) {
console.log(data);
for (var i = 0; i < data.length; i++)
{
var id1 = data[i].id;
$('#brands').append('<a href="#" bid= '+ id1 + ' class="list-group-item list-group-item-action">' + '<b>'+ data[i].brand_name + '<b>' + '</li>');
}
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
}
Click Event of category and brand
$( document ).ready(function()
{
console.log( "ready!" );
$('#categories a.list-group-item').click(function() {
var cid = $(this).attr('cid');
get_product(cid);
});
$('#brands a.list-group-item').click(function() {
var bid = $(this).attr('bid');
get_product(bid);
});
});
Products
function get_product(cid,bid){
$.ajax({
type: 'post',
url: 'get_product.php' ,
data: {cid:cid,bid:bid},
dataType: 'JSON',
success: function (data) {
console.log(data);
$("#Products").empty();
for (var i = 0; i < data.length; i++)
{
var price = data[i].price;
var image = data[i].image;
var description = data[i].description;
$("#Products").append("<div class='col-md-4'> " +
"<div class='panel panel-info' id='Products'>" +
"<div class='card-body'>" +
"<div class='panel-heading'>" + "<h4> " + description + "</h4> " +
"<p class='panel-body'>"+ "<h3> " + price + "</h3>" +
"<p class='panel-body'> <img class='card-img-top' style='width:250px' height='250px' id='theImg' src='images/" + image + "' /> </p>" +
" <a href='#' class='btn btn-primary'>View More</a> </div> </div></div> </div>");
}
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
}
get_product.php
<?php
include("db.php");
$stmt = $conn->prepare("select id,cat_id,brand_id,price,description,image,keywords from products where cat_id = ? and brand_id = ? order by RAND() LIMIT 0,6");
$stmt->bind_result($id,$cat_id,$brand_id,$price,$description,$image,$keywords);
$cid = $_POST["cid"];
$bid = $_POST["bid"];
$stmt->bind_param("s", $cid);
$stmt->bind_result($id,$cat_id,$brand_id,$price,$description,$image,$keywords);
if ($stmt->execute()) {
while ( $stmt->fetch() ) {
$output[] = array ("id"=>$id, "cat_id"=>$cat_id,"brand_id"=>$brand_id,"price"=>$price,"description"=>$description,"image"=>$image,"keywords"=>$keywords);
}
echo json_encode($output);
}
$stmt->close();
?>

Product didn't diplay on ecommerce website

i created the e-commerce website. category and brands both are displayed successfully.
my problem is if I click the category. the product should display based on the category what I clicked. Example: if I click Tv as a category all tv product should display.like that
what i tried so far. i attached the code below.when i running the programming and click the category i got the error as "Uncaught ReferenceError: cid is not defined"
This code I wrote for display category but all category displayed successfully.
$('#categories').append('' + '<b>'+ data[i].catname + '<b>' + '');
Full code for category
Category
function getCategory(){
$.ajax({
type: 'GET',
url: 'get_category.php' ,
dataType: 'JSON',
success: function (data)
{
for (var i = 0; i < data.length; i++)
{
var catname = data[i].catname;
var id = data[i].id;
$('#categories').append('' + '<b>'+ data[i].catname + '<b>' + '');
}
},
error: function (xhr, status, error)
{
console.log(xhr.message)
}
});
}
}
when i click the category the relevant product should be displayed I wrote the code below
$("#categories").click(function ()
{
$.ajax({
type: 'post',
url: 'get_product.php' ,
data: {cid:cid},
dataType: 'JSON',
success: function (data) {
console.log(data);
for (var i = 0; i < data.length; i++)
{
var price = data[i].price;
var image = data[i].image;
var description = data[i].description;
$("#Products").append("<div class='col-md-4'> " +
"<div class='panel panel-info' id='Products'>" +
"<div class='card-body'>" +
"<div class='panel-heading'>" + "<h4> " + description + "</h4> " +
"<p class='panel-body'>"+ "<h3> " + price + "</h3>" +
"<p class='panel-body'> <img class='card-img-top' style='width:250px' height='250px' id='theImg' src='images/" + image + "' /> </p>" +
" <a href='#' class='btn btn-primary'>View More</a> </div> </div></div> </div>");
}
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
});
get_product.php page
<?php
include("db.php");
$stmt = $conn->prepare("select id,cat_id,brand_id,price,description,image,keywords from products where id = ? order by RAND() LIMIT 0,6");
$stmt->bind_result($id,$cat_id,$brand_id,$price,$description,$image,$keywords);
$cid = $_POST["cid"];
$stmt->bind_param("s", $cid);
if ($stmt->execute()) {
while ( $stmt->fetch() ) {
$output[] = array ("id"=>$id, "cat_id"=>$cat_id,"brand_id"=>$brand_id,"price"=>$price,"description"=>$description,"image"=>$image,"keywords"=>$keywords);
}
echo json_encode($output);
}
$stmt->close();
?>
I think this gives you error, you need to get clicked category id
var cid = $(this).attr('cid'); // Use this and try
data: {cid:cid},
You are calling click event on categories; you should call click event on a tag;
Replace you click event;
$("#categories").click(function ()
{
// You code here
}
with this code;
$("a.list-group-item").click(function ()
{
var cid = $(this).attr('cid');
// You code here
}
Hope this will be useful for you!

instagram load more button

UPDATE:
At this moment I have a basic working instagram image display on my website.
What I like to create is a "load next 12 images" button. When I use "max_id=" directly in my url it is working fine.
Can someone point me in the correct direction to make this work?
This is what I have right now:
<style>
section.instagram img {
float:left;
height: 200px;
margin: 10px;
}
</style>
<?php
$otherPage = 'nasa';
$response = file_get_contents("https://www.instagram.com/$otherPage/?__a=1");
if ($response !== false) {
$data = json_decode($response, true);
$userdata = $data['user'];
$mediadata = $data['user']['media']['nodes'];
if ($data !== null) { ?>
<section class="instagram">
<?php
$cnt = count($mediadata) > 12 ? 12 : count($mediadata);
echo $cnt;
for($i = 0; $i < $cnt; $i++){
?>
<img src="<?php echo $mediadata[$i]['thumbnail_src']; ?>" alt="">
<?php
}
?>
</section>
<?php
} // end of response check
} // end of data null
?>
i just finished a code that does that, but im using javascript, here it is!
<!DOCTYPE html>
<html>
<body>
<p id="add-data"></p>
<a id="LoadMore" >Load More</a>
<!--Add jquery-->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
<script>
//Add your token
var token = '[your access token]';
//Declare the var to save the nexturl from the API
nexturl = '';
//First call will load at the beginning of the site
$.ajax({
//Modify the count value to set how many photos you want to load
url: 'https://api.instagram.com/v1/users/self/media/recent/?access_token='+ token + '&count=12',
dataType: 'jsonp',
type: 'GET',
data: {access_token: token},
success: function(data){
//Gather The images of the User
for(i =0;i < data.data.length ;i++){
//this variables are just to save the data and simplify you
// can also use the data.data[] info instead
img = data.data[i].images.low_resolution.url;
img_link = data.data[i].link;
likes = data.data[i].likes.count;
comments = data.data[i].comments.count;
interactions = data.data[i].comments.count + data.data[i].likes.count;
//Appends the variables inside the div
$("#add-data").append("<img src='" + img +"' width='150px' height='150px'> <p>Likes: "+likes+"</p><p>Comments: "+comments+"</p><p>Total Interactions: "+interactions+"</p></div><div class='card-action'><a href='" + img_link + "'>Check Photo</a> ");
}
nexturl = data.pagination.next_url;
},
error: function(data){
console.log(data)
}
});
//Load More Photos From Instagram
//If you click on the Load More text / button / etc it will run again the code
//adding the next 12 photos
$('#LoadMore').click(divFunction);
function divFunction(e){
e.preventDefault();
//Each request from instagram can handle only 33 Images (that's how the API works')
$.ajax({
url: nexturl, // we don't need to specify parameters for this request - everything is in URL already
dataType: 'jsonp',
type: 'GET',
success: function(data){
for(x in data.data){
img = data.data[x].images.low_resolution.url;
img_link = data.data[x].link;
likes = data.data[x].likes.count;
comments = data.data[x].comments.count;
interactions = data.data[x].comments.count + data.data[x].likes.count;
//console.log('Image ID: ' + img_id + ' Image Link: ' + img_link + ' Likes: ' + likes);
i ++;
$("#add-data").append("<div class='col s4'><div class='card horizontal'><div class='card-image'><img src='" + img +"' width='150px' height='150px'></div><div class='card-stacked'><div class='card-content'><p >Likes: "+likes+"</p><p>Comments: "+comments+"</p><p>Total Interactions: "+interactions+"</p></div><div class='card-action'><a href='" + img_link + "'>Check Photo</a></div></div></div></div>");
}
nexturl = data.pagination.next_url;
console.log(tot_nexturl)
},
error: function(result2){
console.log(result2);
}
});
}
</script>
</body>
</html>
Hope this helps !

JSON values not showing properly

I wrote a php script which accept POST request from ajax and give the response back. All working fine. But the receiving string split letter by letter I can't understand what is the reason.
Here is my AJAX code,
$("#btn").click(function(){
console.log($("#search_bar").val());
var dataV;
var htmlText = '';
var containerbootsrap = '';
var filename = '';
var index_no;
$.ajax({
type: "POST",
crossDomain: true,
url: "http://localhost:8090/ontology/setText",
data: $("#search_bar").val(),
contentType: 'text/plain',
// dataType: "json",
success: function( data, textStatus, jQxhr ){
console.log('data');
console.log(data);
for( var item in data) {
console.log ("item: " + item);
console.log ("data: " + data[item]);
index_no = data[item];
// htmlText += '<div class="div-conatiner">';
// htmlText += '<p class="p-name"> Name: ' + data[item] + '</p>';
// htmlText += '<img class="imageload" src="' + data[item] + '" />';
// htmlText += '</div>';
// filename = data[item].replace(/^.*[\\\/]/, '')
$.ajax({
data: 'index_no=' + index_no,
url: 'retrivedata.php',
method: 'POST', // or GET
dataType: 'json',
success: function(msg) {
console.log(msg);
for(var item in msg){
console.log ("item: " + item);
console.log ("data: " + msg[item]);
}
$('#home').hide();
containerbootsrap += '<div class = "container" id="search_container">';
containerbootsrap += '<div class = "row homepage">';
containerbootsrap += '<div class = "col-md-5 col-md-offset-3">';
containerbootsrap += '<a href="#" class="thumbnail">';
containerbootsrap += '<img class="imageload" src="' + msg + '" />';
containerbootsrap += '<h3 id="video_name"> ' + filename + ' </h3>'
containerbootsrap += '</a>';
containerbootsrap += '</div>';
containerbootsrap += '</div>';
containerbootsrap += '</div>';
$('body').append(containerbootsrap);
}
});
// $.post('retrivedata.php', { num: 5 }, function(result) {
// alert(result);
// });
// $('#home').hide();
}
// $('body').append(containerbootsrap);
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( jqXhr );
alert(jqXhr)
}
});
});
php code is below
<?php
$index_no = $_POST["index_no"];
// echo $index_no * 2;
include('dbConnection.php');
$query = mysql_query("SELECT * FROM video_data WHERE index_no = $index_no");
while ($row = mysql_fetch_assoc($query)) {
$imagePath = $row['thumbnail_url'];
$videoPath = $row['video_url'];
// echo $imagePath;
// echo $videoPath;
echo json_encode($imagePath);
}
?>
I need the output as : 'imagepath'
but it is giving the output as split letter by letter.
here is the real output
Output
but i need the output in one line. like /video_frames/bb/frame136.jpg
please help me to figure out where I am going wrong.
Well, in the php code where you're returning the value you need to specify an array not an string. The variable there $imagePath seems to be a string. You can do something like this.
echo json_encode(array('result' => $imagePath));
This will give you your result in the 'result' key. You can parse it and use it.
You need to parse the returned JSON string into an array. One way to do it is by adding data = $.parseJSON(data) in the ajax success callback (highlighted below). I was able to recreate the same thing you're seeing and adding this line fixed it. Hope this helps. parseJSON()
...
success: function( data, textStatus, jQxhr ){
console.log('data');
console.log(data);
data = $.parseJSON(data);
for( var item in data) {
console.log ("item: " + item);
console.log ("data: " + data[item]);
index_no = data[item];
...
Better way to check the type of value in variable you are getting first like
data = '{"name": "Bhushan"}' //string value
data = {name: "Bhushan"} //object value
//for testing you can use either, this will make it unbreakable for this context
if(typeof(data) == 'string')
{
data = JSON.parse(data)
}
//rest of code
This will give your module good stability otherwise you may get json parse unexpected token o.

Image AJAX search not working in Safari

I have a live image search that uses AJAX and an SQL query to find images with a name the same as the users input on a text field. I thought it was working fine until I tested in Safari, and it does literally nothing.
I'm not too sure why not even an error is returned in Safari, does anyone know of an issue in Safari that might be stopping it from working?
jQuery:
var input = $('.image-search');
var value;
var append = $(".results-append");
var loadUrl = '/stock-image-search.php';
var results = $('.results');
var resultsDiv = '<div class="results-heading"><h2>Results for "<span class="results-for"></span>"</h2></div>';
var resultsFor;
var nothingFound = '<div class="nothing-found"><br /><span>No results found.</span></div>'
// on keyup
input.on("keyup", function() {
// remove everything that was there
$('.results-append').remove();
results.empty();
$("#temp_load").remove();
value = input.val();
append.prepend(resultsDiv);
resultsFor = $('.results-for');
resultsFor.html($(this).val());
// ajax the results!
$.ajax({
type: "GET",
data: {
nameLike: value
},
dataType: "html",
url: templateDir + loadUrl,
beforeSend: function() {
append.hide().append('' +
'<div id="temp_load" class="search-loader">' +
'<img src="' + templateDir + '/img/load.GIF" />' +
'</div>'
).fadeIn(200);
},
success: function(data) {
$("#temp_load").fadeOut(200);
// fix for fast typers
results.empty();
var data = $(data);
if (data.length) {
results.append(data);
} else {
results.append(nothingFound);
}
},
error: function(jqXHR, textStatus, errorThrown) {
$("#temp_load").fadeOut(200).remove();
console.log(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
});
PHP function:
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/wp-load.php' );
global $wpdb;
if( isset($_GET['nameLike']) && strlen($_GET['nameLike']) > 1 ) :
$search = $_GET['nameLike'];
$results = $wpdb->get_results( $wpdb->prepare("
SELECT ID
FROM $wpdb->posts
WHERE $wpdb->posts.post_status = 'inherit'
AND $wpdb->posts.post_mime_type != ''
AND ( $wpdb->posts.post_author = 1 OR $wpdb->posts.post_author = 3 )
AND $wpdb->posts.post_title LIKE %s
", '%' . like_escape($search) . '%'
), ARRAY_A);
foreach ($results as $result) : ?>
<?php
$image = wp_get_attachment_image( $result[ID], array(200, 150) );
?>
<div class="grid-1-4 clearfix">
<div class="stock-image-select clearfix" data-id="<?php echo $result[ID]; ?>">
<?php echo $image; ?>
</div>
</div>
<?php endforeach;
else : ?>
<div class="grid-10">Your search needs to be at least 2 characters long.</div>
<?php endif; ?>
If anyone can see a glaring error, please let me know :)
Try something like this
$(document).ready(function() {
$('input[name="search_field"]').keyup(function(e){
$(this).text;
//process your search
});
});
When you detect a key was raised then take the text and do the search.

Categories