Wordpress sending multiple AJAX requests on one click - php

My ajax function for saving post is making multiple requests, and i can't understand why. I tried searching for the duplicate elements, that may cause double clicking, but there is no duplicates. And sometimes it posts on ONE click 4 times
Here is the screenshot of multiple ajax post, when i click on #order_save button,
My #order_save button, when i search for the order_save in the DOM tree, the first match is this element. (original click element)
And the second match(2 of 2) for the order_save is at jquery code (which is normal)
jQuery(function($) {
$(document).on('click','#order_save',function(){
var order_title = $('#client-order-title').val();
var order_comment = $('#client-comment').val();
var order_date = $('#order_date_till').val();
var price_input = $('#order_price').val();
var order_price;
var order_attachments = [];
if($('#order_price_on_deal:checked').val() == 'foo') {
order_price = 'foo';
}else{
order_price = price_input;
}
if(!order_title) {
$('#client-order-title').addClass('has-error');
return false;
}else{
$('#client-order-title').removeClass('has-error');
}
if(!order_comment) {
$('#client-comment').addClass('has-error');
return false;
}else{
$('#client-comment').removeClass('has-error');
}
$('#files_public .order-attachment').each(function() {
var attachment_link = $(this).find('a').attr('href');
var attachment_title = $(this).text();
order_attachments.push({
'file_url' : attachment_link,
'file_name' : attachment_title
});
});
$.ajax({ // Line 68 is here
url: my_ajax.url,
type: "POST",
data: {
'action' : 'xx_order_saving',
'order_title' : order_title,
'order_comment' : order_comment,
'order_date' : order_date,
'order_price' : order_price,
'order_attachment' : order_attachments,
'order_type' : 'public_order'
},
dataType: "json",
success: function(response){
if(response.html) {
$('#currentOrder').html(response.html);
}
}
})
});
});
PHP handler in my functions php (working fine)
function xx_order_saving() {
// posting data here
if($order_title && $order_comment) {
$new_post_a = array(
'post_type' => 'orders',
'post_title' => $order_title,
'post_status' => 'publish'
);
$new_order = wp_insert_post($new_post_a);
if($new_order) {
wp_update_post( array( 'ID' => $new_order, 'post_name' => $new_order ) );
}
$template_file = 'xxx-order-saved.php';
ob_start();
include(locate_template($template_file,false,false));
$page_template = ob_get_contents();
ob_end_clean();
$response['html'] = $page_template;
wp_send_json($response);
}
}
add_action('wp_ajax_xx_order_saving','xx_order_saving');
add_action('wp_ajax_nopriv_xx_order_saving','xx_order_saving');
The template file with the jquery code above is loaded dynamically using this function
function load_frame() {
$option = $_POST['option'];
if($option){
$template_file = 'xxxx-'.$option.'.php';
ob_start();
include(locate_template($template_file,false,false));
$page_template = ob_get_contents();
ob_end_clean();
$response['html'] = $page_template;
wp_send_json($response);
}
}
Sometimes it works just fine, sending one request, saving one post, sometimes it posts 4 or 2 times as shown in the screenshot above.
Here is what seems to cause the problem:
If there is order-attachments, for example one attachment it will send two requests (save two posts) if there is two attachments it will send One request, if there is three attachments it will send 4 requests, if there is 5 it sending One again. I just don't get it. Any help will be appreciated
<div id="files_public" class="form-group">
<span class="list-group-item order-attachment">Image.png
...</span>
</div>

