I am trying to create a simple comment bar using PHP, AJAX, MySQL and json coding.
I've got two files written in php, the first one being a controller with a following code:
<?php
require("../includes/config.php");
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$comments = query("SELECT comments.comment, comments.author, comments.time FROM comments WHERE workid = ?", $_GET["workid"]);
echo json_encode($comments);
}
else if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_SESSION["userid"])) {
throw new Exception("Login");
}
else {
$result = query("INSERT INTO comments (comment, author, time, workid) VALUES(?, ?, ?, ?)", $_POST["text"], $_SESSION["userid"], date("Y-m-d H-i-s"), $_POST["workid"]);
if ($result !== false) {
echo "success";
}
}
}
?>
The second one is purported to display the records from MySQL, based on the data from the controller:
<script>
//loads the comments
$(document).ready(function(){
var comment;
$.ajax({
type: "GET",
url: "../html/comments.php",
data: {
workid: <?php echo $id;?>
},
dataType: "json",
success: function(e) {
var lis = "";
for (var i = 0; i < e.length; i++) {
comment = e[i];
lis +=
"<li class='comment'>" +
"<div class='well'>" +
"<p>" +
"<a class='username' href='#'>" + comments.author + ": " + "</a>" +
comments.comment +
"</p>" +
"<small class='pull-right'>" + comments.time + "</small>" +
"</div>" +
"</li>";
}
$("#comments").html(lis);
},
error: function(e) {
$("#comments").html(
"<li class='comment'> Couldn't load comments </li>"
);
}
});
});
</script>
<script>
$(document).ready(function(){
$("#comment-button").click(function(){
$.ajax({
type: "POST",
url: "../html/comments.php",
data: {
workid: <?php echo $id;?>,
text: $("#comment-textarea").val()
},
dataType: "text",
success: function(e) {
var comment;
$.ajax({
type: "GET",
url: "../html/comments.php",
data: {
workid: <?php echo $id;?>
},
dataType: "json",
success: function(e) {
var lis = "";
for (var i = 0; i < e.length; i++) {
comment = e[i];
lis +=
"<li class='comment'>" +
"<div class='well'>" +
"<p>" +
"<a class='username' href='#'>" + comments.author + ": " + "</a>" +
comments.domment +
"</p>" +
"<small class='pull-right'>" + comments.time + "</small>" +
"</div>" +
"</li>";
}
$("#comments").html(lis);
$("#comment-textarea").val("");
},
error: function(e) {
$("#comments").html(
"<li class='comment'> Couldn't load comments </li>"
);
}
});
}
});
});
});
</script>
Everything works pretty fine, except of the final step; when displaying the data from the database, the only thing displayed is a statement 'undefined' instead of the corect data. Except of this, the amount of comments and form display correctly. I am using a Apache server with a php installed.
In your JavaScript code, you need to replace comments.<xxx> with comment.<xxx>, since comments is indeed an undefined object in your JaveScript.
Related
I want to add a link inside AJAX and needs a html.tpl[i]['nip'] in a tag because I want to display another view that required data with the chosen nip.
This is for PHP language in framework CodeIgniter and getting data from CURL. I have tried different ways to solve it but still, display wrong when I add link function, the AJAX is not working (not display the data).
I expect the output is when the link of detail is click the will display the view of data required with the nip. I expect the output is the table working properly and can choosing the link and can display the view that the data is required with the nip.
What's going wrong?
+"<td><a href='<?php echo site_url('admin/detail/');?>' >detail</a></td>"
document.addEventListener("DOMContentLoaded", () => {
$.ajax({
url: "<?php echo site_url('Admin/piljur');?>",
dataType: "json",
type: "POST",
cache: false,
success: function(html) {
var data = "";
for (var i = 0; i < html.tpl.length; i++) {
data += "<tr><td>" + (i + 1) + "</td>" + "<td>" + html.tpl[i]['nip'] + "</td>" + "<td>" + "<td><a href='<?php echo site_url('admin/detail/'//i want to adding the value (html.tpl[i]['nip']);?>' >detail</a></td>" + "</tr>";
}
$("#datatabel").append(data);
}
})
You could separate the detail url into a variable to be used later after the ajax call success, like this :
document.addEventListener("DOMContentLoaded", () => {
let detail_url = '<?php echo site_url('admin/detail/'); ?>';
$.ajax({
url: "<?php echo site_url('Admin/piljur');?>",
dataType: "json",
type: "POST",
cache: false,
success: function(html) {
var data = "";
for (var i = 0; i < html.tpl.length; i++) {
data += "<tr><td>" + (i + 1) + "</td>" +
"<td>" + html.tpl[i]['nip'] + "</td>" +
"<td><a href='" + detail_url + html.tpl[i]['nip'] + "' >detail</a></td></tr>";
}
$("#datatabel").append(data);
}
});
}
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();
?>
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!
custom.js file:
$(document).ready(function() {
$("#company_name").keyup(function() {
$.ajax({
type: "POST",
url: "http://localhost/capms_v2/ca_autocomplete/getcompanyName",
data: {
keyword: $("#company_name").val()
},
dataType: "json",
success: function(data) {
//alert(data);
if (data.length > 0) {
$('#DropdownCompany').empty();
$('#company_name').attr("data-toggle", "dropdown");
$('#DropdownCompany').dropdown('toggle');
} else if (data.length == 0) {
$('#company_name').attr("data-toggle", "");
}
$.each(data, function(key, value) {
if (data.length >= 0)
$('#DropdownCompany').append('<li role="displayCountries" ><a role="menuitem DropdownCompany" id=' + value['company_id'] + ' Address1=' + value['company_address1'] + ' Address2=' + value['company_address2'] + ' city=' + value['company_city'] + ' state=' + value['company_state'] + ' pincode=' + value['company_zip'] + ' class="dropdownlivalue">' +
value['company_name'] + '</a></li>');
});
}
});
});
$('ul.txtcountry').on('click', 'li a', function() {
$('#company_name').val($(this).text());
$('#company_id').val($(this).attr("id"));
// $('#company_address1').val($(this).text());
$('#tableCityID').html($(this).attr("id"));
$('#tableCityName').html($(this).text());
$('#Address1').html($(this).attr("Address1"));
$('#Address2').html($(this).attr("Address2"));
$('#city').html($(this).attr("city"));
$('#state').html($(this).attr("state"));
$('#pincode').html($(this).attr("pincode"));
});
});
I was getting id in span id="tableCityID" but if I store the value and pass the value to mysql it was not fetching the value
$com = '<span id="tableCityID">';
and if I echo the select query
echo $sql="select * from ca_job WHERE job_status!='Closed' AND job_customer_name = '".$com."'";
I get the result with not completed single codes
select * from ca_job WHERE job_status!='Closed' AND job_customer_name = '15
If anybody faces this problem, please help me. Thanks in advance.
just use the </span>
like this
$com = '<span id="tableCityID"></span>';
My function seems to return nothing for the destination element when the link is referred to from Instagram. It works fine if I directly visit the page.
function getTeamsByLeague(league) {
//console.log("League Set: " + league);
$.ajax({
url: "<?php echo SITE_BASE_URL; ?>json.php",
data: {method: "getteamsbyregion", league: league},
success: function (data) {
if (data && data.length > 0) {
$("#destination").empty();
var selected = "";
$.each(data, function (index, item) {
if (item.team == teamSelected) {
selected = " selected";
$("#latitude").val(item.lat);
$("#longitude").val(item.lng);
} else {
selected = "";
}
$("#destination").append('<option ' + selected + ' value="' + item.lat + ',' + item.lng + '">' + item.team + '</option>');
if (index == 0) {
$("#latitude").val(item.lat);
$("#longitude").val(item.lng);
}
});
}
},
type: "GET",
dataType: "json"
});
}