accessing the jquery function after success call? - php

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
}
}

Related

Data variable return as [object Object]

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/'

Delete record from a dynamically created form using ajax and php

I want to delete the records that are dynamically created but the code is not working..Please have a look
script.js
$(function() {
$('#studentRecord').on('click', 'button.delete', function() {
var $tr = $(this).closest('tr');
var $id = parseInt( $(this).attr('id').split('-')[1] );
if ( confirm("Are you sure you want to delete this record") ) {
$.ajax({
url: '/ab_batch/practice/db/action.php',
type: 'POST',
data: {
action: 'ajaxDelRecord',
id: JSON.stringify(id)
},
success: function() {},
error: function() {}
});
}
});
});
action.php
$action = ( isset($_REQUEST['action']) && !empty($_REQUEST['action']) ) ? $_REQUEST['action'] : null;
switch ($action) {
case 'ajaxDelRecord':
if ( isset($_POST['id']) ) {
$id = json_decode($_POST['id']);
}
$id = json_decode($_POST['id']);
print ( $student->delRecord($id) ) ? 'true' : 'false' ;
break;
}
There is another file db.php that contains all the APIs for delete, add and update
JSON.stringify(id) should be JSON.stringify($id) as you are declaring your id as $id , you don't really need : JSON.stringify as you are just sending an integer to the server.
and for deleting the line which you just removed from database , you can just replace your javascript code with following:
$(function() {
$('#studentRecord').on('click', 'button.delete', function() {
var $tr = $(this).closest('tr');
var $id = parseInt( $(this).attr('id').split('-')[1] );
if ( confirm("Are you sure you want to delete this record") ) {
$.ajax({
url: '/ab_batch/practice/db/action.php',
type: 'POST',
data: {
action: 'ajaxDelRecord',
id: JSON.stringify($id)
},
success: function() {},
$tr.remove(); // removing the current deleted record from html.
error: function() {}
});
}
});
});
i did add $tr.remove(); inside a success callback , as you have already declared the parent element of the deleted record , so you just need to use : $tr.remove(); to delete the tr.

Called and canceled of the admin-ajax.php file multiple times

I have an issue in a Wordpress installation with a plugin. There is a calendar which you can click on a day (or a range of days) and from ajax calls through admin-ajax.php it calculates product costs.
The problem is that, when I click on a calendar cell, the admin-ajax.php is called twice. The first time for a few milliseconds and canceled immediately. Then automatically, it calls it once again and get the ajax response. When I click for a second time on a calendar cell, the admin-ajax.php is called 3 times. The first two are canceled and only the last one get a response.
I found that the code that is used for this part is the following. However, I cannot find any issue on it, even if I can see those cancelled calls on Developer console.
$('.wc-bookings-booking-form')
.on('change', 'input, select', function() {
var index = $('.wc-bookings-booking-form').index(this);
if ( xhr[index] ) {
xhr[index].abort();
}
$form = $(this).closest('form');
var required_fields = $form.find('input.required_for_calculation');
var filled = true;
$.each( required_fields, function( index, field ) {
var value = $(field).val();
if ( ! value ) {
filled = false;
}
});
if ( ! filled ) {
$form.find('.wc-bookings-booking-cost').hide();
return;
}
$form.find('.wc-bookings-booking-cost').block({message: null, overlayCSS: {background: '#fff', backgroundSize: '16px 16px', opacity: 0.6}}).show();
xhr[index] = $.ajax({
type: 'POST',
url: booking_form_params.ajax_url,
data: {
action: 'wc_bookings_calculate_costs',
form: $form.serialize()
},
success: function( code ) {
if ( code.charAt(0) !== '{' ) {
console.log( code );
code = '{' + code.split(/\{(.+)?/)[1];
}
result = $.parseJSON( code );
if ( result.result == 'ERROR' ) {
$form.find('.wc-bookings-booking-cost').html( result.html );
$form.find('.wc-bookings-booking-cost').unblock();
$form.find('.single_add_to_cart_button').addClass('disabled');
} else if ( result.result == 'SUCCESS' ) {
$form.find('.wc-bookings-booking-cost').html( result.html );
$form.find('.wc-bookings-booking-cost').unblock();
$form.find('.single_add_to_cart_button').removeClass('disabled');
} else {
$form.find('.wc-bookings-booking-cost').hide();
$form.find('.single_add_to_cart_button').addClass('disabled');
console.log( code );
}
},
error: function() {
$form.find('.wc-bookings-booking-cost').hide();
$form.find('.single_add_to_cart_button').addClass('disabled');
},
dataType: "html"
});
})
.each(function(){
var button = $(this).closest('form').find('.single_add_to_cart_button');
button.addClass('disabled');
});
And here is a screenshot from the Dev Console:
EDIT: I think I found the problem, but I am not sure. There is also this part of code which was supposed to not used at all. There is a feature for time on calendar, but it isn't activated. So, this code should not be run.
$('.wc-bookings-booking-form').on( 'date-selected', function() {
show_available_time_blocks( this );
});
var xhr;
function show_available_time_blocks( element ) {
var $form = $(element).closest('form');
var block_picker = $form.find('.block-picker');
var fieldset = $form.find('.wc_bookings_field_start_date');
var year = parseInt( fieldset.find( 'input.booking_date_year' ).val(), 10 );
var month = parseInt( fieldset.find( 'input.booking_date_month' ).val(), 10 );
var day = parseInt( fieldset.find( 'input.booking_date_day' ).val(), 10 );
if ( ! year || ! month || ! day ) {
return;
}
// clear blocks
block_picker.closest('div').find('input').val( '' ).change();
block_picker.closest('div').block({message: null, overlayCSS: {background: '#fff', backgroundSize: '16px 16px', opacity: 0.6}}).show();
// Get blocks via ajax
if ( xhr ) xhr.abort();
xhr = $.ajax({
type: 'POST',
url: booking_form_params.ajax_url,
data: {
action: 'wc_bookings_get_blocks',
form: $form.serialize()
},
success: function( code ) {
block_picker.html( code );
resize_blocks();
block_picker.closest('div').unblock();
},
dataType: "html"
});
}

datatables:jQuery loses serialize while posting

Can anybody help me with this? While alerting sData, it contains all the values I need, but when POSTing, it contains only data from current page in datatables.
var oTable;
$(document).ready
(
function()
{
$('#form0').submit
(
function()
{
var sData = $('input', oTable.fnGetNodes()).serialize().replace(/%5B%5D/g, '[]');
alert( "The following data would have been submitted to the server: \n\n"+sData );
$( {
"type": "POST",
"dataType": "html",
"url": $("#form0").attr('action'),
"data": sData,
"success": fnCallback
} );
return false;
}
);
var oTable = $('#gridtable0').dataTable(
{
"sDom": 'T<"clear">lfrtip',
"bSortClasses": false,
"sPaginationType": "full_numbers",
"fnDrawCallback": function ( oSettings )
{
/* Need to redo the counters if filtered or sorted */
if ( oSettings.bSorted || oSettings.bFiltered )
{
for ( var i=0, iLen=oSettings.aiDisplay.length ; i<iLen ; i++ )
{
$('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr ).html( i+1 );
}
}
}
}
);
}
);
Alert: (2 checkboxes checked on 1 and two on second page)
id=2205&id=2204&id=2181&id=2179
POST: (2 checkboxes checked on current page)
id=2181&id=2179
Instead of fnGetNodes, use $
Example:
var sData = $('input', oTable.$('tr')).serialize().replace(/%5B%5D/g, '[]');

sending data via ajax in Cakephp

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

Categories