myfile.php
header('Content-type: application/json');
echo json_encode( array( 'error' => 'jkfshdkfj hskjdfh skld hf.' ) );
the above code works.
but when I alter it it stops working:
if( isset( $_GET['customerID'] ) ){
// do something else error
} else {
header('Content-type: application/json');
echo json_encode( array( 'error' => 'jkfshdkfj hskjdfh skld hf.' ) );
}
both outputs are correct:
{"error":"jkfshdkfj hskjdfh skld hf."}
but I get an ajax error:
myfile.phtml
<?php
if( isset( $_GET['custID'] ) )
echo "var custID = " . htmlentities( $_GET['custID'] ) . ";";
else
echo "var custID = null;";
?>
$.ajax({
url: 'php/viewCustomer.php',
type: 'GET',
data: {customerID: custID},
dataType: 'json',
cache: false,
beforeSend: function(){
$('#display').append('<div id="loader"> Lodaing ... </div>');
},
complete: function(){
$('#loader').remove();
},
success: function( data ){
if( data.error ) {
var errorMessage = "";
$.each( data, function( errorIndex, errorValue ){
errorMessage += errorValue + "\n";
});
alert( errorMessage );
} else {
//$('div#customer-content table tr td').eq(0).text( '1234' );
//$('div#customer-content table tr td').eq(1).text( '1234' );
//$('div#customer-content table tr td').eq(2).text( '1234' );
//$('div#customer-content table tr td').eq(3).text( '1234' );
//$('div#customer-content table tr td').eq(4).text( '1234' );
alert( data );
}
},
error: function( jqXHR ){
alert( 'AJAX ERROR' );
}
});
});
From the comments it sounds like you are passing a null customerID and are not expecting it to go into the if condition. But even if the value is null, $_GET['customerID'] is still set. Change the check to empty() instead and it will work as you expect:
if( !empty( $_GET['customerID'] ) ){
....
Related
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');
I compiled my data into JSON via php with 2 parameters response and status. Response has the data which PHP gets when AJAX is processed and status is the error code or success command.
Now, when I pass the data to jQuery, it comes up with weird back and forward slashes, although are don't appear if I console.log(data.response) on AJAX. Please help ..
IMAGE OF OUTPUT
THE JS:
jQuery(document).ready(function($) {
$('.tax-filter').click( function(event) {
// Prevent defualt action - opening tag page
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
// Get tag slug from title attirbute
var selecetd_taxonomy = $(this).attr('title');
$('.tagged-posts').fadeOut();
data = {
action: 'filter_posts',
afp_nonce: afp_vars.afp_nonce,
taxonomy: selecetd_taxonomy,
};
$.ajax({
type: 'post',
dataType: 'json',
url: afp_vars.afp_ajax_url,
data: data,
success: function( data, textStatus, XMLHttpRequest ) {
$('.tagged-posts').html( data.response );
$('.tagged-posts').fadeIn();
/*console.log( data );
console.log( XMLHttpRequest );*/
},
error: function( MLHttpRequest, textStatus, errorThrown ) {
/*console.log( MLHttpRequest );
console.log( textStatus );
console.log( errorThrown );*/
$('.tagged-posts').html( 'No posts found' );
$('.tagged-posts').fadeIn();
}
})
});
});
THE PHP (WP)
// Script for getting posts
function ajax_filter_get_posts( $taxonomy ) {
// Verify nonce
if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce( $_POST['afp_nonce'], 'afp_nonce' ) )
die('Permission denied');
$taxonomy = $_POST['taxonomy'];
wp_reset_postdata();
// WP Query
$args = array(
'post_type' => 'std9_photographs',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'std9_photograph_cat',
'field' => 'slug',
'terms' => $taxonomy,
),
),
);
// If taxonomy is not set, remove key from array and get all posts
if( !$taxonomy ) {
unset( $args['tag'] );
}
$query = new WP_Query( $args );
$result = '';
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();
$result['response'][] = '<h2>'. get_the_title().' </h2>';
$result['status'] = 'success';
endwhile; else:
$result['response'] = '<h2>No posts found</h2>';
$result['status'] = '404';
endif;
$result = json_encode($result);
echo $result;
die();
}
add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts');
add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts');
JSON will add slashes when needed (so don't worry about that). The problem is that jQuery has problem to parse that data. You are probably facing a problem encoding your response.
Edit: In order to avoid your backslashes try encoding with the following command json_encode($str, JSON_UNESCAPED_SLASHES);
The reason that you are having this forward and back slashes is because you are adding in your response html code with </h2> </a> etc.
First of all make sure your header is: header('Content-Type: application/json');
Secondly, do a JSON.parse() in your javascript to parse response into json object.
So i'm trying to make a follow button in wp, and for some reason the ajax button isn't working right.
Here are the steps of what's supposed to happen
user clicks #followbtn
Ajax goes to $_POST action that = follow
php runs wp_set_object_terms( $user_id, $author_id, 'follow', true );
when that's done the function echo's "ok"
if the data = ok reload the page
For some reason the php isn't executing and the page isn't being reloaded.
add_action( 'wp_ajax_nopriv_jk-author-follow', 'jk_author_follow' );
add_action( 'wp_ajax_jk-author-follow', 'jk_author_follow' );
function jk_author_follow() {
$nonce = $_POST['nonce'];
if ( ! wp_verify_nonce( $nonce, 'ajax-nonce' ) )
die ( 'Nope!' );
if($_POST['action'] == "follow") {
$author_id = get_the_author_meta( 'nickname' ); // get authors name
$termId = get_term_by( 'slug', $author_id, 'follow' ); // get the term id from author
$termId = $termId->term_id;
$followers = get_objects_in_term( $termId, 'follow' ); // count followers in author term
$author_follow_count = count( $followers );
if ( is_user_logged_in() ) { // user is logged in
$user_id = get_current_user_id(); // current user
wp_set_object_terms( $user_id, $author_id, 'follow', true ); // Follow the author
echo "ok";
}
}
}
exit;
}
Front end button
function getAuthorFollowLink( $author_id ) {
$author = get_the_author_meta( 'nickname' );
$user_ID = get_current_user_id();
$termId = get_term_by( 'slug', $author, 'follow' ); // get the term id from author
$termId = $termId->term_id;
$followers = get_objects_in_term( $termId, 'follow' ); // count followers in author term
$count = count( $followers );
$output = 'Folllow '.$count.'';
return $output;
}
js
$(function(){
$('#followbtn').on('click', function(e){
e.preventDefault();
$('#followbtn').fadeOut(300);
$.ajax({
url: ajax_var.url,
type: 'post',
data: {'action': 'follow'},
success: function(data, status) {
if(data == "ok") {
location.reload();
}
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // end ajax call
});
});
Try disabling this code
if ( ! wp_verify_nonce( $nonce, 'ajax-nonce' ) )
die ( 'Nope!' );
If You know the implications. You might want to learn more https://codex.wordpress.org/Function_Reference/wp_verify_nonce
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.