WordPress fuel plugin how to call ajax actions - php

I have installed the wordpress fuel plugin. By this I have created a plugin to list the property.
Here I have integrated one ajax call like this
In my view file i use this below code:
$('#collapse3').click(function(e){
e.preventDefault();
$.ajax({
type: "GET",
url:"<?php echo $plugin->dispatchRequest("saleshome/index",array('lat' => $latitude,'lng'=>$longitude)); ?>",
data: { },
success: function(data){
$('#collapse3_res').html(data);
}
});
});
By using this code, it is not working. I don't know how to write this. Please help me. Thanks

Try Ajax code like this:
jQuery( document ).on( 'click', '#collapse3', function() {
var data = { };
$.ajax({
type: "POST",
url:"<?php echo $plugin->dispatchRequest("saleshome/index",array('lat' => $latitude,'lng'=>$longitude)); ?>",
data: data,
cache: false,
success: function(response){
$("#collapse3_res").html(response);
}
});
});

javascript add in wp_footer hook on function.php
jQuery.post(
ajaxurl,
{
'action': 'add_foobar',
'data': 'foobarid'
},
function(response){
alert('The server responded: ' + response);
}
);
bellow wp_ajax hook add on function.php
add_action( 'wp_ajax_add_foobar', 'prefix_ajax_add_foobar' );
function prefix_ajax_add_foobar() {
// Handle request then generate response using WP_Ajax_Response
// Don't forget to stop execution afterward.
wp_die();
}

Related

Learning AJAX with Wordpress and can't figure out how to debug my mistake

I'm new to wordpress and I'm having trouble getting an AJAX call to work in a plugin. Nothing I try to print to console on the frontend shows up while I have an ajax request running and I don't know how to make anything print to anywhere from the wordpress backend.
If possible, I'd appreciate if someone could tell me how to debug my mistake.
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#question-form').submit(function(e) {
e.preventDefault();
console.log(this);
//var formData = new FormData(this);
var formData = {
action: 'create_question',
post_content: jQuery('#question-form #question-content').val()
};
$.ajax({
type: 'post',
dataType: 'json',
url: '<?php echo wp_localize_script(admin_url( "admin-ajax.php" )); ?>',
data: formData,
processData: false,
contentType: false,
success: function(response) {
if(response.type == "success") {
console.log("test");
// Update question display
}
else {
alert("Error");
}
},
error: function(xhr, textStatus, error) {
console.log(xhr.responseText);
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
});
});
</script>
<?php
add_action( 'wp_ajax_create_question', 'create_question_handler' );
add_action( 'wp_ajax_nopriv_create_question', 'create_question_handler' );
function create_question_handler() {
wp_send_json(123);
}
?>
When I delete the ajax, it logs the formdata to console. Otherwise, nothing logs to console except for a navigation to a new blank page. I was under the impression that AJAX is used to avoid loading a new page, so this also confuses me.
I don't know how to confirm whether my hooks are being created or where to look to see if my handler is outputting anything.
I appreciate any help.
your url parameter is using an unnecessary function. it should be:
url: '<?php echo esc_url( admin_url( 'admin-ajax.php') ); ?>',

How to use $.ajax in WP custom function?

I am working with Wordpress and I want to use the jQuery $.ajax() function in my custom function.php file in child theme . I am new in WP so I don't have any ideas how to use jQuery AJAX in WP.
I have no idea what will be the URL of the function from where the JSON data will come. Please help
<div class="rig-textGrid" style="cursor: pointer" data-toggle="modal" data-target="#myModal" onclick="GetDetailsCat('.$cat_id.')">'.$name.'</div>
function GetDetailsCat(cat_id) {
data = "";
url = "";
data = "&cat_id=" + cat_id;
url = "";
$.ajax({
data: data,
type: "get",
url: url,
dataType: "json",
error: function(resp) {
alert("Somthing Went Wrong !!!");
},
success: function(resp) {}
});
}
Like this
You can write GetDetailsCat() in function.php
<?php
function load_script_to_get_data(){
?>
<script>
function GetDetailsCat(cat_id) {
$.ajax({
type: "post",
url: "<?php echo admin_url('admin-ajax.php'); ?>",
dataType: "json",
data : { action: "get_data", cat_id: cat_id }
error: function(resp) {
alert("Somthing Went Wrong !!!");
},
success: function(resp) {
}
});
}
</script>
<?php
}
add_action( 'wp_footer', 'load_script_to_get_data' );
Look for this solution. I think it will sure help you.
for run ajax in Wordpress in ajax URL you need to give admin-ajax URL which is admin_url('admin-ajax.php')
next, you need to post an action in data which belongs to your functions.php's function
function GetDetailsCat(cat_id) {
$.ajax({
type: "post",
url: "<?php echo admin_url('admin-ajax.php'); ?>",
dataType: "json",
data : { action: "get_data", cat_id: cat_id }
error: function(resp) {
alert("Somthing Went Wrong !!!");
},
success: function(resp) {
}
});
}
functions.php
add_action( 'wp_ajax_get_data', 'get_data' );
add_action( 'wp_ajax_nopriv_get_data', 'get_data' );
function get_data() {
$cat_id= esc_attr ($_POST['cat_id ']);
$result = "Your custom code which you want to do run";
echo $result; //return value
die();
}

Call ajax after success

