jQuery PHP MySQL Like button - javascript

I would like to create a like button using PHP, MySQL and jQuery, but seems there's an error, i don't know where is it, can you help ?
I have two pages [index.php & callback.php]
INDEX
$k = 1; //POST ID
$nip = 24; //USER ID
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click', '.like', function(){
if($(this).attr('title')=='Like'){
$.post('callback.php',{k:$(this).attr('id'),action:'like'},function(){
$(this).text('Unlike');
$(this).attr('title','Unlike');
});
}else{
if($(this).attr('title')=='Unlike'){
$.post('callback.php',{k:$(this).attr('id'),action:'unlike'},function(){
$(this).text('Like');
$(this).attr('title','Like');
});
}
}
});
});
</script>
</head>
<body>
<?php
$query=$db->prepare("SELECT * FROM activity WHERE nip = :nip AND value = :value");
$query->execute(array(
':nip' => $meNip,
':value' => $k
)
);
$all = $query->rowCount();
if($query->rowCount()==1){
echo 'Unlike <b>'.$all.'</b>';
}else{
echo 'Like <b>'.$all.'</b>';
}
?>
</body>
</html>
CALLBACK
$nip= //COOKIE
$k= $_POST['k'];
$action=$_POST['action'];
if (!empty($k)) {
$checkAd=$db->prepare("SELECT * FROM ad WHERE id = :id");
$checkAd->execute(array(
':id' => $k
)
);
$checkingAd=$checkAd->fetchAll(PDO::FETCH_ASSOC);
foreach ($checkingAd as $row) {
//LIKE
if ($action=='like'){
$callback=$db->prepare("SELECT * FROM activity WHERE nip = :nip AND value = :value");
$callback->execute(array(
':nip' => $meNip,
':value' => $k
)
);
$matches=$callback->rowCount();
if($matches==0){
$callback=$db->prepare("UPDATE ad SET likes = :likes WHERE id = :id");
$callback->execute(array(
':likes' => $row['likes']+1,
':id' => $k
)
);
$callback=$db->prepare("INSERT INTO activity (nip, value) VALUES(:nip, :value)");
$callback->execute(array(
':nip' => $meNip,
':value' => $k
)
);
}
}elseif ($action=='unlike'){ //UNLIKE
$callback=$db->prepare("SELECT * FROM activity WHERE nip = :nip AND value = :value");
$callback->execute(array(
':nip' => $meNip,
':value' => $k
)
);
$matches=$callback->rowCount();
if($matches==1){
$callback=$db->prepare("UPDATE ad SET likes = :likes WHERE id = :id");
$callback->execute(array(
':likes' => $row['likes']-1,
':id' => $k
)
);
$callback=$db->prepare("DELETE FROM activity WHERE nip = :nip AND value = :value");
$callback->execute(array(
':nip' => $meNip,
':value' => $k
)
);
}
}
}
}
?>
I tested the callback.php file, (address bar using GET) it's working fine, can you check the INDEX, i think, i miss something, a dot ?
Thanks for your help

Your reference to $(this) in $.post is incorrect. You probably assumed $(this) will be the .like element, but that's not the case. this in a $.post would return something similar:
Object { readyState=1, getResponseHeader=function(), getAllResponseHeaders=function(), more...}
Object { url="callback.php", type="POST", isLocal=false, more...}
The code below should change the text accordingly.
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click', '.like', function(){
var $this = $(this);
var likes_count = $('.likes_count');
if($(this).attr('title')=='Like'){
$.post('callback.php',{k:$(this).attr('id'),action:'like'},function(){
$this.text('Unlike');
$this.attr('title','Unlike');
var likes = parseInt(likes_count.text())+1;
likes_count.text(likes);
});
}else{
if($(this).attr('title')=='Unlike'){
$.post('callback.php',{k:$(this).attr('id'),action:'unlike'},function(){
$this.text('Like');
$this.attr('title','Like');
var likes = parseInt(likes_count.text())-1;
likes_count.text(likes);
});
}
}
});
});
</script>

Related

Can't retrieve data from controller to view page without refreshing