Change
$(document).on("click", "#order_save", function () {
to
$("#order_save").click(function () {

Related

increase number with ajax php and mysql

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.

Ajax div to refresh on success not working

I have a DIV which contains how many likes fetching from Mysql database.
I click on button which says like and it will go through ajax function like(id1) with parameter.
Ajax use page likes.php and does all job adding to database. And it gives out JSON data as feedback with code zero if successful. And one if fails.
In success section ajax _js.code is one then its already liked. Thus shows us message. But my problem is I cannot refresh DIV likes when code is zero which is success. It either goes to top of the page instead of staying at DIV likes.
For information it also appends hash TAG at the end of URL.
Button line, I want like button which should work as facebook or other major app does. Without moving page on top. And update like button immediately when clicked.
My main page
<input type="checkbox" id="like" onclick="like(<?php echo $_SESSION["id"];?>);"/>
<div id="likes">
<?php
$like = 0;
$conditions = "WHERE id = $_SESSION[id]";
echo $total = $ll->get_likes($conditions); //displaying how many likes
?>
</div>
Ajax
<script>
function like(id1) {
$.ajax ({
type: "POST",
url: "likes.php",
data: {id: id1 },
success: function(feedback) {
var _js = jQuery.parseJSON(feedback);
$("#likes").html(_js.message); //printing message here
$("#likes").attr("class", ""); //resetting class of CSS
if( _js.code == 0) {
/**I want to refresh DIV likes after this **/
} else {
$("#likes").addClass("red"); //This is working fine, i get message when already liked
}
}
});
}
likes.php
<?php
if ( isset($_POST)) {
//All PHP staff goes here and its working
if ( $success) {
$return = array (
'code' = 0,
'message' = ""
);
} else {
$return["code"] = 1;
$return["message"] = "You already liked";
}
echo json_encode($return);//Converting PHP into JSON format
}
?>
change following in HTML and JS
<input type="checkbox" id="like" onclick="return like(<?php echo $_SESSION["id"];?>);"/>
<script>
function like(id1) {
$.ajax ({
type: "POST",
url: "likes.php",
data: {id: id1 },
success: function(feedback) {
var _js = jQuery.parseJSON(feedback);
$("#likes").html(_js.message); //printing message here
$("#likes").attr("class", ""); //resetting class of CSS
if( _js.code == 0) {
/**I want to refresh DIV likes after this **/
} else {
$("#likes").addClass("red"); //This is working fine, i get message when already liked
}
}
});
return false;
}
#tashi,
There is a syntax error in likes.php. Use => operator when declaring arrays. The code should be as follows.
$return = array (
'code' => 0,
'message' => ""
);
if you want to display no of likes on success the change your code as follows
In likes.php
<?php
if ( isset($_POST)) {
//All PHP staff goes here and its working
if ( $success) {
$return = array (
'code' => 0,
'message' => "",
'likes_count' => $likes_count //get updated likes count from db
);
} else {
$return["code"] = 1;
$return["message"] = "You already liked";
//here you do not need to send the like count
}
echo json_encode($return);//Converting PHP into JSON format
}
?>
javascript code
function like(id1) {
$.ajax ({
type: "POST",
url: "likes.php",
data: {id: id1 },
success: function(feedback) {
var _js = jQuery.parseJSON(feedback);
$("#likes").html(_js.message); //printing message here
$("#likes").attr("class", ""); //resetting class of CSS
if( _js.code == 0) {
/**I want to refresh DIV likes after this **/
$('#likes').html(_js.likes_count);//this will update your likes count
} else {
$("#likes").addClass("red"); //This is working fine, i get message when already liked
}
}
});
}

AJAX getting posts from wpquery, prevent post duplication

I'm trying to AJAX loading posts in my blog, I've successfully get it to work this way:
the page displays 3 posts on page load, then the visitor can get 3 more posts each time he clicks the button "LOAD MORE".
Now I want to load 9 posts on page load but keep 3 posts with each click on "LOAD MORE" button.
A problem occurs with the page number value in the WPQuery, it's getting the same 3 posts which were already displayed.
how can I prevent posts duplication?
Please check it here at my temp website
[note that I have less than 9 posts at the category page, it should load all of them]
(function($) {
$(document).ready(function(){
var $content = $('#list-content');
var $btnLoad = $('#btnLoad');
var loading = true;
var page = 1;
var load_posts = function($count){
var post_id = $(this).attr( 'id' );
/** Ajax Call */
$.ajax({
cache : false,
timeout : 8000,
url : php_array.admin_ajax,
type : "POST",
data : {action:'main_query', numPosts : $count, pageNumber: page, condition: php_array.condition, val: php_array.val},
beforeSend : function() {
$('#loadimg').slideToggle("fast");
$btnLoad.prop("disabled",true);
},
success : function(data, textStatus, jqXHR ){
var $data = $( data );
if($data.length){
$content.append( $data );
$btnLoad.prop("disabled",false);
}
else{
$btnLoad.html("That's it");
$btnLoad.prop("disabled",true);
}
},
error : function( jqXHR, textStatus, errorThrown ){
if(t==="timeout") {
alert("Server is too slow, try again later");
} else {
alert(t);
}
console.log( 'ajaxLoop.js: The following error occured: ' + textStatus, errorThrown );
},
complete : function( jqXHR, textStatus ){
$('#loadimg').slideToggle("fast");
loading = false;
page++;
}
});
}
$btnLoad.on("click", function(e) {
e.preventDefault();
loading = true;
load_posts(3);
});
load_posts(9); //load the first elements
});
})(jQuery);
PHP code:
function main_query_init() {
/** Made Query */
$numPosts = (isset($_POST['numPosts'])) ? $_POST['numPosts'] : 0;
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
$condition = (isset($_POST['condition'])) ? $_POST['condition'] : '';
$val = (isset($_POST['val'])) ? $_POST['val'] : '';
$args = array(
'posts_per_page'=> $numPosts,
'paged' => $page,
);
if($condition != ''){
$args[$condition] = $val;
}
$post_query = new WP_Query( $args );
if ($post_query->have_posts()) : while ($post_query->have_posts()) : $post_query->the_post();
You are probably looking for the offset parameter for WP_Query. Setting it to 3 will cause it to skip the first 3 results when using posts_per_page and paged.
The other option is to specify the post_ids that you don't want explicitly using the post__not_in parameter, but this will require passing the array of values to exclude with each request - you might be able to get away with just passing in the first 3 IDs, but I would go with offset.
The key is var currCount = $data.filter('article').length;
where I store the current count of posts from ajax response.
Since I ask for extra 3 posts every load button click, then if((currCount % 3) == 0) will tell me if it got 3 posts otherwise there are no more posts and there is no need to increment page counter.
success : function(data, textStatus, jqXHR ){
var $data = $( data );
var currCount = $data.filter('article').length;
totalCount += currCount;
if(currCount > 0){
$content.append( $data );
$btnLoad.prop("disabled",false);
if((currCount % 3) == 0)
page += currCount / 3;
else
page += (parseInt(totalCount/3) + 1);
return;
}
$btnLoad.html("That's it");
$btnLoad.prop("disabled",true);
},

Rating not add with ajax in wordpress

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 :)

how could i retrieve profile data in a modal using ajax in php?

here's the deal, i've created a search results page and i'd like to open a modal and retrieve profile data via ajax in php but i'm not too sure on how i can implement it. I've created the modal but but i don't know how i would go about getting the 'id' from clicking the search result, passing it onto ajax to retrieve the profile details.
Twitter has this kinda feature; when you click a username in a feed and it opens a modal and gives you a brief overview of the profile with a link to the full profile.
It would mean so much to me if someone could help me out or point me in the right direction! :)
P.S. I'm using codeigniter, if anyone is wondering what framework i'm using.
EDIT: here's the code
<?php
/*** PHP Search Results Loop ***/
if ($num > 0){
foreach ($query->result_array() as $row)
{
echo "link to ajax"'>";
}
} else {
echo "<strong>results not found :(</strong>";
}?>
<script> /* jQuery Runs When Result Has Been Clicked */
$('#ResultText').click(function() {
var targetid = {
id: /*Profile Id*/,
ajax: '1'
};
/* Modal Code */
$('.modal-backdrop, .modal-profilebox').css('display', 'block');
$('.modal-backdrop').animate({'opacity':'.50'}, 100, 'linear');
$('.modal-profilebox').animate({'opacity':'1.00'}, 200, 'linear');
$.ajax({
url: "<?php echo site_url('finder/modal'); ?>",
type: 'POST',
data: form_data,
success: function(profileData) {
$('.modal-profilebox').html(profileData);
}
});
return false;
});
</script>
Try something like this
public function ajax_user_profile($user_id)
{
if( !$this->input->is_ajax_request() )
{
redirect('/'); //only allow ajax requests
}
try
{
$user_profile = ''; //grab user object from DB
if( !$user_profile )
throw new Exception("Error Message");
}
catch(Exception $e)
{
log_message('error', $e->getMessage());
echo json_encode(array(
'error' => 1
));
exit;
}
$data = $this->load->view(array(
'some_view' => 'some_view',
'user' => $user_profile
), TRUE); //NO Template, just the view by adding TRUE
echo json_encode(array(
'error' => 0,
'data' => $data
)); //return view data
}
--
<a rel="modal" data-user-id="1" >Joe Bloggs</a>
--
(function($){
var userObj = {
init : function(){
this.getProfile();
},
getProfile : function(){
var modalSearch = $("a[rel='modal']");
modalSearch.on('click', function(){
//trigger the modal window
//request ajax
$.ajax({
url : BASEPATH + 'users/profile/' + $(this).data('user-id'),
type : 'POST',
dataType: 'json',
success : function(callback){
if(callback.error ==0)
{
$('.modal-profilebox').html(callback.data);
}
}
});
});
}
}
$(function(){
userObj.init()
});
})(jQuery);

Categories