I have a button with data :
data-boutique-id="<?php echo esc_attr(get_the_ID());
In my main.js i have 2 jQuery functions using those 2 variables :
$fav = $('.fav-btn'),
boutiqueId = $fav.data('boutique-id');
My on('click') function is working fine, it does return the data-boutique-id. Bu my ready() function is not working and the variable boutiqueId is returning [object Object] instead of the Id. There must be something i don't know.
var $fav = $('.fav-btn'),
boutiqueId = $fav.data('boutique-id');
$fav.ready(function(theBoutique) {
$.ajax({
type: 'GET',
data: {
action: 'check-fav',
boutiqueId: theBoutique
},
url: '/wp-json/fav_ajax/v1/manage_fav/'
}).done(function(_data) {
console.log(_data);
});
});
function manage_fav_rest_route()
{
// Path to ajax
register_rest_route(
'fav_ajax/v1',
'/manage_fav/',
array(
'methods' => WP_REST_SERVER::READABLE,
'callback' => 'handle_rest_call'
)
);
}
function handle_rest_call()
{
$the_boutique = $_GET['boutiqueId'];
$the_action = $_GET['action'];
if ('check-fav' == $the_action)
{
return $the_boutique;
}
}
I had to create an event with the function inside.
$fav.ready(function( event ) {
console.log( "event ready!" );
// Validate user is logged in
if( isLoggedIn) {
checkFav( boutiqueId );
}
});
function checkFav( theBoutique ) {
console.log( "function ready!" );
$.ajax({
type: 'GET',
data: {
action : 'check-fav',
boutiqueId : theBoutique
},
url: '/wp-json/fav_ajax/v1/manage_fav/'
Related
I tried to update the data with ajax on php but it went wrong while ajax information has been successful but the data is not updated, I think the script is correct but do not want to update the data, what is wrong with my script ??
<input type="hidden" id="select_id" name="select_id" value="<?php echo $read_inbox['id_data']; ?>" />
$('[id^=delete_read_inbox]').click(function() {
if (confirm('You are sure to delete this message?')) {
var id = $("#select_id").val();
var url = base_url+'message/delete_inbox_read';
$.ajax({
url : url,
type: 'POST',
data: 'select_id='+id,
success: function(response) {
console.log('success');
},
error: function (request, jqXHR, textStatus, errorThrown) {
console.log(request.responseText);
}
});
} else {
}
});
Controllers
function delete_inbox_read() {
$this->Message->delete_ReadInbox();
redirect('user/message/inbox');
}
Models
function delete_ReadInbox() {
$update = $this->input->post('select_id');
$data = array(
'delete_pa_inbox' => 0
);
$this->db->where('id_Message', $update);
$this->db->update('tb_message', $data);
}
you are trying to POST 'id' from js and fetching 'select_id' on PHP side, hence its not working, change to:
...
var id = $("#select_id").val();
var url = base_url+'message/delete_inbox_read';
$.ajax({
url : url,
type: 'POST',
data: { 'id' : id },
success: function(response) {
console.log('success');
},
....
Controller:
function delete_inbox_read() {
//get the POST data
$select_id = $this->input->post('id'); //id not select_id
$this->Message->delete_ReadInbox($select_id);
//redirect('user/message/inbox'); //remove redirect
echo "done";
}
Model:
function delete_ReadInbox($select_id) {
$data = array(
'delete_pa_inbox' => 0
);
$this->db->where('id_Message', $select_id);
$this->db->update('tb_message', $data);
}
I am trying to display select 2 search ajax results with groups. But it doesn't display any results. I am using WordPress Ajax for this.
Here is my JS code ,
jQuery('select.select2-group_filters-dropdown').select2({
//placeholder: "Select pages / post / categories",
ajax: {
url: ajaxurl,
dataType: 'json',
method: 'post',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page,
action: 'cp_get_posts_by_query'
};
},
results: function (data, page) {
return {results: data};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
minimumInputLength: 0,
});
data I am returning from PHP as,
$searchString = $_POST['q'];
$childdata = array();
$query = new WP_Query( array( 's' => $searchString ) );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$title = get_the_title();
$ID = get_the_id();
$childdata[] = array('id' => "post-".$ID, 'text' => $title );
}
} else {
$data[] = array('id' => '0', 'text' => 'No results Found');
}
$data = array(
"text" => "posts",
"children" => $childdata
);
wp_reset_postdata();
// return the result in json
echo json_encode( $data );
die();
This is not running as expected. It returns zero results. Please help me with this.
If you are getting the data from the back end then the problem is in select2 configuration.
Try to make ajax call first and then populate select2 with data. Somethong like this (not sure that will work for you, I cannot test it here):
jQuery.ajax({
url: ajaxurl,
dataType: 'json',
method: 'post',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page,
action: 'cp_get_posts_by_query'
}
}
}).done(function( data ) {
jQuery('select.select2-group_filters-dropdown').select2({ data:data, minimumInputLength: 0});
});
$('.select2').select2({
allowClear: true,
ajax: {
url: function (params) {
return "api/endpoint/?user=" + params.term;
},
dataType: 'json',
delay: 500,
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
/* NOTE: return in this format i.e.
* key = **text** : value = username
* key = **id** : value = id
*/
text: item.username,
id: item.id
}
})
};
},
minimumInputLength: 1,
minimumInputLength: 3,
cache: true,
escapeMarkup: function (markup) {
return markup;
},
templateResult: function (item) {
return item.username;
},
templateSelection: function (item) {
return item.username;
},
}
});
AJAX Post is not returning success call in wordpress. I have the following code and I can get to the first dialog box in testing, but no mater what I do its not getting to the second. It's not finding the function in functions.php even though I have it declared.
jQuery(document).ready(function(){
jQuery("#send_btn").click(function(){
var datastring = $("#redemmpointsForm").serialize();
var points = $('#points').val();
var comments = $('#comments').val();
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {"action": "redeempoints", "points":points},
success: function(response) {
if(response.type == "success") {
alert('do i get here');
}
else {
// Do something else
}
}
});
});
}); //Modal event Ends
functions.php file
wp_localize_script( 'inkthemes', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php')));
function functionRedeempoints() {
die();
return true;
}
add_action("wp_ajax_functionRedeempoints", "functionRedeempoints");
add_action("wp_ajax_nopriv_functionRedeempoints", "functionRedeempoints");
Ok so i treid the following
jQuery(document).ready(function(){
jQuery("#send_btn").click(function(){
var points = jQuery('#points').val();
var comments = jQuery('#comments').val();
var allData = {
action: 'functionRedeempoints',
points: points,
comments:comments
}
var data = JSON.stringify(allData);
alert( data);
jQuery.ajax({
type : "post",
dataType : 'json',
url : myAjax.ajaxurl,
data : data,
success: function(response) {
if(response.success) {
alert('do i get here');
}
else {
// Do something else
}
}
});
});
}); //Modal event Ends
And iN MY FUCNTIONS php Its like its not fidning the php function.
wp_localize_script( 'inkthemes', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php')));
function functionRedeempoints() {
wp_send_json_success(true);
}
add_action("wp_ajax_redeempoints", "functionRedeempoints");
add_action("wp_ajax_nopriv_redeempoints", "functionRedeempoints");
The problem is that your function functionRedeempoints does not return anything that the ajax call can handle.
It just dies even before the return statement.
Also a return by the PHP end will never actually be interpreted by the JS. JS can only read from the http request, so you need to actually write to it by an echo statement.
Wordpress provides a convenient way of handling this for you:
What you need would be something like:
function functionRedeempoints() {
wp_send_json_success(true);
}
This already takes care of stopping execution and properly JSON encoding your response.
Also the correct response handling on the JS side is a little different than in your example code.
You can find the details on this here:
https://codex.wordpress.org/Function_Reference/wp_send_json_success
But what it boils down to is that the success is encoded in the result.success property of the response.
Hence you want your check to be
if(response.success)
instead of if(response.type == "success")
With these changes your example should work though :)
Working example ( in plugin form) based on your code:
Put this in hello.php in the plugins folder
<?php
/*
Plugin Name: Ajax demo
*/
function test_load_js() {
wp_register_script( 'ajax_demo', plugins_url( 'hello.js' ), array( 'jquery' ) );
wp_localize_script( 'ajax_demo', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'ajax_demo' );
}
function functionRedeempoints() {
wp_send_json_success( true );
}
add_action( "wp_ajax_functionRedeempoints", "functionRedeempoints" );
add_action( "wp_ajax_nopriv_functionRedeempoints", "functionRedeempoints" );
add_action( "init", "test_load_js" );
if ( ! defined( 'DOING_AJAX' ) ) {
echo '<input type=button value="send" id="send_btn">';
}
Put this in hello.js in the plugins folder
jQuery(document).ready(function () {
jQuery("#send_btn").click(function () {
var points = jQuery('#points').val();
var comments = jQuery('#comments').val();
var data = {
action: 'functionRedeempoints',
points: points,
comments: comments
};
alert(JSON.stringify(data));
jQuery.ajax({
type: "post",
dataType: 'json',
url: MyAjax.ajaxurl,
data: data,
success: function (response) {
if (response.success) {
alert('do i get here');
}
else {
// Do something else
}
}
});
});
});
Hope this helps you to get a start here, works just fine when you click the button that should appear on the upper left of your admin screen ( zoom in ;) )
i am new to cakephp and trying to send data from ajax to my controller action..
i have a popup model in which there is a input box ..i want to grab that value and send to controller without page refresh
here is my code ..
<a class="button anthracite-gradient" onclick="openPrompt()">submit </a>
my javascript
function openPrompt()
{
var cancelled = true;
$.modal.prompt('Please enter a value:', function(value)
{
$.ajax({
type:"POST",
url:"/cakephp/controller/action/",
success : function(data) {
alert(value); //value right now is in this variable ... i want to send this variable value to the controller
},
error : function() {
alert("false");
}
});
}, function()
{
});
};
</script>
myController
public function action(){
if( $this->request->is('ajax') ) {
$new = $this->request->data;
echo "ok"
return;
}
}
i want to first get the value here and then send the response to may ajax request
Its simple post the value to the controller and do what you want , in ajax request bind the value in data:{value_to_send:value} and get in controller
function openPrompt()
{
var cancelled = true;
$.modal.prompt('Please enter a value:', function(value)
{
$.ajax({
type:"POST",
data:{value_to_send:value},
url:"/cakephp/controller/action/",
success : function(data) {
alert(data);// will alert "ok"
},
error : function() {
alert("false");
}
});
}, function()
{
});
};
</script>
public function action(){
if( $this->request->is('ajax') ) {
// echo $_POST['value_to_send'];
echo $value = $this->request->data('value_to_send');
//or debug($this->request->data);
echo "ok"
die();
}
}
For more see accessing-post-data
I will give you some example. In my case, list out book list as a smart search while typing on text box.
$( ".selectBook" ).each(function(){
$(this).keyup(function( event ) {
var tri = $(this).val();
var oPrnt = $(this).parents('.smartsearch');
var str = '';
if(tri.length > 2){
$.ajax({
type: "POST",
url: "/utility/getbooks/",
data: JSON.stringify({string: tri, activeonly:false}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data, function(key, val) {
str += '<li id="a'+key+'" term="'+val+'" data-did="'+key+'">'+val+'</li>';
});
oPrnt.find("ul.result").html(str);
},
error: function (errormessage) {
oPrnt.find("ul.result").html('<li><b>No Results</b></li>');
}
});
oPrnt.find("ul.result").slideDown(100);
}
});
});
And in the controller, action (getbooks Action in UtilityController in my case)
public function getbooks($string = '', $activeonly = true){
$this->autoRender = false;
if( $this->request->is('ajax') ) {
$data = $this->request->input('json_decode');
$string = $data->string;
$activeonly = $data->activeonly;
}
$aReturn = array();
// ... fetch books data from DB goes here...
$aResult = $this->Book->fetch('list');
foreach($aResult as $r){
if(isset($r['bookname'])){
$aReturn[$r['id']] = $r['bookname'];
}
}
return json_encode($aReturn);
}
jQuery(function ($) {
/* fetch elements and stop form event */
$("form.follow-form").submit(function (e) {
/* stop event */
e.preventDefault();
/* "on request" */
$(this).find('i').addClass('active');
/* send ajax request */
$.post('listen.php', {
followID: $(this).find('input').val()
}, function () {
/* find and hide button, create element */
$(e.currentTarget)
.find('button').hide()
.after('<span class="following"><span></span>Following!</span>');
});
});
});
i want to know what when i process the mysql query in the listen.php file, how deos it get the success message back, and then perform the change after?
UPDATE
PHP code:
<?php
if ( $_POST['action'] == 'follow' ) {
$json = '';
if ( $_POST['fid'] == "2" ) {
$json = array( array( "id" => 1 , "name" => "luca" ),
array( "id" => 2 , "name" => "marco" )
);
}
echo json_encode($json);
}
?>
jQuery code:
$.ajax({
type: 'POST',
url: 'listen.php',
data: 'action=follow&fid=' + 2, //$(this).find('input').val(),
success: function(data) {
var obj = $.parseJSON(data);
for ( var i = 0; i < obj.length; i++ ) {
alert( obj[i].id + ' ' + obj[i].name )
}
},
complete: function(data) {
//alert(data.responseText);
},
error: function(data) {
alert(data);
}
});
it's XMLHTTP Object that is responsible behind the scene.
your php script should output text... so lets say the query works output "YES" if it doesn't output "NO" then use this function in your $.post():
function (data) {
if(data=="YES"){
// worked
}
else{
// didn't work
}
}