I am using ajax to load data when clicking a link in WordPress.
The request returns the response 2 times in one click.
The Code:
add_action( 'wp_ajax_pt_add_to_compare', 'pt_add_to_compare_callback' );
add_action( 'wp_ajax_nopriv_pt_add_to_compare', 'pt_add_to_compare_callback' );
function pt_add_to_compare_callback() {
$response = do_shortcode('[aps_product_specs id="'.$_POST['id'].'"]');
echo $response;
exit;
}
and the Ajax Part is
$(document).on('click', '.aps-comp-results li a', function (e) {
e.preventDefault();
var link = $(this).attr('href');
var id = getQueryVariable(link, "id");
$.post({
url: ptobject.ajaxurl,
data: {
id: id,
action: 'pt_add_to_compare',
},
success: function (response) {
$('.comparison-row').append('<div class="col-md-4">' + response + '</div>');
}
});
});
So Why this code returns the response twice?
Related
So, i have a following ajax code and controller code, my problem is i want to insert comment withouth refreshing the page and not redirecting to another page, and it seems that whenever i hit btnCommentSubmit it is redirecting me to my controller page, how to prevent that?
Ps. The insertion is working
//AJAX CODE
$('#btnComment').click(function(e){
var comment_identifier = $(this).data("value");
var comment_by = $(this).data("id");
$('#formAddComment').attr('action', '<?php echo base_url() ?>Discussion/addComment/'+comment_identifier+"/"+comment_by);
});
$('#btnCommentSubmit').click(function(){
var url = $('#formAddComment').attr('action');
var addCommentTxt = $('#addCommentTxt').val();
$.ajax({
type: 'post',
url: url,
data: {addCommentTxt:addCommentTxt},
success: function(){
alert('success');
},
error: function(){
console.log(data);
alert('Could not add data');
}
});
});
});
//Controller code
public function addComment(){
$cIden = $this->uri->segment(3);
$cBy = $this->uri->segment(4);
$data = array(
"comment_identifier" => $cIden,
"comment_by" => preg_replace('/[^a-zA-Z-]/', ' ', $cBy),
"comment" => $this->input->post('addCommentTxt'),
"comment_at" => time()
);
if ($this->Crud_model->insert('comments',$data)) {
return true;
}else{
return false;
}
}
Add e.preventDefault() in the beginning of your function:
$('#btnCommentSubmit').click(function(e){
e.preventDefault();
...
}
You may want to use jQuery form plugin. It submit form to our controller without any page refresh/redirect. I use it all the time.
https://jquery-form.github.io/form/
Example usage:
$('#form').ajaxForm({
beforeSubmit: function() {
//just optional confirmation
if (!confirm('Are you sure want to submit this comment?')) return false;
show_loading();
},
success: function(status) {
hide_loading();
if (status == true) {
alert('success');
} else {
alert('Could not add data');
}
}
});
You can use javascript:void(0); like href="javascript:void(0);"
I am trying to send my values using ajax from original page to the page one and then to page 2 this is my code but it seems to be not working.
This is the code on the original page here I have only given the script as I am just using the click event of my div to send the values
<script>
function displayRecords(numRecords, pageNum,x,catg) {
$.ajax({
type: "GET",
url: "button.php",
data: {
show:numRecords,
pagenum:pageNum,
val12:x,
catg12:catg,
},
cache: false,
success: function(data) {
$("#tabs1-html").html(data);
}
});
}
function changeDisplayRowCount(numRecords) {
displayRecords(numRecords, 1);
}
$(document).ready(function() {
$('.tab12').click(function(){
var catg=$('#cat').val();
var x =$(this).val();
displayRecords(5,1,x,catg);
});
});
</script>
now for the code on my page 1
here
<script type="text/javascript">
function get_data(no,x,catg) {
$.ajax({
type:'post',
url:'question_call.php',
data:{
row_no:no,
X:x,
category:catg,
},
success:function(response) {
document.getElementById("pagination_div").innerHTML=response;
}
});
}
$(document).ready(function() {
$('#tota_page_div').click(function(){
var catg = $category.val();
var x = $X.val();
get_data(no,x,catg);
});
});
</script>
and these are the values where i saved the previous ones
$X = $_GET['val12'];
$category = $_GET['catg12'];
Now when I try to use print_r on my page 2 it only shows row_no not catg12 and val12
Hi so I have a JS file with a function for my button, this button get value from different checkbox in a table. But now i want to get these value on another page (for invoice treatement).
Here is my Script :
$("#boutonfacturer").click(function () {
var checked = $('input[name="id_commande[]"]:checked');
var tab = [];
var jsonobj = {};
checked.each(function () {
var value = $(this).val();
jsonobj.value = value;
tab.push(jsonobj);
});
var data= { recup : tab };
console.log(data);
$.ajax({
type: 'POST',
url: 'genererfacture-facture_groupee.html',
data: data,
success: function (msg) {
if (msg.error === 'OK') {
console.log('SUCCESS');
}
else {
console.log('ERROR' + msg.error);
}
}
}).done(function(msg) {
console.log( "Data Saved: " + msg );
});
});
i use an MVC architecture so there is my controller :
public function facture_groupee() {
$_POST['recup'];
var_dump($_POST['recup']);
console.log(recup);
$this->getBody()->setTitre("Facture de votre commande");
$this->getBody()->setContenu(Container::loader());
$this->getBody()->setContenu(GenererFacture::facture_groupee());
and for now my view is useless to show.
I have probably make mistake in my code.
Thank you.
Nevermind after thinking, I have used my ajax.php page which get my another page thanks to a window.location :
my JS :
$("#boutonfacturer").click(function () {
var checked = $('input[name="id_commande[]"]:checked');
var tab = [];
checked.each(function () {
var value = $(this).val();
tab.push(value);
});
var data = {recup: tab};
console.log(data);
$.ajax({
type: 'POST',
url: 'ajax.php?action=facture_groupee',
data: data,
success: function (idfac) {
console.log("Data Saved: " + idfac);
var id_fac = idfac;
window.location = "ajax.php?action=facture_groupee=" + id_fac;
}
});
});
my php :
public function facture_groupee() {
foreach ($_POST['recup'] as $p){
echo $p; }
I am trying to write a code for getting products on Scroll
Steps i following like
1 ] search product
2 ] Getting result on one div
3 ] And on the scrolling of result div want next product
but what happening on every search hit and scrolling product
Calling many ajax request at a time
what i want only once that ajax should call( and not old ajax request )
my jQuery code is
jQuery("#product_search_filter").submit(function () {
jQuery(".load_more_result").remove();
jQuery.ajax({
url: ajaxurl,
type: "post",
data: jQuery(this).serialize(),
dataType: "json",
success: function (products) {
var load_more = 0;
jQuery(".right_bar_sub_inner").html("");
jQuery.each(products, function (i, data) {
if (this.image) {
jQuery(".right_bar_sub_inner").append('<div class="product_show" alt="' + i + '"> <img class="right_bar_img size-auto" src="' + this.image + '" title="'+ this.title +'"> </div>');
}
});
jQuery(".right_bar_sub_inner").append("<div class='load_more_result'>Load More...</div>");
var start = false;
jQuery(".right_bar_sub").scroll( function(){
var _data = jQuery("#product_search_filter").serialize();
_data += "&offset=" + load_more;
jQuery(".load_more_result").css('opacity','0.1');
jQuery.ajax({
url: ajaxurl,
type: "post",
data: _data,
dataType: "json",
success: function (products) {
jQuery.each(products, function (i, data) {
if (this.image) {
jQuery(".load_more_result").before('<div class="product_show" alt="' + i + '"> <img class="right_bar_img size-auto" src="' + this.image + '" title="'+ this.title +'"> </div>');
}
});
jQuery(".load_more_result").css('opacity','1');
start = false;
}
});
return false;
});
}
});
return false;
});
You can see that problem at
Lamp-database
try to search again then see on console of firebug
you can see first time only one request is calling on scroll
if you search again then two request is calling
and
So on...
What you probably want is to not make an ajax request on each scroll event, but instead make the ajax request when the user has stopped scrolling for some time. For that to happen, you can restart a timer on each scroll event, which after reaching a particular value (250ms in the example) will trigger the actual ajax request.
e.g. you could
on each scroll call scrolled()
var timeoutid;
jQuery(".right_bar_sub").scroll( function() {
scrolled();
//...
});
function scrolled() { //delay the request.
clearTimeout(timeoutid); //otherwise it will be called multiple times
timeoutid=window.setTimeout("ajaxcall()", 250); //make ajax request in 250 ms
}
function ajaxcall() {
//make your ajax request here
}
For some reason ajax is not sending data.
On the PHP I have this code:
if (isset($_POST['submit'])) {
echo "submit";
} else {
echo "not submit";
}
And I get not submit.
This is JS code:
$(function () {
$('#submit').click(function () {
var length = $('#number').val();
var small = $('#small').val();
var big = $('#big').val();
var number = $('#numero').val();
var special = $('#special').val();
var submit = 'submit';
var url = 'public/php/codegenerator.php';
var data = "length=" + length + "&small=" + small + "&big=" + big +
"&number=" + number + "&special=" + special + "&submit=" + submit;
$.ajax({
type: "POST",
url: url,
data: data,
success: function () {
$('#code').load(url, function () {
$(this).fadeIn(1000)
});
}
});
return false;
});
});
You can try this approach
$(function(){
$('#submit').click(function(){
//YOUR CODE
var param = {
length:length,
small:small,
big:big,
number:number,
special:special,
submit:submit
}
$.ajax({
type: "POST",
url: url,
data: param,
//EDITED LINE
success: function (data) {
$('#code').hide().html(data).fadeIn(1000);
}
});
return false;
});
});
// REVISED ANSWER
// IN YOUR PHP FILE
if (isset ($_POST['submit'])) {
echo json_encode(array('result'=>"submit"));
}
else {
echo json_encode(array('result'=>"not submit"));
}
//IN YOUR JQUERY CODE
$.ajax({
type: "post",
url: url,
data: param,
dataType:'json';
//EDITED LINE
success: function (data) {
// alert(data.result);
$('#code').hide().html(data.result).fadeIn(1000);
}
});
You are getting Not submit, because it comes from the .load() call and not from .ajax - and in the load call you just load the URL without passing any POST data. So why you are running .load inside the success callback of .ajax with the same url?