I am trying to implement a "like" button for my website. I am using Codigniter, Ajax and Jquery. When the like button is clicked data should be entered to database and if unlike button is pressed data should delete from database. But I am facing a problem in model, data is not added to database when I click like button. Please help me to find a solution.
This is my Jquery file "likeitem.js"
function likeItem(postId)
{
if ($("#likeItem_"+postId).text() == "Like")
{
$("#likeItem_"+postId).html('Unlike');
var purpose = "Like";
}
else
{
$("#likeItem_"+postId).html('Like');
var purpose = "UnLike";
}
$.ajax({
type : "POST",
url : "http://localhost/codeig_smarty/index.php/user/likeItem",
data : "postId=" + postId + "purpose=" + purpose,
success : function()
{
}
});
return false;
}
This is my model "usermodel.php"
public function itemLike()
{
$id = $this->session->userdata('userID');
$postId = $this->input->post('postId');
$purpose = $this->input->post('purpose');
if($purpose=="Like")
{
// echo 'test';
// exit();
$data = array(
"userID" => $id,
"postTextID" => $postId,
);
$this->db->insert('like', $data);
}
else
{
echo 'hai';
}
}
This is my view file "home.tpl"
<li><a class="like-unlike" href="#" id="likeItem_{$item['postID']}" onclick="likeItem({$item['postID']})">Like</a></li>
This is my Controller "user.php"
public function likeItem()
{
$this->usermodel->itemLike();
}
You mistake here. You forgot to put & symbol. Try this code.
data : "postId=" + postId + "&purpose=" + purpose,
Full code:
If you want to manipulate result returned from ajax, you can do something on success block as following code :
$.ajax({
type : "POST",
url : "http://localhost/codeig_smarty/index.php/user/likeItem",
data : "postId=" + postId + "&purpose=" + purpose,
success : function(data)
{
// do seomthing here with data
// console.log(data) --> to see data return or not
}
});
Related
How do you run Classes from an external file from the functions.php?
I'm using WordPress and the Beaver Builder plugin. I have a pagination list with info from the WP db. This is on a page using a search template (search.php). It includes a file (get-jobs.php). In order to see the results, I have to use a PHP Snippet plugin to set a global variable on the page that recognizes the $result variable provided by get-jobs.php, as I use the built-in modules to layout the page.
This works so far. I can see my formatted results.
When the pagination button is clicked, a function is called from my js file(custom-script.js) to update the results.
function selectJobs() {
$.ajax({
url: site_url + '/get-jobs.php',
type: "GET",
data: {
ajax': '1',
'state': GetURLParameter('country'),
'limit': GetURLParameter('limit')
},
success:function(data) {
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
}
This doesn't work and I received a 403(Forbidden) error. I changed it to this:
function selectJobs(country) {
var country = country;
$.ajax({
url: ajaxurl,
type: "POST",
data: {
'action':'country_ajax_request',
'country' : country
},
success:function(data) {
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
}
...which got rid of the error, and submitted the request.
In my functions.php, I have this:
function country_ajax_request() {
//include_once( get_stylesheet_directory() .'/get-jobs.php');
MY FUNCTIONS GO HERE
}
add_action( 'wp_ajax_country_ajax_request', 'country_ajax_request' );
add_action( 'wp_ajax_nopriv_country_ajax_request', 'country_ajax_request' );
Here's an bit of what's in get-jobs.php:
<?php
$get = (!empty($get) ? $get : $_REQUEST);
if(isset($get['ajax']) && $get['ajax'] == 1) {
require_once($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php');
}
class GetJobs {
private $wpdb;
public function __construct($input) {
global $wpdb;
$this->wpdb = $wpdb;
$this->tableName = $this->wpdb->prefix . 'job_postings';
$this->country = (!empty($input['country']) ? $input['country'] : '');
$this->page = (!empty($input['page']) ? $input['page'] : '');
$this->limit = (!empty($input['limit']) ? $input['limit'] : 10);
}
public function getLocations() {
$result = [];
$states = $this->wpdb->get_results("SELECT country FROM " . $this->tableName . " WHERE deleted_at = '0000-00-00 00:00:00'");
foreach ($country as $key=>$row) {
$result[$row->country] = $row->country;
}
return $result;
}
// almost 200 more lines of this
}
$get['page'] = (!empty($get['page']) ? $get['page'] : 1);
$jobs = new GetJobs($get);
$query = $jobs->getQuery();
$jobsQuery = $jobs->getJobsQuery($query,(!empty($get['limit']) ? $get['limit'] : $jobs->limit));
$result['postings'] = $jobs->formatPostings($jobsQuery);
if(isset($get['ajax']) && $get['ajax'] == 1){
echo json_encode($result);
}
I tried to include the file, but that didn't work. It pulled data, but didn't seem go through the functions.
I want to reuse the existing file to perform the update list task. I don't want to rewrite get-jobs.php, if possible. I've used this same code just fine on other projects. Just not with this plugin.
Any thoughts or assistance as how I can approach this problem is appreciated.
Thanks.
UPDATE
I took another look at that include. It is pulling data. However, it's generates a json file, following by all of the html. The HTML is malformed. Here's what the beginning looks like:
<div id="postings" style="display: block;">{"states":{"AB":"AB","AZ":"AZ","BC":"BC","CA":"CA","FL":"FL","GA":"GA","IL":"IL","KS":"KS","NC":"NC","NS":"NS","ON":"ON","PA":"PA","QC":"QC","WA":"WA"},"category":{"":"","Accounting":"Accounting","Customs":"Customs","Finance":"Finance","Human Resources":"Human Resources","IT":"IT","Information Technology":"Information Technology","International":"International","Marketing":"Marketing","Marketing and Communications":"Marketing and Communications","Operations":"Operations","Project Management":"Project Management","Reception":"Reception","Sales":"Sales","Warehouse":"Warehouse"},"postings":"\n\t\t\t\t\t
I'm using MVC pattern in my project and I have controller product with method delete($slug)
On my page (~/show/basket) I have products that user wants to buy. There's a 'delete' button and when he clicks on that button I want to delete that product from SESSION and remove from current page.
I was trying with jquery ajax function:
$(document).ready(function() {
$('.on-delete').on('click', function() {
var path = '/ITAKADEMIJA_zavrsni_rad/3-itcomm/';
var slug = $(this).data('slug');
$.ajax({
url: $(location).attr('host') + path + 'product/delete/' + slug,
success: function(res) {
console.log(res);
},
error: function(err) {
console.log('ERROR!');
}
});
});
});
and then I have a method delete inside product controller
public function delete($slug)
{
$cardModel = $this->model('Card');
if ($slug === null) {
header("Location:" . BASE_ROOT . '/show/products');
} else if ($cardModel->getProduct($slug)) {
$product = $cardModel->getProduct($slug);
$cardModel->removeProduct($product);
header("Location: " . BASE_ROOT . '/show/basket');
}
}
public function removeProduct($product)
{
if (isset($_SESSION['products'][$product->slug]))
{
unset($_SESSION['products'][$product->slug]);
}
}
Now the problem is:
I'm getting this error:
Warning: call_user_func_array() expects parameter 1 to be a valid callback, class 'App\Controllers\Show' does not have a method 'index' in C:\Users\nikol\Dropbox\www\ITAKADEMIJA_zavrsni_rad\3-itcomm\app\Core\App.php on line 50
Nothing happens, that product is still in session. It looks like that function wasn't even called.
I would like to call the function, that function should remove product from session and from that page.
I am having trouble with a form I created and trying to redirect the data someplace else by a JavaScript method that I call whenever the submit button is clicked.
The first thing that is happening, is that the form is created and filled in, then the user will click on the HTML generated button with this action in it:
onclick="javascript:saveEssayScore(<?php echo $key . "," . $pid; ?>);"
Secondly the script file is read and performed. The code is below:
<script type="text/javascript" language="javascript">
document.body.className = document.body.className.replace("modal", "");
function saveEssayScore(key, pid){
var user_id = document.getElementById("user-"+key).value;
console.log("user " + user_id);
var grade = document.getElementById("grade-"+key).value;
console.log("grade " + grade);
var teacher_answer = document.getElementById("feedback-"+key).value;
console.log("teacher_answer " + teacher_answer);
var question_id = document.getElementById("question-"+key).value;
console.log("question_id " + question_id);
var quiz_id = document.getElementById("quiz-"+key).value;
console.log("quiz_id " + quiz_id);
var req = new Request.HTML({
method: 'post',
url: "<?php echo JURI::base();?>index.php?option=com_guru&controller=guruAuthor&task=saveFeedback&tmpl=component&format=raw",
data: { 'pid' : pid, 'user_id' : user_id, 'grade' : grade, 'teacher_answer' : teacher_answer, 'question_id' : question_id, 'quiz_id' : quiz_id},
onSuccess: function(response, responseElements, responseHTML){
alert('yeyy');
}
}).send();
}
Now in the URL, it is read to run the method (task) saveFeedback() in the controller guruAuthor which is in the component com_guru.
The problem I am having is, how do I read the data that I just send through the HTML request? I am trying stuff like $user_id = JRequest::getVar("user_id"); But whenever I'm trying to echo or dump, it is returned to me but empty. Not the values that I am dumping in JavaScript console.log(user_id);
JRequest is deprecated
Use JInput instead. Read - Retrieving request data using JInput
In your mentioned code - if the controller function is being called, try this code-
$jinput = JFactory::getApplication()->input;
$user_id = $jinput->get('user_id', '', 'INT');
I hope this helps.
I am making a LIVE UPDATE in CodeIgniter and it is almost working.
Just one little issue: When I click the button it also appears my navigation inside the "responds" box which is very strange.
And when I refresh the page it is removed and the record is there.
Here is an image to explain what I mean
Here is the JavaScript:
<script type="text/javascript">
$(document).ready(function() {
//##### Add record when Add Record Button is click #########
$("#FormSubmit").click(function (e) {
e.preventDefault();
if($("#contentText").val() ==='')
{
alert("Please enter some text!");
return false;
}
var myData = 'content_txt='+ $("#contentText").val(); //build a post data structure
jQuery.ajax({
type: "POST", // Post / Get method
url: "<?php echo site_url('admin/dashboard/index'); ?>", //Where form data is sent on submission
dataType:"text", // Data type, HTML, json etc.
data:myData, //Form variables
success:function(response) {
$("#responds").append(response);
},
error:function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
});
});
</script>
EDIT:
HERE IS THE CONTROLER
class Dashboard extends CI_Controller
{
public function __construct()
{
parent::__construct();
// Load libraries
$this->load->library('ion_auth');
$this->load->library('parser');
// Load models
$this->load->model('note_model');
// Load helpers
$this->load->helper('date');
// Set error delimiters
$this->form_validation->set_error_delimiters('<div class="alert alert-danger">', '</div>');
}
public function index()
{
// Check if user is loged in
if (!$this->ion_auth->logged_in())
{
redirect('auth/login');
}
else
{
// Create notes object
$notes = new Note_model();
// Order the notes by date post
$notes->order_by('date_post', 'desc')->get();
$recent_notes = array();
foreach ($notes as $note)
{
$single_note = array
(
'id' => $note->id,
'note_text' => $note->note_text,
'date_post' => $note->date_post,
);
array_push($recent_notes, $single_note);
}
// Get the user id as an object
$getinfo = $this->ion_auth->user($this->session->userdata('user_id'))->row();
// Create a new note
$createNote = new Note_model();
$createNote->note_text = $this->input->post('content_txt');
$created = date('Y-m-d H:i:s');
$createNote->date_post = $created;
// Validation rules
$rules = $this->note_model->rules;
$this->form_validation->set_rules($rules);
$data = array
(
'admin_content' => 'admin/dashboard',
'notes' => $recent_notes,
'username' => $getinfo->{'first_name'} . ' ' . $getinfo->{'last_name'},
);
if ($this->form_validation->run() == FALSE)
{
$this->parser->parse('admin/template_admin', $data);
}
else
{
$createNote->save();
redirect('admin/dashboard');
}
}
}
The problem is the action you are calling.
It seems admin/dashboard/index outputs the navigation as well as the data you want to display.
You should post to an action that ONLY displays the data you require, and nothing else
I have some template files in the project for example '/view/dynamic.html' containing these simple data :
<div class="dynamic"></div>
On the client side : I have a clickable element on my web page using Jquery that posts an asynchronous request to the server side.
$('a.clickable').on('click', function()
{
var $this = $(this);
var $type = $this.data('type');
var $project_id = 1;
$.ajax({
type: 'POST',
url: "php/zeek.php",
data: {
'method': 'clicked',
'type': $type,
'project_id': $project_id
},
dataType: 'text',
success: function($input)
{
console.log('result:' + $input);
},
error: function($request, $status, $error)
{
$('div.dynamic').replaceWith(
'<div class="dynamic"><h2>'
+ $error + '</h2></div>');
console.log($status + ' : ' + $error);
}
});
});
On the server side :
I have a function that is displaying the content of the dynamic view file.
public function dynamic_display() {
ob_start();
include 'view/dynamic.html';
return ob_get_clean();
}
and finally I have function that receives the request :
case 'clicked':
$type = strtolower($params['type']);
if ($type == 'disconnect') {
echo("? " . $this->dynamic_display() . " ?");
return true;
}
The problem :
when I test my function 'dynamic_display' with unit test, this function sends back the correct expected string. Using var_dump, I obtain :
string(28) "<div class="dynamic"></div>
"
When I click on the element on my page : I doesn't obtain the same result on the console
"result:? ?"
Why it doesn't work? What is happening? How should make it working?
Thanks & Regards!
Leo
It does work when I use
include '/home/leo/zeek/view/dynamic.html';
instead of
include 'view/dynamic.html';
I am really surprised? Somebody could explained?