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.
Related
I update vote count on the content of a post, but I also have a widget that has counts of votes on each post. When the user clicks on the vote on a post, the vote counts
in each post of the widget does not get updated.
I wrote an AJAX function that calls function through actions like so
// AJAX function file ajax-vote-on-post.js
function voteOnPost(postId) {
jQuery.ajax({
type: 'POST',
url: voteonpostajax.ajaxurl,
data: {
action: 'addvote-to-post',
postid: postId
},
success: function(data, textStatus, XMLHttpRequest) {
var votecontainerid = '#vote-count-' + postId;
jQuery(votecontainerid).html('');
jQuery(votecontainerid).append(data);
},
error: function(MLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
I properly registered the ajax file to be called by WP in a Widget file that contains other functions and PHP codes.
...
// function in the PHP file that is called.
function addvote-to-post(){
$result = '';
// get vote count from DB
$post_ID = $_POST['postid'];
$votepostcount = get_post_meta($post_ID, '_votepostcount', true) != '' ? get_post_meta($post_ID, '_votepostcount', true) : '0';
// Code that updates the DB in WordPress does other things
...
// Output count on the DOM
$votecountnew = $votepostcount + 1;
$result = '<div class="vote-count-'.$post_ID.'" >'.$votepostcountNew.'</div>'
// update_all_count_for_post($post_ID, $votecountnew);
die($result);
}
The page load slowly and how best to update the DOM without using an extra function.
class MyVotePostWidget extends WP_Widget {
// Widget Front End
public function widget {
// HTML code to display posts with votes
}
}
I have a button that when you click it, it will show a confirmation box. If the user clicks 'ok', the word 'reached' would display inside of the div named 'EventData'.
So far the confirmation box shows when I click the button but 'EventData' won't show the word 'reached' when I confirm it.
*the 'event_id' has a value
I think the problem is with the url part where it won't go in the function
Route:
Route::post('/ArchiveEventPosts','AdminController#ArchiveEventposts')->name('ArchiveEventposts');
Script:
$(document).on('click', '.archive', function() {
var event_id = $(this).attr('event_id');
var x = confirm("Are you sure you want to archive this record?");
if (x) {
$.ajax({
method: "POST",
url: '{{ route("ArchiveEventposts") }}',
data: {
event_id: event_id
},
success: function(data) {
$('#EventData').html(data);
alert('Record Archived');
}
});
}
});
Function in the controller:
public function ArchiveEventposts(Request $request)
{
echo 'Reached';
}
You might need to change the way your route is assigned. What you are doing is assigning a plain string to the URL with a single quotation mark. Try like this:
var archiveEventpostsRoute = "{{ route('ArchiveEventposts') }}";
and below
url: archiveEventpostsRoute,
Also, make sure that your controller is returning the proper data, as stated in the other answer:
public function ArchiveEventposts(Request $request)
{
return response()->json(["message" => "Reached"]);
}
Your controller method is not returning any data; it's simply printing the word "Reached".
You'll need to change the function to something like this:
public function ArchiveEventposts(Request $request)
{
return response()->json(["message" => "Reached"]);
}
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
}
});
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 need to get last insert id from controller to ajax success function......
I want to customize product and when user press add to cart ajax is executed and design is going to insert on database....
And after inserting in database i m getting last insert id.....on insert...
but need last insert id....when user press on add to cart button in hidden field...
here is my Ajax code.
$('#store').click(function(){
$.ajax({
type: "POST",
url: ajax_url_store,
data: {action: 'store', views: JSON.stringify(thsirtDesigner.getProduct()) },
success: function(data) {
if(parseInt(data) > 0) {
//successfully added..here i am getting last insert id...
// and i want to pass that in hidden variable.....
// on view page.....
}
else {
document.getElementById('succes-message').innerHTML = 'You Design has not Been Saved';
}
},
error: function() {
//alert('some error has occured...');
},
start: function() {
//alert('ajax has been started...');
}
});
});
my CI controller
public function saveData(){
if($this->input->post('action') == 'store') {
$views = $this->input->post('views');
$id = $this->product_model->save($views);
$data = array('cust_id'=>$id);
$this->session->set_userdata($data);
if($id !=''){
header('Content-Type: application/json');
echo json_encode($id);
}
}
}
$this->db->insert_id() returns the last id.
After your insertion operation in model, use following code
$this->db->insert_id();
this will give you id where last insert done.
Documentation