Before asking question on SO, I searched a lot about what I needed to make a ajax request with WordPress. All my code and the request is working, but is not doing what I need it to do.
What I need to do is When I click at the buttom on checkout page "Novo Dependente", the information with the values to calculate total must update. "Total" value must be updated with a value which I defined at product post type page on admin panel. This value I already get, but the updating the value is real problem to me.
This is the page that I working.
This is the form, that shows up when i click the button, when i Toogle the checkbox I need to add the second value to the Total, another request with ajax.
And here my code goes
Obs: it's a plugin.
Here is the php code.
public function add_total_value()
{
if (! $_POST['action'] || $_POST['action'] !== 'add_total_value' ) :
echo json_encode(
array(
'status' => 'failed',
'message' => 'erro'
)
);
wp_die();
endif;
$woocommerce;
$quantidadeDependentes = $_POST['quantiaDependentes'];
//$produto_valor = WC()->cart->total;
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item )
{
$product = $cart_item['data'];
$item_id = $cart_item['product_id'];
$endereco_igual = get_post_meta( $item_id, 'adicional_mesmo', true);
$endereco_igual = str_replace(',', '.', $endereco_igual);
$endereco_igual = floatval( filter_var( $endereco_igual, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION ) );
$produtoValor = floatval( get_post_meta( $item_id, '_regular_price', true) );
$valorTotal = $produtoValor + ( $endereco_igual * $quantidadeDependentes );
WC()->cart->total = $valorTotal;
WC()->cart->calculate_totals();
wc_price($valorTotal);
}
echo json_encode(
array(
'status' => 'success',
'valorTotal' => wc_price($valorTotal)
));
wp_die();
}
My Ajax request
function contagemDependentes()
{
$contagem = jQuery('.woocommerce-dependentes-contagem');
var quantiaDependentes = jQuery('.woocommerce-dependentes-card').length;
if ( quantiaDependentes <= 0 ) {
var mensagemNumeroDependentes = 'Nenhum dependente informado';
} else if ( quantiaDependentes === 1 ) {
var mensagemNumeroDependentes = '1 dependente';
} else {
var mensagemNumeroDependentes = quantiaDependentes+' dependentes';
}
jQuery($contagem).html(mensagemNumeroDependentes);
var quantiaDependentes = jQuery('.woocommerce-dependentes-card').length + 1;
var dados = {
action: 'add_total_value',
quantiaDependentes: quantiaDependentes
};
jQuery.ajax({
type: 'POST',
url: custom_values.ajaxurl,
data: dados,
dataType: 'json',
success: function(response)
{
console.log(response);
if (response.status === 'success')
{
console.log(response.status);
console.log(response.valorTotal);
var html = "<tr class='order-total'>";
html += "<th>Total</th>";
html += "<td>";
html += response.valorTotal;
html += "</td>";
html += "</tr>";
jQuery( '.order-total' ).remove();
jQuery( 'tfoot' ).append( html );
jQuery( 'body' ).trigger( 'update_checkout' );
}
}
});
}
before function() in functions.php always must be such code
add_action('wp_ajax_your_function_name', 'your_function_name');
add_action('wp_ajax_nopriv_your_function_name', 'your_function_name');
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
show display nothing from cart menu sidebar when first i click on add to cart.
show display from cart menu sidebar when second i click on add to cart.
URL: https://www.bellastudio.pk/new/products.php?p_slug=olive-green
when i ty to start the add to cart i get this error:
PHP Warning: array_column() expects parameter 1 to be array, null given in
PHP Warning: array_search() expects parameter 2 to be array, null given in
i don't know how to make'it work, some help is appreciated. I'm new with this.
PHP
try {
if(isset($_POST['product_name']))
{
$name = $_POST['product_name'];
}
if(isset($_POST['product_price']))
{
$price = $_POST['product_price'];
}
if(isset($_POST['product_itemno']))
{
$itemno = $_POST['product_itemno'];
}
if(isset($_POST['product_quantity']))
{
$qty = $_POST['product_quantity'];
}
if(isset($_POST['product_color']))
{
$color = $_POST['product_color'];
}
if(isset($_POST['product_size']))
{
$size = $_POST['product_size'];
}
if(isset($_POST['sleeves']))
{
$sleeves = $_POST['sleeves'];
}
if(isset($_POST['neck']))
{
$neck = $_POST['neck'];
}
$stockitemno = $itemno.'-'.$size;
$host = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$host->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $host->prepare( "SELECT * FROM productstock INNER JOIN product ON product.p_id = productstock.pid INNER JOIN productsize ON productsize.sid = productstock.size_id WHERE product.p_itemno = :itemno AND productsize.sname = :size" );
$stmt->bindValue( ':itemno', $itemno );
$stmt->bindValue( ':size', $size );
$stmt->execute();
while ( $row = $stmt->fetch( PDO::FETCH_ASSOC ) ) {
// Current stock quantity
$stockqty = $row[ 'stockqty' ];
// No stock, bail early
if ( !$stockqty ) {
echo '<p>No available stock for that item.</p>';
}
// User didn't provide a quantity value
else if ( !$qty ) {
echo '<p>Please enter a quantity</p>';
}
// Lets add to the cart
else {
// Find product in cart
$cartindex = array_search( $stockitemno, array_column( $_SESSION[ 'cart' ], 'stockitemno' ) );
// Product info
$product = null;
// If already exists in cart
if ( $cartindex !== false ) {
$product = $_SESSION[ 'cart' ][ $cartindex ];
}
// Does not exit in cart, create new product info
else {
$product = [
'name' => $name,
'price' => $price,
'item_no' => $itemno,
'qty' => 0, // Default to none added
'color' => $color,
'size' => $size,
'stockitemno' => $stockitemno,
'sleeves' => $sleeves,
'neck' => $neck,
'stockqty' => $stockqty
];
}
// Track how many items were able to be added to the cart
$totaladded = 0;
// If users full amount is available
if ( ( $product[ 'qty' ] + $qty ) <= $stockqty ) {
$totaladded = $qty;
}
// Else add all available stock
else if ( $stockqty - $product[ 'qty' ] ) {
$totaladded = ( $stockqty - $product[ 'qty' ] );
}
// If we were able to add new items to cart
if ( $totaladded ) {
// Update product new qty
$product[ 'qty' ] += $totaladded;
// Update cart item
if ( $cartindex !== false ) {
$_SESSION[ 'cart' ][ $cartindex ] = $product;
}
// Add new item to cart
else {
$_SESSION[ 'cart' ][] = $product;
}
// Example: 5 item (size) were successfully added to your shopping cart.
printf( '<p><strong>%d</strong> %s (%s)<br>was successfully added to your shopping cart.</p>', $totaladded, $name, $size );
} else {
echo '<p>Not enough stock</p>';
}
}
}
} catch ( PDOException $e ) {
echo 'Error: ' . $e->getMessage();
}
$host = null;
$cart_count = count( $_SESSION[ 'cart' ] );
AJAX
$(document).ready(function()
{
load_cart_data();
function load_cart_data()
{
$.ajax({
url:"asset/includes/fetch_cart1.php",
method:"POST",
success:function(data)
{
$('.cart_details').html(data);
$('.badge1').text(data.total_item);
}
});
}
$(document).on('click','#add_to_cart',function (e) {
var cart_count = $('.navbar-tool-badge').text();
cart_count = parseInt(cart_count);
if($('input[type=radio][name=size]:checked').length == 0)
{
$('.msg').html('Please choose size.');
return false;
} else {
var product_name = $('#hidden-name').val();
var product_price = $('#hidden-price').val();
var product_itemno = $('#itemno').val();
var product_quantity = $('.quantity').val();
var product_color = $('#color').val();
var product_size = $("input[name='size']:checked").val();
var sleeves = $('#sleeves').val();
var neck = $('#neck').val();
e.preventDefault();
$.ajax
({
type: "POST",
url: "asset/includes/insertcart.php",
data:{product_name:product_name, product_price:product_price, product_itemno:product_itemno , product_quantity:product_quantity, product_color:product_color, product_size:product_size, sleeves:sleeves, neck:neck},
cache: false,
success: function(response)
{
load_cart_data();
$("#getCode").html(response);
$("#myModal").modal('show');
// remove cart count
$('.navbar-tool-badge').html(cart_count + 1);
}
});
}
});
$(document).on('click', '.delete', function(){
var item_no = $(this).attr("id");
var cart_count = $('.navbar-tool-badge').text();
cart_count = parseInt(cart_count);
$.ajax({
url:"asset/includes/delete_item.php",
method:"POST",
data:{item_no:item_no},
success:function(data)
{
if(data){
load_cart_data();
$('#cart-popover').popover('hide');
}
// remove cart count
$('.navbar-tool-badge').html(cart_count - 1);
}
})
});
});
at the first attempt, your $_SESSION[ 'cart' ] might be empty and hence you are getting an error. try to validate for empty cart and then do a search like this
if(!empty($_SESSION[ 'cart' ])){
$cartindex = array_search( $stockitemno, array_column( $_SESSION[ 'cart' ], 'stockitemno' ) );
}
Image Issue Example
At the WooCommerce "checkout" page:
I would like to input any number in the "Custom Fee Input"
- then it will be calculated in the "Total price table".
- After placing order the "Custom Fee" will be auto synchronized into the database.
Recommendation: using Plain JavaScript instead of jQuery is highly appreciated.
This is my codes:
html
<label>
Custom Fee
<input id="custom_fee" name="custom_fee" type="number" required>
</label>
Plain JavaScript
var $custom_fee = document.getElementById("custom_fee");
$custom_fee.addEventListener("change", function(){
var data = {
action: 'custom_fee',
security: wc_checkout_params.apply_state_nonce,
custom_fee_cost: $custom_fee.value,
};
var request = new XMLHttpRequest();
request.open('POST', wc_checkout_params.ajax_url, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
var resp = this.response;
console.log(resp);
} else {
var resp = this.response;
console.log(resp);
}
};
request.send(data);
});
function.php
add_action('wp_ajax_custom_fee', 'custom_fee_ajax', 10);
add_action('wp_ajax_nopriv_custom_fee', 'custom_fee_ajax', 10);
function custom_fee_ajax() {
if( ! is_checkout() ) return;
global $wpdb;
if( isset($_POST['custom_fee']) ){
$custom_fee = $_POST['custom_fee'];
WC()->session->set( 'custom_fee', $custom_fee );
echo json_encode( WC()->session->get('custom_fee' ) );
}
die();
}
//________________________________________________________
add_action('woocommerce_cart_calculate_fees', 'custom_fee');
function custom_fee() {
if( ! is_checkout() ) return;
session_start();
global $woocommerce;
if ( !defined( 'DOING_AJAX' ) ) return;
$fee = $_SESSION['custom_fee'];
$woocommerce->cart->add_fee( 'Custom Fee' , $fee, true, '' );
}
NOTE: The above code does not work correctly (bad request 400; php functions); so I would like to have someone help I to solve this issue.
I'm using the starter theme Sage to create a custom Wordpress Theme. I made a very simple infinite scroll system to display every posts. On that point, everything seems to work fine.
Now, I have to display an advertisement block each N posts in the loop. At first sight, it seemed pretty easy, but unfortunately, it was not.
My system works this way :
When the blog page is displayed, the firsts N posts are shown. In that template (Template 1), in the loop, I call a method to check if I have to display an advertisement.
When the user starts to scroll, the next N posts are loaded with AJAX. So, JS calls a Wordpress action which loads the next posts and call the appropriate template (Template 2). In that template, I check again how many posts have passed and if I have to display an advertisement.
Counting informations are stocked in session variables.
The problem is this one :
When the page is loaded, everything is fine. When the infinite scroll operates for the first time, it still fine. But, when the system is called once again, the counting informations stocked in variables session are not good. They take the previous values like if the session variables were not incremented.
At first time, I used some static attributes and a static method but it didn't work. So, I thought it was because the script was not call at once and I used global variables. But it didn't work either.
It seems that the counting works fine but every time the template called by AJAX is loaded, the session variables are reset to their previous values, like if they were late.
Here are the files that I use :
Template 1, it's the index.php of the theme
Template 2, the file called by AJAX
Ajax functions, which contains all the AJAX actions I need in Wordpress
Advertisement Controller, which contains every method relative to the advertisements blocks
A JS file with the different AJAX queries.
Can somebody tell what I am doing wrong? It will be much appreciated.
Please, find my code below:
Template 1
/****************************************/
/********** TEMPLATE 1 - INDEX **********/
/****************************************/
use Roots\Sage\ThemeAdvertisementController;
$AdvertisementController = new ThemeAdvertisementController\AdvertisementController();
$_SESSION['globalCountAds'] = 0;
$_SESSION['globalArrayAds'] = '';
$_SESSION['globalCountPosts'] = 1;
get_template_part('templates/page', 'header');
while (have_posts()) {
the_post();
get_template_part('templates/content', get_post_type() != 'post' ? get_post_type() : get_post_format());
$theLoopAd = $AdvertisementController->getTheLoopAds();
if ( $theLoopAd ) {
echo $theLoopAd;
}
}
Template 2
/**************************************************/
/********** TEMPLATE 2 - CALLDED BY AJAX **********/
/**************************************************/
use Roots\Sage\ThemeAdvertisementController;
$AdvertisementController = new ThemeAdvertisementController\AdvertisementController();
while (have_posts()) {
the_post();
get_template_part( 'templates/content', get_post_type() != 'post' ? get_post_type() : get_post_format() );
$theLoopAd = $AdvertisementController->getTheLoopAds();
if ( $theLoopAd ) {
echo $theLoopAd;
}
}
Advertisement Controller
/**********************************************/
/********** ADVERTISEMENT CONTROLLER **********/
/**********************************************/
namespace Roots\Sage\ThemeAdvertisementController;
use Roots\Sage\ThemeViewController;
use Roots\Sage\ThemePostController;
class AdvertisementController {
public function __construct() {
}
private function getTheAds() {
$PostController = new ThemePostController\PostController();
$postType = 'advertisement';
$nbPosts = -1;
$status = 'publish';
$orderBy = 'title';
$order = 'ASC';
$meta = '';
$taxQuery = '';
$metaQuery = array(
array(
'key' => 'advertisement_in_news',
'value' => true,
'compare' => '='
)
);
return $PostController->getThePosts( $postType, $nbPosts, $status, $orderBy, $order, $meta, $taxQuery, $metaQuery );
}
private function displayTheAd() {
$ViewController = new ThemeViewController\ViewController();
$theAdsArray = $_SESSION['globalArrayAds'];
$theGlobalCountAds = $_SESSION['globalCountAds'];
$thePostID = $theAdsArray->posts[ $theGlobalCountAds ]->ID;
if ( !empty( $thePostID ) ) {
$_SESSION['globalCountAds']++;
$ViewController->postID = $thePostID;
$ViewController->postType = 'advertisement';
$ViewController->nbPosts = 1;
$ViewController->status = 'publish';
$ViewController->orderBy = 'ID';
$ViewController->order = 'ASC';
$ViewController->meta = '';
$ViewController->taxQuery = '';
return $ViewController->displayAdvertisementBlock();
} else {
return false;
}
}
public function getTheLoopAds() {
$arrayAds = $_SESSION['globalArrayAds'];
$adsCount = $_SESSION['globalCountAds'];
$postCount = $_SESSION['globalCountPosts'];
$_SESSION['globalCountPosts']++;
if ( empty( $arrayAds ) ) {
$theAds = $this->getTheAds();
$_SESSION['globalArrayAds'] = $theAds;
}
if ( $postCount%2 == 0 && $postCount != 0 ) {
$displayedAd = $this->displayTheAd();
if ( $displayedAd ) {
return $displayedAd;
} else {
return false;
}
} else {
return false;
}
}
}
Ajax functions
/************************************/
/********** AJAX FUNCTIONS **********/
/************************************/
function infinitePaginateAjax() {
$paged = $_POST['paged'];
$postsPerPage = get_option('posts_per_page');
$args = array( 'paged' => $paged,
'post_status' => 'publish',
'order' => 'DESC',
'post_type' => 'post',
'posts_per_page' => $postsPerPage
);
query_posts( $args );
get_template_part('templates/loop-news');
exit;
}
add_action( 'wp_ajax_infinitePaginateAjax','infinitePaginateAjax' );
add_action( 'wp_ajax_nopriv_infinitePaginateAjax','infinitePaginateAjax' );
function getNbPostsPerPageAjax() {
$value = array();
$nbPostsPerPage = get_option('posts_per_page');
if ( !empty( $nbPostsPerPage ) ) {
$value['answer'] = 1;
$value['value'] = $nbPostsPerPage;
$value['globalCountAds'] = $_SESSION['globalCountAds'];
$value['globalCountPosts'] = $_SESSION['globalCountPosts'];
} else {
$value['answer'] = 0;
$value['value'] = 0;
}
$data = json_encode( $value );
die( $data );
}
add_action( 'wp_ajax_getNbPostsPerPageAjax','getNbPostsPerPageAjax' );
add_action( 'wp_ajax_nopriv_getNbPostsPerPageAjax','getNbPostsPerPageAjax' );
function getTotalPostsAjax() {
global $wp_query;
$value = array();
$nbPosts = wp_count_posts( 'post' );
$nbPublishedPosts = $nbPosts->publish;
if ( !empty( $nbPublishedPosts ) ) {
$value['answer'] = 1;
$value['value'] = $nbPublishedPosts;
$value['globalCountAds'] = $_SESSION['globalCountAds'];
$value['globalCountPosts'] = $_SESSION['globalCountPosts'];
} else {
$value['answer'] = 0;
$value['value'] = 0;
}
$data = json_encode( $value );
die( $data );
}
add_action( 'wp_ajax_getTotalPostsAjax','getTotalPostsAjax' );
add_action( 'wp_ajax_nopriv_getTotalPostsAjax','getTotalPostsAjax' );
JS
jQuery(document).ready(function() {
var pageInfinite = '.infinite-page';
var loaderInfinite = '.infinite-loader';
var contentInfinite = '.main-content';
var getTotalPosts = function() {
var totalPosts = '';
jQuery.ajax({
type : "POST",
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
async: false,
url : data_sage_js.ajaxurl,
data: {
action: 'getTotalPostsAjax'
},
success: function( data ) {
data = jQuery.parseJSON( data );
if ( data.answer !== 0 ) {
totalPosts = data.value;
} else {
totalPosts = 0;
}
},
error: function () {
console.log( 'error: cannot get nb posts' );
totalPosts = 0;
}
});
return totalPosts;
};
var getNbPostsPerPage = function() {
var postsPerPage = '';
jQuery.ajax({
type : "POST",
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
async: false,
url : data_sage_js.ajaxurl,
data: {
action: 'getNbPostsPerPageAjax'
},
success: function( data ) {
data = jQuery.parseJSON( data );
if ( data.answer !== 0 ) {
postsPerPage = data.value;
} else {
postsPerPage = 0;
}
},
error: function () {
console.log( 'error: cannot get max posts page' );
postsPerPage = 0;
}
});
return postsPerPage;
};
var infiniteLoadArticle = function( pageNumber ) {
jQuery( loaderInfinite ).show( 'fast' );
setTimeout(function(){
jQuery.ajax({
type:'POST',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
async: false,
url: data_sage_js.ajaxurl,
data: {
action: 'infinitePaginateAjax',
paged: pageNumber
},
success: function( html ) {
jQuery( loaderInfinite ).hide( 'fast' );
jQuery( contentInfinite ).append( html);
}
});
}, 1000);
return false;
};
if ( jQuery( pageInfinite ).length > 0 ) {
var postsTotal = parseInt( getTotalPosts() );
var incPost = parseInt( getNbPostsPerPage() );
var postsCount = parseInt( incPost );
var nbPage = parseInt( 1 );
var nbTotalPage = parseInt( Math.ceil( postsTotal / incPost ) );
jQuery(window).scroll(function() {
if ( jQuery(window).scrollTop() === jQuery(document).height() - jQuery(window).height() ) {
if ( nbTotalPage > nbPage ) {
nbPage++;
infiniteLoadArticle( nbPage );
postsCount = postsCount + incPost;
} else if ( nbTotalPage <= nbPage ) {
return false;
}
}
});
}
});
EDIT/SOLVE
So, after hours of searching, I decided to do it another way : I decided to use the "posts_per_page" attribute to count posts and to know when I have to display an advertisement. I just had to refactor a few functions and methods.
Do session variables work outside of the Ajax Calls? on page refresh etc.
If they do not then it may be to do with the fact that wordpress can treat session variables very weirdly.
I think its for security but if in your php.ini if 'register_globals' is on it unregisters all of the php globals.
Reference: WP_unregister_GLOBALS
In which case I believe things like https://wordpress.org/plugins/wp-session-manager/ fill in the blanks for this, or you could turn off register_globals in your php.ini (although I dont understand the repercussions of doing that sorry
In 3 different AJAX scripts that I have written the error message is displayed even though the ajax is processes the PHP file updated and all the success statements are executed. Since I only discovered ajax a few days ago. There must be something wrong with my scripts. Perhaps someone could see where I have gone wrong.
AJAX:
function bookingdetails() {
var actdate = $('#actdate').val();
var airport = $('#FLTairport').val();
var number = $('#FLTnumber').val();
var time = $('#FLTtime').val();
var dataString = 'actdate=' + actdate + '&airport=' + airport + '&number=' + number + '&time=' + time;
$.ajax({
type: 'POST',
url: '<?php echo $thisposturl;?>?update',
data: dataString,
beforeSend: function() {
$('#airloader').html('<img id="BKloader" src="http://www.divethegap.com/update/z-images/structure/icons/blockloader.gif" alt="" width="30" height="30"/>');
},
error: function() {
$('#airloader').html('arse up');
},
dataType:'json',
success: function(data) {
$('#actdate').val(data.date);
$('#FLTnumber').val(data.FLTnumber);
$('#airloader').html('marvellous');
$('#FLTairport').val(data.FLTairport);
$('#FLTdate').val(data.FLTdate);
$('#FLTtime').val(data.FLTtime);
$('#datediv').load('<?php echo $thisposturl;?> #datediv');
}
});
}
PHP : (dont worry about the insert post bits)
<?php
function __update_post_meta( $post_id, $field_name, $value = '' )
{
if ( empty( $value ) OR ! $value )
{
delete_post_meta( $post_id, $field_name );
}
elseif ( ! get_post_meta( $post_id, $field_name ) )
{
add_post_meta( $post_id, $field_name, $value );
}
else
{
update_post_meta( $post_id, $field_name, $value );
}
}
if ( is_user_logged_in() ) {
$my_post = array(
'ID' => get_the_ID(),
'post_date' => $_POST['actdate'],
);
$the_post_id = wp_update_post( $my_post );
__update_post_meta( $the_post_id, 'FLTairport', $_POST['airport'] );
__update_post_meta( $the_post_id, 'FLTnumber', $_POST['number'] );
__update_post_meta( $the_post_id, 'FLTtime', $_POST['time'] );
}
$FLTdate = get_the_time('d/m/Y');
$actdate = get_the_time('Y-m-d');
$FLTairport = $_POST['airport'];
$FLTnumber = $_POST['number'];
$FLTtime = $_POST['time'];
echo json_encode( array('FLTdate'=>$FLTdate, 'actdate'=>$actdate, 'FLTairport'=>$FLTairport, 'FLTnumber'=>$FLTnumber, 'FLTtime'=>$FLTtime));
?>
Result all values are updated but it still displays 'arse up' in the #airloader. This is one example I can provide it with 3 out of 4 of the ajax scripts that I have written.
Any ideas?
Marvellous
Have you checked the second parameter to your error function?
See: http://api.jquery.com/jQuery.ajax/
error(jqXHR, textStatus, errorThrown)
..., a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". ...
I am using the following ajax to update information on a page and then resubmit the page into the database. The script is failing each time stopping at the Error parameter. Can anyone see where I have gone wrong.
AJAX -
function bookingdetails() {
var date = <?php the_time('Y-m-d');?>;
var airport = $('#FLTairport').val();
var number = $('#FLTnumber').val();
var time = $('#FLTtime').val();
var dataString = 'date=' + date + '&airport=' + airport + '&number=' + number + '&time=' + time;
$.ajax({
type: 'POST',
url: '<?php echo $thisposturl;?>?update',
data: dataString,
beforeSend: function() {
$('#airloader').html('<img id="BKloader" src="http://www.divethegap.com/update/z-images/structure/icons/blockloader.gif" alt="" width="40" height="30"/>');
},
error: function() {
$('#airloader').html('Failed to update booking, try again');
},
dataType:'json',
success: function(data) {
$('#date').val(data.date);
$('#FLTnumber').val(data.FLTnumber);
$('#airloader').val(data.FLTnumber);
$('#FLTairport').val(data.FLTairport);
$('#FLTdate').val(data.FLTdate);
$('#FLTtime').val(data.FLTtime);
}
});
}
PHP -
<?php
function __update_post_meta( $post_id, $field_name, $value = '' )
{
if ( empty( $value ) OR ! $value )
{
delete_post_meta( $post_id, $field_name );
}
elseif ( ! get_post_meta( $post_id, $field_name ) )
{
add_post_meta( $post_id, $field_name, $value );
}
else
{
update_post_meta( $post_id, $field_name, $value );
}
}
if ( is_user_logged_in() ) {
$my_post = array(
'ID' => get_the_ID(),
'post_date' => $_POST['date'],
);
$the_post_id = wp_update_post( $my_post );
__update_post_meta( $the_post_id, 'FLTairport', $_POST['airport'] );
__update_post_meta( $the_post_id, 'FLTnumber', $_POST['number'] );
__update_post_meta( $the_post_id, 'FLTtime', $_POST['time'] );
}
$FLTdate = get_the_time('d/m/Y');
$date = get_the_time('Y-m-d');
$FLTairport = $_POST['airport'];
$FLTnumber = $_POST['number'];
$FLTtime = $_POST['time'];
echo json_encode( array('FLTdate'=>$FLTdate, 'date'=>$date, 'FLTairport'=>$FLTairport, 'FLTnumber'=>$FLTnumber, 'FLTtime'=>$FLTtime));
?>
Any ideas?
Marvellous
The jQuery Documentation shows 3 arguments that can be used in your error callback, which could be very useful in debugging your error.
From the docs
so with that in mind, try changing your error callback like so...
error: function(xhr,ts,et) {
$('#airloader').html('Failed to update booking.');
$('#airloader').append('Error Text - '+ts);
},
and you should see the specific error, which should put you down the right path to fix it.
Are you able to see what your php script is sending? I would recommend using firebug in firefox to see exactly what is coming back to be consumed by your javascript. I don't see where it is outputting a success parameter for your json.