Ajax ResponseText is getting true but can't write to div

Issue

Ajax Code:

    jQuery(document).ready( function($) {
    var valueCheck;
    $('#acf-field_5cdc07b87c8f8-field_5cdc08405814f').on( 'change', function () {
         valueSelect = $(this).val();
         if ( parseInt ( valueSelect ) > 0 ) {
        $.ajax( ajaxurl, {
            type: 'POST',
            url: '<?php echo admin_url('admin-ajax.php'); ?>',
            data: { action: 'hesaplama', // The name of the WP action
                    value:  valueSelect,       // the dataVAlues
            },
            dataType: 'json',
            success: function ( response ) {     // to develop in case of success
                             if ( response.success ) {
                                  sonucum = response.html;  // Here we get the results of the PHP remote function
                                  $('#xcvb').html( sonucum );
                             }
                             else {
                                  $('#xcvb').html( '<span>Bu #id: ' +  valueSelect + ' ye ait bir içerik bulunamadı.</span>' );
                             }
                        },
            error: function ( errorThrown ) {   // to develop in case of error
                             console.log( errorThrown ); 
                        }, 
        });
         }
    });
});

Functions.PHP :

function hesaplayici(){
$id    = (int) $_POST['value'];
$sonucum =  the_field('sertifika_aciklamasi', $id);}

Responsetext show on console but can’t write to my div ( id: #xcvb ) Any one can help me about this ?

https://up.uac.ist/images/2019/06/17/Screenshot_2.png
https://up.uac.ist/images/2019/06/17/Screenshot_3.png

Solution

Looks like you have a few things wrong here. This is the proper way to use Ajax with WordPress.

$.ajax({
            type: 'POST',
            url: ajax_object.ajax_url,
            data: {
                action: 'hesaplama',
                value: valueSelect
            }, 
            error: function (data) {
                console.log(data);
            }, 
            success: function (data) {
               
               console.log(data);
               if ( data == '') {
                  $('#xcvb').html( '<span>Bu #id: ' +  valueSelect + ' ye ait bir içerik bulunamadı.</span>' );
               }
               else {
                  $('#xcvb').append( data );
               }

            }
    });

You should try echoing your response.

function hesaplayici(){

$id = $_POST['value'];

$sonucum =  the_field('sertifika_aciklamasi', $id);

echo $sonucum;

die();

}

add_action( 'wp_ajax_send_hesaplayici', 'hesaplayici' );
add_action( 'wp_ajax_nopriv_hesaplayici', 'hesaplayici' );

Answered By – DubVader

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published