I made an ajax request to get the name of each button I click...
Then I want to put everything in that url into "#Container".(url define a page that has some codes)
It works for me at the first time...but for the other times I have to reload the page to show me the details of each button and it doesn't show me details of other buttons that clicked after first desired button..
$(function () {
$('button').click(function () {
var data= $(this).val();
$.ajax({
url: '/myurl',
type: 'post',
dataType: 'json',
data: {
data: data
},
success: function (data) {
$('#container').html(data);
}
});
});
});
What should I do?
Is there something preventing of running the ajax for next times ?
Try with $(document).on('click', instead of $('button').click like below
$(function () {
$(document).on('click','button',function () {
var data= $(this).val();
alert(data);
$.ajax({
url: '/myurl',
type: 'post',
dataType: 'json',
data: {data: data},
success: function (data) {
$('#container').html(data);}
});
});
});
You will need to re-bind ajax event because of its re-rendering DOM after an ajax request completes. All those elements under #container are not virtual part of DOM and your click event only works for pre-existed elements.
Try this
Wrap ajax event in a separate function
function ajaxEvent(data){
$.ajax({
url: '/myurl',
type: 'post',
dataType: 'json',
data: {data: data},
success: function (data) {
$('#container').html(data);
clickEvent(); //note this function attachment I added below
}
});
}
You can wrap your click event into a function
function clickEvent(){
$('button').off('click');
$('button').on('click',function(){
ajaxEvent($(this).val());
});
}
Now js looks like
<script>
$(function(){
clickEvent();
});
function ajaxEvent(data){
$.ajax({
url: '/myurl',
type: 'post',
dataType: 'json',
data: {data: data},
success: function (data) {
$('#container').html(data);
}
});
}
function clickEvent(){
$('button').off('click');
$('button').on('click',function(){
ajaxEvent($(this).val());
});
}
</script>
Also I see you are passing ajax data as $('button').val() which is not correct. Use a input type text if you want to send a data to server.

jQuery ajax post inside each function, success continue in each

So I have this simple jQuery ajax function, but it's inside each function because it's inside each post on site
$('.post .button').each(function() {
$(this).click(function() {
$.ajax({
url: 'action/update.php',
type: 'POST',
data: {
postID: $(this).closest('.container').find('.postID').val()
},
success: function() {
$(this).css({'color' : 'green'});
}
});
});
});
But after success I want change some css of that element that has been clicked.
Basically I want to post this without need of refreshing the site using basic html post.
Is it even possible? Can you help me out?
you may try this :
$('.post .button').on('click',function() {
var $this = $(this);
$.ajax({
url: 'action/update.php',
type: 'POST',
data: {
postID: $this.closest('.container').find('.postID').val()
},
success: function() {
$this.css({'color' : 'green'});
}
});
});

Multiple jQuery AJAX calls conflicts?

I am trying to create a simple shopping cart using AJAX and PHP.
Everything works as it should BUT 1 thing doesn't work all the time and it seems that it fails to execute. (it works 3 times out of 5).
to explain this issue please take a look at the code bellow:
jQuery(document).ready(function() {
//////////////////////LETS RUN OUR ADD TO CART FEATURE USING AJAX //////////////
$(function(){
$('.form1').on('submit', function(e){
$( "#preloader" ).fadeIn( 850 );
// prevent native form submission here
e.preventDefault();
// now do whatever you want here
$.ajax({
type: $(this).attr('method'),// <-- get method of form
url: $(this).attr('action'),
//url: "cart.php",
data: $(this).serialize(), // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
},
success: function(data){
$( "#preloader" ).fadeOut( 850 );
}
});
});
});
//////////////////////LETS RUN LOAD THE cart-header.php ON PAGE LOAD USING AJAX //////////////
$(document).ready(function () {
function load1() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "cart-header.php",
dataType: "html", //expect html to be returned
success: function (data2) {
$('#headerCart').html($(data2));
//setTimeout(load2, 500);
}
});
}
load1();
});
//////////////////////LETS LOAD THE cart-header.php on form1 submit USING AJAX //////////////
<!----- This is the part that SOMETIMES Fails to work --->
$(function(){
$('.form1').on('submit', function(load2){
// prevent native form submission here
load2.preventDefault();
// now do whatever you want here
$.ajax({
type: "GET",// <-- get method of form
url: "cart-header.php",
//url: "cart.php",
dataType: "html", // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
},
success: function(data){
//$('#test').load('cart.php #total').html();
$('#headerCart').html($(data));
}
});
});
});
//////////////////////LETS RUN OUR DELETE FROM CART FEATURE USING AJAX //////////////
$(document).on('submit', '.delForm', function(dleItem){
// prevent native form submission here
dleItem.preventDefault();
// now do whatever you want here
$.ajax({
type: $(this).attr('method'),// <-- get method of form
url: "cart-header.php",
//url: "cart.php",
data: $(this).serialize(), // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
},
success: function(data){
$('#headerCart').html($(data));
}
});
});
});
//////////////////////LETS GET THE QUANTITY OF CURRENT ITEMS ADDED IN THE CART USING AJAX/////////////
$(document).ready(function () {
function load() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "cart.php",
//url: "cart-header.php",
dataType: "html", //expect html to be returned
success: function (data) {
$('.item_count').html($(data).find('#total').text());
//$('#headerCart').html($(data));
setTimeout(load, 1000);
}
});
}
load();
});
I have commented the code so you can see the parts of the code and what they do.
the issue is this part:
//////////////////////LETS LOAD THE cart-header.php on form1 submit USING AJAX //////////////
<!----- This is the part that SOMETIMES Fails to work --->
$(function(){
$('.form1').on('submit', function(load2){
// prevent native form submission here
load2.preventDefault();
// now do whatever you want here
$.ajax({
type: "GET",// <-- get method of form
url: "cart-header.php",
//url: "cart.php",
dataType: "html", // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
},
success: function(data){
//$('#test').load('cart.php #total').html();
$('#headerCart').html($(data));
}
});
});
});
As I mentioned above, this code works fine but it only works when it wants to as if it has mind of its own!
could someone please advise on this issue?
Thanks in advance.

Categories