I'm new to coding and I'm trying to create a simple project which is a BMI calculator. Every time I hit the 'calculate' button the page posts the data with the DIV element for a second then the page refreshes.
Here's my code from controller:
<?php
class Cal extends BaseController
{
protected $helpers = ['url', 'form', 'text', 'html'];
public function calc(){
return view('calc');
}
public function calculator(){
$bmi = new BMI();
$height = $this->request->getPost('height');
$weight = $this->request->getPost('weight');
$bmicalc = $weight/($height*$height);
$result;
if($bmicalc <= 18.5){
$result = "Underweight";
}elseif($bmicalc > 18.5 AND $bmicalc<=24.9){
$result = "Normal weight";
}elseif($bmicalc > 24.9 AND $bmicalc<=29.9){
$result = "Overweight";
}elseif($bmicalc > 30.0){
$result = "OBESE";
}elseif($bmicalc > 31.0){
$result = "OBESE 2";
}
$bmiInsert = array(
'weight' => $this->request->getPost('weight'),
'height' => $this->request->getPost('height'),
'res' => $result,
);
$data = [
'res' => $result,
];
$bmi->insert($bmiInsert);
return view('calc', $data);
}
}
Here's my code for my view page:
<div class="try">
<?php
if(isset($res[0]))
echo "Your BMI is ", "$res";
?>
</div>
Now here's the script that I've tried already:
$(".btn-check").click(function() {
$('form').submit(function() {
$(".try").css('display', 'block');
event.preventDefault();
});
});
I've also tried changing the button type into "button" instead of "submit" but still no avail.
You need to pass event as an function parameter to submit to prevent default behaviour
$(".btn-check").click(function() {
$('form').submit(function(event) {
$(".try").css('display', 'block');
event.preventDefault();
});
});

AJAX load more function multiplies the old data?

I have a PHP code that creates a JSON data from wordpress posts in the database.
I load this JSON on my html page using AJAX.
The above works fine.
Now I need to add a "Load More" button so everytime its pressed, we load another 10 posts and append/add them to the ones that were already loaded WITHOUT having to delete the old ones and re-adding them.
So this my AJAX code for loading more:
var i = 0;
$(document).on("click", ".loadMoreBtn", function () {
$.ajax({
url: 'https://some-domain.com/index.php?t=' + mainCat + '&page=' + i + '',
dataType: 'json',
jsonp: 'jsoncallback',
timeout: 5000,
success: function (data, status) {
if (!$.trim(data)) {
}
else {
}
$.each(data, function (pi, item) {
var id = item.id;
var img = item.img;
var title = item.title;
var date_added = item.date_added;
var item = '' + title + '';
$('.myDiv').before(item);
i++;
});
},
error: function () {
//error handling////
}
});
});
And this is my PHP code:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-config.php';
include_once $path . '/wp-load.php';
include_once $path . '/wp-includes/wp-db.php';
include_once $path . '/wp-includes/pluggable.php';
$t = $_GET['t'];
$page = $_GET['page'];
$posts = get_posts(array(
'posts_per_page' => $page, //add -1 if you want to show all posts
'post_type' => 'post',
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $t //pass your term name here
)
))
);
$output= array();
foreach( $posts as $post ) {
$feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
$mysqldate = $post->post_date;
$phpdate = strtotime( $mysqldate );
$mysqldate = date( 'F d Y', $phpdate );
// Pluck the id and title attributes
$output[] = array( 'id' => $post->ID, 'title' => $post->post_title, 'date_added' => $mysqldate, 'img' =>$feat_image );
}
echo json_encode( $output );
When I click on the 'Load More' button, it acts strangely! it basiclaly adds the old data and multiplies the same ones and adds/loads some new ones as well.
I know I am missing something in my PHP code but I couldn't figure out what.
Could someone please advice on this issue?
Thanks in advance.
The error is in your wordpress query. "posts_per_page" set how many posts will be loaded. Set that as how many post should be loaded like 12 or something.
The parameter your want to set as your $page parameter is "paged".
Eg. $query = new WP_Query( array( 'paged' => 6 ) ); // page number 6
https://codex.wordpress.org/Class_Reference/WP_Query#Pagination_Parameters
You could also use WP API instead of rolling your own

button radio wont stay checked after update Wordpress

