I have a problem
There is a rating system on songs (Its not my code i debugging it). but it could not add or update or show me the rating.
here is my code:
Ajax.js
function bindEvents() {
$(cssSelector.rating_succes).css('display','none');
//Set the new rating when the user clicks
$(cssSelector.ratingLevel).click(function() {
var $this = $(this), rating = $this.parent().children().index($this) + 1, index;
var trackname = $(cssSelector.title+':first').text();
var postdata1 = 'action=my_special_ajax_call5&rating='+rating+'&trackname='+trackname;
alert(postdata1);
jQuery.ajax({
type:'POST',
url:ajaxurl,
cache:false,
data: postdata1,
beforeSend:function(){
},
success:function(res){
$(cssSelector.rating_succes).html(res).fadeIn(500).delay(1000).fadeOut(500);
//window.setTimeout(function(){location.reload()},2000);
}
});
$this.prevAll().add($this).addClass(attr(cssSelector.ratingLevelOn)).end().end().nextAll().removeClass(attr(cssSelector.ratingLevelOn));
});
}
Proccess.php
function implement_ajax5(){
global $wpdb;
$table = $wpdb->prefix."songs";
$table1 = $wpdb->prefix."rating";
$song_title = strip_tags($_POST['trackname']);
$rating_value = strip_tags($_POST['rating']);
$songres = $wpdb->get_row("SELECT * FROM $table WHERE `title`='$song_title'") or die(mysql_error());
$song_id = $songres->id;
$total_votes = $songres->total_votes;
$total_votes = $total_votes+1;
$ip = $_SERVER['REMOTE_ADDR'];
$data = array(
'song_id' => $song_id,
'rating_value' => $rating_value,
'user_ip' => $ip
);
$check = $wpdb->get_results("SELECT * FROM $table1 WHERE song_id='$song_id' AND user_ip='$ip'");
if(!$check){
$insert = $wpdb->insert($table1,$data);
$wpdb->update(
$table,
array(
'total_votes' => $total_votes,
),
array( 'ID' => $song_id )
) or die(mysql_error());
echo 'Thank you';
}else{echo 'Already rated';}
die();
}
index.php
add_action('wp_ajax_my_special_ajax_call5', 'implement_ajax5');
add_action('wp_ajax_nopriv_my_special_ajax_call5', 'implement_ajax5');//for users that are not logged in.
I dont understand what happen when i alert it shows me right values but not add or update in database.
ok just try this in your Ajax.js at top of the page
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
And every thing goes perfect
and i think in your process page there is no need to update query. If you want to delete this there is no issue.
i get this a lot........ajaxurl needs to be defined, so i've learned that its just easier to not use ajaxurl and put in "/wp-admin/admin-ajax.php" in the url section.
Also i dont see you using non-conflict jQuery? (use the word jQuery instead of $)
You may also have issues with your postdata string, i may be wrong but what you need is action: '' ,
rating: '',
etc.
A good practice is to var_dump $_POST and exit at the beginning of your function to make sure they are passing over correctly. then in success- console.log(res) or whatever you are calling your return data
function bindEvents() {
jQuery(cssSelector.rating_succes).css('display','none');
//Set the new rating when the user clicks
jQuery(cssSelector.ratingLevel).click(function() {
var $this = jQuery(this), rating = $this.parent().children().index($this) + 1, index;
var trackname = jQuery(cssSelector.title+':first').text();
//alert(postdata1); -> console.log() is better for looking at objects
jQuery.ajax({
type:'POST',
url: "/wp-admin/admin-ajax.php",
cache:false,
data: {
action: 'my_special_ajax_call5',
rating: rating,
trackname: trackname
}
success:function(output){
console.log(output)
jQuery(cssSelector.rating_succes).html(output).fadeIn(500).delay(1000).fadeOut(500);
//window.setTimeout(function(){location.reload()},2000);
}
});
$this.prevAll().add($this).addClass(attr(cssSelector.ratingLevelOn)).end().end().nextAll().removeClass(attr(cssSelector.ratingLevelOn));
});
}
see how you get on with that :)
Related
I need it to fit and I click on a file to increase the number to 1 and saved in the database
I already have the database created and part of the AJAX code ready, in addition to the number YA INCREMENTA, the issue is that I have an update of the page manually instead of only updating the div
Number to update
<span id="'.$rowRE[id_reclamo].'" class="badge badge-primary badge-pill like">'.$rowRE[positivo].'</span>
Function with ajax
$(document).ready(function () {
$('.like').on('click', function () {
var reclamoID = $(this).attr('id');
if (reclamoID) {
$.ajax({
type: 'POST'
, url: 'like.php'
, data: 'reclamo_id=' + reclamoID
, success: function () {}
});
}
else {
alert("error");
}
});
});
php code
$reclamoID=$_POST['reclamo_id'];
$query = $db->query("UPDATE reclamos SET positivo = positivo +1 WHERE id_reclamo = $reclamoID");
//Count total number of rows
$rowCountTabla = $query->num_rows;
I need you NOT to recharge the entire page if not ONLY THE NUMBER
Return the count in the same request you make when you post your data. Something along the lines of:
PHP:
$reclamoID = pg_escape_string($_POST['reclamo_id']);
$results = $db->query("SELECT positivo FROM reclamos WHERE id_reclamo = '".$reclamoID."'");
// Whatever DB wrapper you're using here... this is just a guess.
$count = $results[0]['positivo'];
echo json_encode(array(
'id' => $reclamoID,
'count' => $count
));
Javascript:
$('.like').on('click', function () {
var element = $(this);
var reclamoID = element.attr('id');
if (reclamoID) {
$.post(
'like.php',
{
reclamo_id: reclamoID
},
function (responseData) {
element.text(responseData.count);
},
'json'
);
}
});
ALWAYS sanitize posted data, to prevent injections and other malicious code.
I tried some steps I saw on the internet on how to send forms without refreshing the page using ajax but I cant seem to do it fine. Here is my code inside the form
$(".coupon_thumbsup").on('submit', function(e) {
e.preventDefault();
console.log("click");
var ThumbsUp = $(this).parent().find(".ThumbsUpVal").val();
ThumbsUp = parseInt(ThumbsUp) + 1;
$(this).parent().find(".ThumbsUpVal").val(ThumbsUp);
$(this).find(".green_thumb").css('background', 'url(http://www.accessdoorreviews.com/wp-content/uploads/2017/11/smalllike2.jpg)');
var totalvotess = $(this).parent().parent().find(".numofvotes").text();
totalvotess = parseInt(totalvotess) + 1;
$(this).parent().find(".ThumbsUpVote").val("1");
$(this).parent().parent().find(".numofvotes").text(totalvotess);
var successpercentv = ((ThumbsUp/totalvotess)*100).toFixed(2);
$(this).parent().parent().find(".successpercent").text(successpercentv);
console.log(successpercentv);
var ThumbsDown = $(this).parent().find(".ThumbsDownVal").val();
ThumbsDown = parseInt(ThumbsDown);
var companycouponid = $(this).parent().find(".companycouponid").val();
$.ajax({
type: "POST",
url: "insertcouponthumbs.php",
data: {'ThumbsUp': ThumbsUp, 'companycouponid':companycouponid, 'ThumbsDown':ThumbsDown},
});
});
And this is my php file:
<?php add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
global $wpdb;
$comcoupid = $_POST['companycouponid'];
$resultcoupon = $wpdb->get_results("SELECT * FROM wp_coupon_list WHERE ID = $comcoupid");
foreach ($resultcoupon as $keyy) {
$wpdb->update($wpdb->prefix."coupon_list", array(
'ThumbsDown' => $_POST['ThumbsDown'],
'ThumbsUp' => $_POST['ThumbsUp'],
), array('ID'=>$keyy->ID)
);
}
wp_die();
} ?>
I am trying to update a database entry through jQuery and AJAX.
I am checking that the values i send over is correct - but I am not sure how to check why the database is not updated.
My code is as follows:
$(document).on("click", ".approve", function(){
var classes = $(this).parents('div:eq(0)'); // this gets the parent classes.
i = 0;
var pros = [];
classes.find(".prosncons .pros ul li").each(function(){
pros.push($(this).text());
});
var cons = [];
classes.find(".prosncons .cons ul li").each(function(){
cons.push($(this).text());
});
var notes = classes.find(".notes").text();
var id = classes.find(".id").text();
var data = "method=approve&pros="+pros+"&cons="+cons+"¬es="+notes+"&id="+id;
$.ajax({
type: "POST",
url: "../scripts/upload.php",
data: data,
success: $(this).closest(".approval").remove(),
});
});
PHP::
if($method == "approve"){
$sql = "UPDATE `approval` SET approved = 1 WHERE pros=:pros, cons=:cons, notes=:notes, id=:id";
$statement = $conn->prepare($sql);
$statement->execute(array(':pros' => $pros, ':cons' => $cons, ':notes' => $notes, ':id'=> $id));
}
You are t sending in the right way your data to the php file
Change your ajax request with this:
$.ajax({
type: "POST",
url: "../scripts/upload.php",
data: { method: "approve", pros: pros, cons:cons, note:notes, id:id },
success: $(this).closest(".approval").remove(),
});
To get your variable into the php file you can retireve that with $_POST['var_name']
In your php try this to check method:
if($_POST['method'] == "approve"){
$sql = "UPDATE `approval` SET approved = 1 WHERE pros=:pros, cons=:cons, notes=:notes, id=:id";
$statement = $conn->prepare($sql);
$statement->execute(array(':pros' => $_POST['pros'], ':cons' => $_POST['cons'], ':notes' => $_POST['notes'], ':id'=> $_POST['id']));
}
You can check $conn->error for the last error. This should tell you if you have an error.
I would normally check if there is an error and if there is I would return a status of error so my JS code knows there was a problem, then handle it.
This function, ajax ... every thing is working well.
When I want to reload the $users it return the same $users
Is there any way after loading ajax to reload the $users with new data?
Controller
function list_of_users_by_skills($project_ids){
$project_id = json_decode($project_ids);
/* Generate Users by Skills
* By Isaac
*/
$this->loadModel('Training');
//Get list of users by skills
$users_return = $this->Training->find('all', array('conditions' => array('Training.Project_id' => $project_id)));
//some code here to return the $users :)
asort($users);
$this->set('users', $users);
}
View
var page = 'http://localhost/index.php/shifts/list_of_users_by_skills/[176,196]/';
console.log(page);
$.ajax({
url: page,
success: function(data) {
<?php echo "var user_array = [" . json_encode($users) . "];\n"; ?>
console.log(user_array);
console.log(<?php echo json_encode($users); ?>);
}
});
You have hard-coded your users variable in your javascript:
<?php echo "var user_array = [" . json_encode($users) . "];\n"; ?>
This will only be filled once, on the initial page request.
You need to make sure that the script that you are calling with ajax, returns the actual user list and use that:
Something like:
$.ajax({
url: page,
dataType: "json",
success: function(data) {
var user_array = data;
console.log(user_array);
}
});
And your page script should do something like this at the end:
echo json_encode($users);
you're pushing the same user_array on the succes callback...
You should declare the var before the function and overwrite the var ín the function{
var page = 'http://localhost/index.php/shifts/list_of_users_by_skills/[176,196]/';
var users = [<?php echo json_encode($users); // or make in an array so json_encode is sufficient ?>];
$.ajax({
url: page,
success: function(data) {
users = data.users;
}
});
where you're gateway (the PHP side of things) would return an array (or object) with a key 'users' => array(user1, user2 etc etc);
When I click on share on a users link..It shares that post fine, yet it posts it twice. I've checked firebug and when clicked (Once) it shows up two POST requests, inserts two posts to the database and then shows them in the users feed.
I really don't understand where I'm going wrong.
SHARE LINK
echo'<a class="sharelink" title="Share '.$poster_name['fullusersname'].'s status" href="#"
data-streamitem_creator='.$streamitem_data['streamitem_creator'].'
data-streamitem_target='.$_SESSION['id'].'
data-streamitem_content='.$streamitem_data['streamitem_content'].'
data-streamitem_type_id=4>Share</a>';
AJAX
$(document).ready(function() {
$('.sharelink').click(function(e) {
e.preventDefault();
var streamitem_creator = $(this).data('streamitem_creator');
var streamitem_target = $(this).data('streamitem_target');
var streamitem_content = $(this).data('streamitem_content');
var streamitem_type_id = $(this).data('streamitem_type_id');
$.ajax({
type: "POST",
url: "../include/share.php",
data: {
streamitem_creator: streamitem_creator,
streamitem_target: streamitem_target,
streamitem_content: streamitem_content,
streamitem_type_id: streamitem_type_id
},
success: function(data) {
$(".usermsg").html(data);
}
});
});
});
SHARE.php
<?
session_start();
require"load.php";
if(isset($_POST['streamitem_type_id'])&isset($_POST['streamitem_creator'])&isset($_POST['streamitem_content'])&isset($_POST['streamitem_target'])){
user_core::create_streamitem(4,$_SESSION['id'],$_POST['streamitem_content'],1,$_POST['streamitem_creator']);
}
?>
LOAD.PHP
public function create_streamitem($typeid,$creatorid,$content,$ispublic,$targetuser){
global $mysqli;
$content = $content;
// $content = strip_tags($content);
if(strlen($content)>0){
$insert = "INSERT INTO streamdata(streamitem_type_id,streamitem_creator,streamitem_target,streamitem_timestamp,streamitem_content,streamitem_public) VALUES ($typeid,$creatorid,$targetuser,UTC_TIMESTAMP(),'$content',$ispublic)";
$add_post = mysqli_query($mysqli,$insert) or die(mysqli_error($mysqli));
$last_id = mysqli_insert_id($mysqli);
if(!($creatorid==$targetuser)){
$fromuser= rawfeeds_user_core::getuser($creatorid);
$_SESSION['id']==$content;
}
return;
}else{
return false;
}
I can't see any problem.. By any chance, don't you have that $('.sharelink').click handler registered twice within your page?