How to use $.ajax in WP custom function? - php

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();
}

Related

WordPress fuel plugin how to call ajax actions

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();
}

Simple ajax call in wordpress for upvoting post

Here's my ajax call:
$("#yes, #no").click(function(){
var upOrDown = $(this).attr('id');
$.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
action: "updateVote",
data: {upOrDown: upOrDown},
dataType: "json",
success: function(data) {
console.log(data.output);
}
});
return false;
});
Here's the function in functions.php
function updateVote() {
echo json_encode(array(
'output' => 'hello!'
));
die();
}
add_action('wp_ajax_updateVote', 'updateVote');
add_action('wp_ajax_nopriv_updateVote', 'updateVote');
Why does this keep returning "0". It should return "hello!"
Thanks.

Select2 remote source on dropdown field

I have a city field, where on inlinedit call it will load ajax data on dropdown list. Please check my code & let me know where am I wrong. I read the select2 documentation
<script type="text/javascript">
jQuery(function($) {
$('#city_id').editable({
type: 'select2',
name: 'otmp_tx_user_details:city_id',
pk:"userdetailid:<?php if($student_info->userdetailid) echo $student_info->userdetailid; else echo "0";?>",
ajax: {
url: "<?php echo site_url()?>students/get_city_by_country",
dataType: 'json',
data: function () {
return;
},
results: function (data) {
return {results: data};
}
},
url: "<?php echo site_url();?>students/inlineedit",
success: function(data) {
}
});
});
</script>
Here is my ajax data from PHP file:
$array = array(
array("id"=>1,text=>"Dhaka"),
array("id"=>2,text=>"Pabna")
);
echo json_encode($array);
Please help me to solve my problem.
Try wrapping your Ajax object inside a select2 object, like so:
jQuery(function($) {
$('#city_id').editable({
type: 'select2',
name: 'otmp_tx_user_details:city_id',
pk:"userdetailid:<?php if($student_info->userdetailid) echo $student_info->userdetailid; else echo "0";?>",
select2: {
ajax: {
url: "<?php echo site_url()?>students/get_city_by_country",
dataType: 'json',
data: function () {
return;
},
results: function (data) {
return {results: data};
}
}
},
url: "<?php echo site_url();?>students/inlineedit",
success: function(data) {
}
});
});

Ajax PHP: Variable from page url

With the following AJAX call I set pagination for a webpage. It works.
In my PHP file already have:
$page= $_POST[page];
AJAX call:
function pg2(page) {
pag.ajax({
type: "POST",
url: "file.php",
data: { page: page },
success: function(ccc) {
pag("#search_results").html(ccc);
}
});
}
I also need to pass id from the URL.
http://website.com/title/?id=2 **//I need to pass id in php file and echo it out.
How can I do that? many thanks.
var id=<?php echo $_GET['id'];?> // like this you can store php variable in javascript varibale
Now call function pg2(page,id) however you want...
function pg2(page, id) {
pag.ajax({
type: "POST",
url: "file.php",
data: { page: page, id: id },
success: function(ccc) {
pag("#search_results").html(ccc);
}
});
}
hope it may help you
If your JS is embedded:
function pg2(page) {
var id = <?php echo intval($_GET['id']); ?>;
pag.ajax({
type: "POST",
url: "file.php",
data: { page: page, id: id },
success: function(ccc) {
pag("#search_results").html(ccc);
}
});
}
If your JS is in an external file (best option):
var id = <?php echo intval($_GET['id']); ?>;
pg2(page, id);
Read id via GET and pass in the function
$id = $_GET['id'];
function pg2(page, id) {
pag.ajax({
type: "POST",
url: "file.php",
data: { page: page, id: id },
success: function(ccc) {
pag("#search_results").html(ccc);
}
});
}

jquery json request failed

I'm trying to make a json call with jquery but noting happened. My code:
javascript:
<script type="text/javascript" charset="utf-8">
$(document).ready(function()
{
$("#TwImport").click(function()
{
$.ajax({
type: "POST",
url: "https://<?php echo $_conf['siteurl']; ?>/files/connect/import/customers.php",
dataType: 'json',
success: function (data)
{
alert(data.percentage);
}
});
});
});
</script>
PHP
$output = array(
'percentage' => "50"
);
echo json_encode($output);
Any suggestions?
The code looks fine to me,
EDITED
Also try removing the protocol and use url: "//<?php echo $_conf['siteurl']; ?>/files/connect/import/customers.php",
$("#TwImport").click(function()
{
$.ajax({
type: "POST",
url: "https://<?php echo $_conf['siteurl']; ?>/files/connect/import/customers.php",
dataType: 'json',
success: function (data)
{
alert(data.percentage);
},
error: function (jqXHR,textStatus,errorThrown)
{
//Check for any error here
}
});
});
if you add and error callback to the ajax call you should get some error printouts to let you know what is going on
$.ajax({
type: "POST",
url: "https://<?php echo $_conf['siteurl']; ?>/files/connect/import/customers.php",
dataType: 'json',
success: function (data)
{
alert(data.percentage);
},
error : function (e1, e2, e3) {
console.log(e1);
console.log(e2);
console.log(e3);
}
});
EDIT:
i just had a thought, if i remember correctly jquery ajax doesnt like using full url's if possible try using a relative path

Categories