I m trying to implement query with custom fields on my local wordpress website.
All works like a charm except when I check the radio button, this one want to be checked...
Can you help me please ? thanks for your reply.
<div id="archive-filters">
<?php foreach( $GLOBALS['my_query_filters'] as $key => $name ):
$field = get_field_object($key);
if( isset($_GET[ $name ]) ) {
$field['value'] = explode(',', $_GET[ $name ]);
}
// create filter
?>
<div class="filter" data-filter="<?php echo $name; ?>">
<?php create_field( $field ); ?>
</div>
<?php endforeach; ?>
</div>
<script type="text/javascript">
(function($) {
// change
$('#archive-filters').on('change', 'input[type="radio"]', function(){
var url = '';
args = {};
$('#archive-filters .filter').each(function(){
var filter = $(this).data('filter'),
vals = [];
$(this).find('input:checked').each(function(){
vals.push( $(this).val() );
});
// append to args
args[ filter ] = vals.join(',');
});
// update url
url += '?';
// loop over args
$.each(args, function( name, value ){
url += name + '=' + value + '&';
});
// remove last &
url = url.slice(0, -1);
// reload page
window.location.replace( url );
});
})(jQuery);
</script>

Autocomplete Multiple Values in Codeigniter

I have problem with autocomplete in Codeigninter and Jquery
I have a controller
<?php
public function search() {
$user = $_GET['term'];
$query = $this
->db
->select('nama_kota')
->like('nama_kota', $user)
->get('kota');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row) {
$row_set[] = htmlentities(stripslashes($row['nama_kota']));
}
echo json_encode($row_set);
}
}
?>
I have a view
<script>
$(function () {
var availableTags = "<?php echo base_url('admin/kota/search'); ?>";
$("#user-input").autocomplete({
source: availableTags
});
});
</script>
<input id="user-input" type="text" name="nama_kota" placeholder="Search User" autocomplete="on">
everything its okay
but I'm trying multiple values
<script>
$(function () {
var availableTags = "<?php echo base_url('admin/kota/search'); ?>";
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
$("#user-input").autocomplete({
minLength: 0,
source: function (request, response) {
// delegate back to autocomplete, but extract the last term
response($.ui.autocomplete.filter(
availableTags, extractLast(request.term)));
},
focus: function () {
// prevent value inserted on focus
return false;
},
select: function (event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
});
</script>
<input id="user-input" type="text" name="nama_kota" placeholder="Search User" autocomplete="on">
no work and availableTags only read addres url no function in controller
whats wrong guys please help me, Thanks
which type off output you need If you need like this
eg.
name,
address,
blood_group.
with output of Autocomplete call
Sorry For late reply I am very very busy in my work
this is JS call to Controller
<script>
jQuery("#h_student_name").autocomplete({
minLength: 0,
source: "DropdownController/hostel_students/" + $("#h_student_name").val(),
autoFocus: true,
scroll: true,
dataType: 'jsonp',
select: function (event, ui) {
jQuery("#h_student_name").val(ui.item.contactPerson);
jQuery("#h_student_id").val(ui.item.code);
}
}).focus(function () {
jQuery(this).autocomplete("search", "");
});
</script>
and this is controller for call
<?php
//Hostel Student Auto compelete
public function hostel_students(){
$term = trim(strip_tags($this->input->get('term')));
if( $term == ''){
$like = $term;
$result_set = $this->DropdownModel->hostel_students(array('hostel_status_id' => 1));
$labels = array();
foreach ($result_set as $row_set) {
$labels[] = array(
'label' => $row_set->student_name.' S/D '.$row_set->father_name.' ,Form# '.$row_set->form_no.' ',
'code' => $row_set->hostel_id,
'value' => $row_set->student_name,
);
}
$matches = array();
foreach($labels as $label){
$label['value'] = $label['value'];
$label['code'] = $label['code'];
$label['label'] = $label['label'];
$matches[] = $label;
}
$matches = array_slice($matches, 0, 10);
echo json_encode($matches);
} else if($term != ''){
$like = $term;
$result_set = $this->DropdownModel->hostel_students(array('hostel_status_id' => 1), $like);
$labels = array();
foreach ($result_set as $row_set) {
$labels[] = array(
'label' => $row_set->student_name.' S/D '.$row_set->father_name.' ,Form# '.$row_set->form_no.' ',
'code' => $row_set->hostel_id,
'value' => $row_set->student_name,
);
}
$matches = array();
foreach($labels as $label){
$label['value'] = $label['value'];
$label['code'] = $label['code'];
$label['label'] = $label['label'];
$matches[] = $label;
}
$matches = array_slice($matches, 0, 10);
echo json_encode($matches);
}
}
?>
and this is model for call
<?php
// Hostel student autocomplete
public function hostel_students($where, $like = NULL){
if($like):
$this->db->like('student_name', $like);
$this->db->or_like('form_no', $like);
$this->db->or_like('college_no', $like);
endif;
$this->db->join('student_record', 'student_record.student_id=hostel_student_record.student_id');
return $this->db->where($where)->get('hostel_student_record')->result();
}
}
?>
have any issue comment me I will online today

$.getJSON with php file

Hi guys :) I'm quite new in the programming world, so I really need your help. I tryed to get data from some database tables and unfortunately something goes wrong in my $.getJson() function . If i run the php file it works , and so that with the functions from script.js . My html is also ok so i suppose it is the $get.JSON fault. I don't know so many javascript , so i put all my hopes into you :*
html file:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>jQuery Ajax - PHP</title>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<script src="script.js">
</script>
</body>
</html>
script.js file :
$('document').ready( function() {
done();
}
);
function done() {
setTimeout(function() {
updates();
done();
}
, 200 );
}
function updates(){
$.getJSON( "read.php", function (data){
$.each(data.array, function () {
$("body").append("<li>Titlu: "+this['title']+"</li>
<li>Descriere: "+this['describtion']+"</li>");
}
);
$.each(data.array1, function () {
$("body").append("<li>Id: "+this['id']+"</li>
<li>Category_Id: "+this['category_id']+"</li>
<li>Titlu: "+this['title']+"</li>
<li>Descriere: "+this['describtion']+"</li>");
}
);
$.each(data.array2, function () {
$("body").append("<li>Id: "+this['id']+"</li>
<li>Titlu: "+this['title']+"</li>
<li>Latitudine: "+this['location_latitude']+"</li>
<li>Longitudine:"+this['location_longitude']+"</li>
<li>Numar de telefon: "+this['phone_number']+"</li>
<li>Descriere: "+this['describtion']+"</li>");
}
);
$.each(data.array3, function () {
$("body").append("<li>Id: "+this['id']+"</li>
<li>Interest_point_id:"+this['interest_point_id']+"</li>
<li>Pret: "+this['price']+"</li>
<li>Data: "+this['event1_time']+"</li>");
}
);
}
);
}
And finally the read.php file (Here it shows me what i expect , so i think everything is all right) :
<?php
include_once ('db.php');
$query= "SELECT * FROM category";
$query1= "SELECT * FROM sub_category";
$query2= "SELECT * FROM interest_point";
$query3= "SELECT * FROM event1";
global $connect;
$result = mysqli_query($connect,$query);
$result1 = mysqli_query($connect,$query1);
$result2 = mysqli_query($connect,$query2);
$result3 = mysqli_query($connect,$query3);
$array = array();
$array1 = array();
$array2 = array();
$array3 = array();
while($row=mysqli_fetch_array($result))
array_push($array , array( 'id' => $row[0],
'title' => $row[1],
'describtion' => $row[2]
));
while($row1=mysqli_fetch_array($result1))
array_push($array1 , array( 'id' => $row1[0],
'category_id' => $row1[1],
'title' => $row1[2],
'describtion' => $row1[3]
));
while($row2=mysqli_fetch_array($result2))
array_push($array2 , array('id' => $row2[0],
'title' => $row2[1],
'location_latitude' => $row2[2],
'location_longitude'=> $row2[3],
'phone_number' => $row2[4],
'describtion' => $row2[5]
));
while($row3=mysqli_fetch_array($result3))
array_push($array3 , array(
'id' => $row3[0],
'interest_point_id'=> $row3[1],
'price' => $row3[2],
'event1_time' => $row3[3]
));
echo json_encode(array("array"=>$array)).'<br>'.'<br>';
echo json_encode(array("array1"=>$array1)).'<br>'.'<br>';
echo json_encode(array("array2"=>$array2)).'<br>'.'<br>';
echo json_encode(array("array3"=>$array3)).'<br>'.'<br>';
?>
You can only echo once when sending json and there can only be one php array containing all the data. You can't print anything outside of this such as the <br> tags
try changing
echo json_encode(array("array"=>$array)).'<br>'.'<br>';
echo json_encode(array("array1"=>$array1)).'<br>'.'<br>';
echo json_encode(array("array2"=>$array2)).'<br>'.'<br>';
echo json_encode(array("array3"=>$array3)).'<br>'.'<br>';
To
$output = array(
"array1"=>$array1,
"array2"=>$array2,
"array3"=>$array3
);
echo json_encode($output);
Also note that <li> is an invalid child of <body>. Use <div> or insert into a <ul>

Categories

Resources