I got function that collects and display's all posts, and for each have upvote/downvote buttons.
On button click I call function called upvotePost and downvotePost.
It all works fine, but it refreshes page, I want to understand how to make it not-refresh page.
I know it's done by ajax/jquery, but don't understand how to make it.
My button example:
<a href="fun.php?upvote-btn=true?action=select&image_id=<?php echo $post['id'];?>">
Function calling:
if(isset($_GET['upvote-btn'])){
$fun->upvotePost();
}
And my function:
public function upvotePost(){
try
{
if(isset($_SESSION['user_session'])){
$user_id = $_SESSION['user_session'];
$stmt = $this->runQuery("SELECT * FROM users WHERE id=:id");
$stmt->execute(array(":id"=>$user_id));
$myRow=$stmt->fetch(PDO::FETCH_ASSOC);
}else{
$_SESSION["error"]='Sorry, You have to login in you account!';
}
$id = $_GET['image_id'];
$user_id = $myRow['id'];
$stmt2 = $this->conn->prepare("SELECT count(*) FROM fun_post_upvotes WHERE image_id=('$id') AND user_id=('$user_id')");
$stmt2->execute();
$result2 = $stmt2->fetchColumn();
if($result2 == 0){
$stmt3 = $this->conn->prepare("INSERT INTO fun_post_upvotes (image_id,user_id) VALUES(:image_id,:user_id)");
$stmt3->bindparam(":image_id", $id);
$stmt3->bindparam(":user_id", $user_id);
$stmt3->execute();
$stmt4 = $this->conn->prepare("SELECT * FROM fun_posts WHERE id=('$id')");
$stmt4->execute();
$result4 = $stmt4->fetchAll();
foreach($result4 as $post){
$newUpvotes = $post['upvotes']+1;
$stmt5 = $this->conn->prepare("UPDATE fun_posts SET upvotes=$newUpvotes WHERE id=('$id')");
$stmt5->execute();
$_SESSION["result"]='You have succesfully liked this post!';
}
}else{
$_SESSION["error"]='You have already liked this post!';
}
$stmt6 = $this->conn->prepare("SELECT count(*) FROM fun_post_downvotes WHERE image_id=('$id') AND user_id=('$user_id')");
$stmt6->execute();
$result6 = $stmt6->fetchColumn();
if($result6 > 0){
$stmt7 = $this->conn->prepare("DELETE FROM fun_post_downvotes WHERE image_id=('$id') AND user_id=('$user_id')");
$stmt7->execute();
$stmt8 = $this->conn->prepare("SELECT * FROM fun_posts WHERE id=('$id')");
$stmt8->execute();
$result8 = $stmt8->fetchAll();
foreach($result8 as $post){
$newDownvotes = $post['downvotes'] - 1;
$stmt9 = $this->conn->prepare("UPDATE fun_posts SET downvotes=$newDownvotes WHERE id=('$id')");
$stmt9->execute();
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
Ajax is the perfect answer for your question. Please check out this. you may need to alter this snippet according to your requirement.
before doing this you should import jquery.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
your upvote button should be like this,
<button id="upvote"> upvote </button>
add below snippet in your javascript section.
$(function(){
$("#upvote").click(function(){
$.ajax(
{ url: "fun.php?upvote-btn=true?action=select&image_id=<?php echo $post['id'];?>",
type: "get",
success: function(result){
// todo something you need to perform after ajax call
}
});
});
});
Basically you have to create a php file which will route the call(let's call it a controller) to the intended function. Then create an ajax function which will hit that controller. Have a look at
Ajax Intro
Or look at the Jquery Implementation
Related
I have this button
<button id = "addBtn-1" onclick = "noneAdd();add1()">Add to My Classes</button>
It calls a function called add1() from my js file, which adds and removes classes and also calls add():
function add(){
$.ajax({url:"add.php",
success:function(result){
alert("Added to My Classes");
}
});
}
which calls my php file, add.php:
require_once "config.php";
include "classes.php";
$myun = $_SESSION["un"];
function bookmark1Add(){
$sql = "SELECT testclass1 FROM classes WHERE username = ?";
if($stmt = mysqli_prepare($db, $sql)){
mysqli_stmt_bind_param($stmt, "s", $param_un);
$param_un = $myun;
if(mysqli_stmt_execute($stmt)){
mysqli_stmt_bind_result($stmt, $myclass1);
if(mysqli_stmt_fetch($stmt)){
if($myclass1 == 0){
$sql2 = "UPDATE classes
SET testclass1 = 1";
if($stmt2 = mysqli_prepare($db, $sql2)){
mysqli_stmt_bind_param($stmt2, "s", "param_un");
$param_un = $myun;
if(mysqli_stmt_execute($stmt2)){
header("Refresh:0");
}
else{
echo "Something went wrong, please try again later!";
}
}
mysqli_stmt_close($stmt2);
}
}
}
}
mysqli_stmt_close($stmt);
}
bookmark1Add();
This line of code is supposed to update the data in my table, but it doesn't seem to be working. When I click the button, nothing changes in the database, however the adding and removing of classes from add1() works so it succeeded in calling the function
nvm I made the code much simpler since the one above was way too complicated and rat it on its own to see if there were any bugs.
<?php
require_once "config.php";
include "classes.php";
$myun = $_SESSION["un"];
$sql = "UPDATE classes SET testclass1 = 1 WHERE username = '$myun'";
if (mysqli_query($db, $sql)) {
header: "Refresh:0";
}
?>
this worked way better
I've got a complicated little problem here.
I'm building a WordPress plugin where I select a "parent" post (of a custom type that I made called 'step') and then an AJAX function shows a new select bar with all of the children of that parent. I do this by outputting the new and elements in the PHP file that's called in the AJAX function. This works, but now I want to repeat the process to run a function from the same JQuery file when this new outputted element is added to the page. (See Javascript code)
Main php plugin file (in a folder within the plugin directory):
<?php
/*
Plugin Name: n8jadams Step by Step Plugin (WIP)
Plugin URI:
Description:
Author: Nathan James Adams
Author URI: http://nathanjamesadams.com
Version: 0.0.1a
*/
//Exit if accessed directly
if(!defined('ABSPATH')) {
exit;
}
//My custom post type, it works fine
require_once(plugin_dir_path(__FILE__).'n8jadams-step-funnel-cpt.php');
require_once(plugin_dir_path(__FILE__).'n8jadams-ajax.php');
//Add my javascript
function n8jadams_init_javascript() {
wp_register_script('n8jadams_javascript', plugin_dir_url(__FILE__).'n8jadams-scripts.js', array('jquery'),'1.1', false);
wp_enqueue_script('n8jadams_javascript');
}
add_action('wp_enqueue_scripts', 'n8jadams_init_javascript');
//Adds a plugin menu to the wordpress sidebar
function n8jadams_add_plugin_menu() {
add_menu_page('', 'Steps Settings', 4, 'steps-settings', 'n8jadams_steps_settings', '');
}
add_action('admin_menu', 'n8jadams_add_plugin_menu');
//The actual function for the menu page
function n8jadams_steps_settings() {
//Access the database and the tables we want
global $wpdb;
$posts = $wpdb->prefix.'posts';
//Get the user id
$user = wp_get_current_user();
$userid = $user->ID;
//Initialize javascript (it works here!)
n8jadams_init_javascript();
/* Get all the parents */
$parentsquery = "
SELECT `ID`, `post_title`
FROM $posts
WHERE `post_author` = $userid
AND `post_parent` = 0
AND `post_status` = 'publish'
AND `post_type` = 'step'
";
$parentsarray = $wpdb->get_results($parentsquery);
?>
<h4>My Forms:</h4>
<select id="parentselect">
<option id="-1"> - Select Your Step Form - </option>
<?php
//output the parents
for($i=0;$i<sizeof($parentsarray);$i++) {
echo '<option id="'.$parentsarray[$i]->ID.'">'.$parentsarray[$i]->post_title.'</option>';
}
?>
</select>
<div id="displayChildren"></div>
<?php
}
?>
Javascript (n8jadams-scripts.js):
(function($){
$('#parentselect').change(function(s) {
var thisID = s.target[s.target.selectedIndex].id;
var outputDisplay = document.getElementById('displayChildren');
if(thisID != '-1') {
$.ajax({
type: 'POST',
url: 'admin-ajax.php',
data: {
action: 'n8jadams_get_children',
id: thisID
},
success: function(response){
if(response == "") {
outputDisplay.textContent = "This form has no children. Add them in the sidebar menu of this step form.";
} else {
outputDisplay.innerHTML = response;
}
},
error: function(errorThrown) {
alert(errorThrown);
}
});
} else {
outputDisplay.textContent = '';
}
});
// I want this function to work
/*
$('#childselect').change(function(t) {
console.log("test");
});
*/
})(jQuery);
PHP file called by AJAX (n8jadams-ajax.php):
<?php
function n8jadams_get_children() {
//Get the id of the parent
$parent_post_id = $_POST['id'];
//Sanitize the input (Added after question was answered)
$parent_post_id = preg_replace("/[^0-9]/","",$parent_post_id);
//Access database
global $wpdb;
$posts = $wpdb->prefix.'posts';
$user = wp_get_current_user();
$userid = $user->ID;
$childrenquery = "
SELECT `ID`, `post_title`,`post_content`
FROM $posts
WHERE `post_parent` = $parent_post_id
AND `post_status` = 'publish'
AND `post_type` = 'step'
AND `post_author` = $userid
";
//Retrieve the children associated with this parent
$childrenarray = $wpdb->get_results($childrenquery);
//Initialize Javascript (it doesn't work here!)
n8jadams_init_javascript();
if(!empty($childrenarray)) { ?>
<h4>My Steps:</h4>
<select id="childselect">
<option id="-1"> - Select Your Step - </option>
<?php
//output the children of the parent
for($i=0;$i<sizeof($childrenarray);$i++) {
echo '<option id="'.$childrenarray[$i]->ID.'">'.$childrenarray[$i]->post_title.'</option>';
} ?>
</select>
<?php wp_die();
}
}
add_action('wp_ajax_n8jadams_get_children', 'n8jadams_get_children');
add_action('wp_ajax_nopriv_n8jadams_get_children', 'n8jadams_get_children');
?>
Screenshot of Plugin Menu
I cannot figure out why my javascript file isn't working in the PHP file that's called by AJAX. Maybe the vast wisdom of the StackOverflow can help me. Thanks for the help in advance. :)
You are hooking into wp_enqueue_scripts, which is only run for the frontend of Wordpress (the part the average visitor sees). If you want to load a script into wp-admin, the backend of Wordpress, use the admin_enqueue_scripts action.
Since this code does not work in /wp-admin/, you don't need to use admin_enqueue_scripts. I guess the whole problem would be that you are attaching a handler to $('#childselect'), while no such element exists on the page at that time. Use deferring with $(..).on(..):
$(document).on('change', '#childselect', function(e) {
//Black magic
});
Side note: As already mentioned in the comments, the following part contains an unsanitised variable which will allow an attacker to perform sql injections.
$childrenquery = "
SELECT `ID`, `post_title`,`post_content`
FROM $posts
WHERE `post_parent` = $parent_post_id
AND `post_status` = 'publish'
AND `post_type` = 'step'
AND `post_author` = $userid
";
Use WP_Query if at all possible. If this is only used from the backend of Wordpress, don't use wp_ajax_nopriv_*, because users that are not logged in into your site have no right to use that anyway.
I have a JavaScript confirm box and i have some MySQL insert query code to be executed at some condition. This is how my code look like:
<?php
$id = $_POST['id'];
$name= $_POST['name'];
$query = mysql_query("select * from table where id='$id'");
$count = mysql_num_rows($query );
if($count!=0)
{
?>
<script type="text/javascript">
if (confirm("This seems to be Duplicate. Do you want to continue ?") == true)
{
//Execute/Insert into table as how it is given below
}
else
{
//Dont execute/insert into table but close the window
}
</script>
<?php
}
else
{
$queryinsert = mysql_query("INSERT INTO table(id,name) VALUES('$id','$name')");
}
?>
You can't execute MySQL or PHP command inside javascript, what you can do instead is to make a PHP function that you can call by Ajax. The best way is by using jQuery or by redirecting the page with your PHP function in URL.
<script type="text/javascript">
if (confirm("This seems to be Duplicate. Do you want to continue ?"))
{
$.ajax({
url: 'your_path_to_php_function.php',
type: 'POST', // Or any HTTP method you like
data: {data: 'any_external_data'}
})
.done(function( data ) {
// do_something()
});
}
else
{
window.location = 'your_url?yourspecialtag=true'
}
</script>
You're mixing serverside and clientside scrips. This won't work. You have to use AJAX, which are asynchronous server-client/client-server requests. I recommend jQuery, which is JavaScript which easily handles lot of things, including AJAX.
Run this if user confirms action
$.post("phpscript.php", {action: true})
Php file:
if ($_POST['action'] === TRUE) {
<your code here>
}
I am trying to create vote up in my codeigniter named "like". I use this method, that i just found in http://www.technicalkeeda.com/codeigniter-tutorials/voting-system-using-jquery-ajax-and-php-codeigniter-framework
And update is run successfully on database, But the problem is the result of like in view is not showing and the output is text from localhost "Sorry unable to update". And when i refresh the page, the result of "like" showing up.
This is the Controller:
function voteme(){
$id_vote= $this->input->post('id_vote');
$upOrDown= $this->input->post('upOrDown');
$status ="false";
$updateRecords = 0;
if($upOrDown=='upvote'){
$updateRecords = $this->home_model->updateUpVote($id_vote);
}
if($updateRecords>0){
$status = "true";
}
echo $status;
$data['id_vote'] = $id_vote;
redirect ('home',$data);
}
This is Model:
function updateUpVote($id_vote){
$sql = "UPDATE vote set like = like+1 WHERE id_vote =?";
$this->db->query($sql, array($id_vote));
return $this->db->affected_rows();
}
Here is the view:
<button class="btn btn-success voteme" id="3_upvote"><span id="<?php echo $data['id_vote']?>_upvote_result" ><?php echo $data['like']?></span> <b>Like</b></button>
This is javascript:
<script type="text/javascript">
$(document).ready(function(){
$(".voteme").click(function() {
var id_vote = this.id;
var upOrDown = id_vote.split('_');
$.ajax({
type: "post",
url: "http://localhost/ngelol/home/voteme",
cache: false,
data:'id_vote='+upOrDown[0] + '&upOrDown=' +upOrDown[1],
success: function(response){
try{
if(response=='true'){
var newValue = parseInt($("#"+id_vote+'_result').text()) + 1;
$("#"+id_vote+'_result').html(newValue);
}else{
alert('Sorry Unable to update..');
}
}catch(e) {
alert('Exception while request..');
}
},
error: function(){
alert('Error while request..');
}
});
});
});
How to get this result of like without refreshing page?
Many Thanks....
Update:
I have new problem guys, does anyone know how to redirect page in javascript.. I mean, to use vote we need to login first, then i replace
alert('Sorry Unable to update..');
with
url: "localhost/latihan/login"; but it didn't work... thanks for help before
Problem is in your controller function voteme after echoing status you should not use redirect, if you use redirect then it will return your home page html with true status.
So, you can use is_ajax_request(), if ajax request is true then use exit; otherwise redirect() it like,
function voteme(){
$id_vote= $this->input->post('id_vote');
$upOrDown= $this->input->post('upOrDown');
$status ="false";
$updateRecords = 0;
if($upOrDown=='upvote'){
$updateRecords = $this->home_model->updateUpVote($id_vote);
}
if($updateRecords>0){
$status = "true";
}
echo $status;
// check for ajax request
if(! $this->input->is_ajax_request()){ // if not ajax request
$data['id_vote'] = $id_vote;
redirect ('home',$data);// redirect it
}
exit;
}
Even your referral link is not using redirect()
Try this:
function voteme(){
$id_vote= $this->input->post('id_vote');
$upOrDown= $this->input->post('upOrDown');
$status ="false";
$updateRecords = 0;
if($upOrDown=='upvote'){
$updateRecords = $this->home_model->updateUpVote($id_vote);
}
if($updateRecords>0){
$status = "true";
}
return $status
}
To redirect with javascript, you can use 'window.location.href' :
window.location.href = "localhost/latihan/login";
Alright, so I asked a question yesterday regarding how to save the blog posts that a user makes. I figured out the database side of it, and that works fine. Now, I want to REMOVE a blog post based after clicking an onclick button. Through my hours of digging through the web, I've found calling an jQuery AJAX function is the best way to go about it. I've been tooling around with it, but I can't get this working.
Blog code retrieved from database in blog.php:
$connection = mysql_connect("...", "...", "...") or die(mysql_error());
$database = mysql_select_db("...") or die(mysql_error());
$query = mysql_query("SELECT * FROM template") or die(mysql_error());
$template = mysql_fetch_array($query);
$loop = mysql_query("SELECT * FROM content ORDER BY content_id DESC") or die (mysql_error());
while ($row = mysql_fetch_array($loop))
{
print $template['Title_Open'];
print $row['title'];
print '<button class="deletePost" onClick="deleteRow(' . $row['content_id'] . ')">Remove Post</button>';
print $template['Title_Close'];
print $template['Body_Open'];
print $row['body'];
print $template['Body_Close'];
}
mysqli_close($connection);
This creates the following HTML on home.php:
<div class="blogtitle" class="post3">Title
<button class="deletePost" onClick="deleteRow(3)">Remove Post</button></div>
<div class="blogbody" class="post3">Content</div>
Which should call my remove.js when button is clicked (This is where I start to lose what I'm doing):
$function deleteRow(id){
$.ajax({
url: "remove.php",
type: "POST",
data: {action: id}
});
return false;
};
Calling remove.php (No idea what I'm doing):
$con=mysqli_connect("...","...","...","...");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_POST['action'];
$query = mysql_query("DELETE FROM content WHERE content_id=$id") or die(mysql_error());
My goal here is to REMOVE the row with the ID from the table which would in turn remove the blog post entirely since it won't see the row when it loops through the database table.
Any ideas?
Thanks for your help,
Kyle
couple of issues in your original code: the functions in Jquery shouldn't use a $ sign at the beginning and since you need to pass a single value I would use the query string rather than the POst, and instead of calling the "die" in php I would use the affected rows to return the callback of whether or not the value was deleted. But this is just my approach, there other ways I'm sure.
Here are little improvements in you code:
//HTML
<div class="blogtitle" class="post3">Title
<button class="deletePost" data-item="3" >Remove Post</button></div>
<div class="blogbody" class="post3">Content</div>
//JQUERY
jQuery(document).ready(function($) {
$('button.deletePost').each(function(){
var $this = $(this);
$this.click(function(){
var deleteItem = $this.attr('data-item');
$.ajax({url:'remove.php?action='+deleteItem}).done(function(data){
//colect data from response or custom code when success
});
return false;
});
});
});
//PHP
<?php
$id = $_REQUEST['action'];
$query = mysql_query('DELETE FROM content WHERE content_id="'.$id.'"');
$confirm = mysql_affected_rows() > 0 ? echo 'deleted' : echo 'not found or error';
?>
Hope this sample helps :) happy coding !
i hope this should help you i used this to remove items from my shopping cart project.
$(".deleteitem").each(function(e) {
$(this).click(function(e) {
$.post("library/deletefromcart.php",{pid:$(this).attr('prodid'), ajax:true},function(){
window.location.reload()
})
return false;
});
});