I couldn’t add selected data to a div using ajax. Here is my code:

<?php
function master_ajaxurl() {
        $myOpt = $_POST['option'];
        bringDetails($myOpt);
 }                     

function bringDetails($opt)
{
        global $wpdb;
        $sql ="SELECT * from mst_urun_liste WHERE kod like '$opt'";
        $rows = $wpdb->get_row($sql );
        return $rows;
}
add_action('wp_ajax_master_ajaxurl', 'master_ajaxurl');
add_action('wp_ajax_nopriv_master_ajaxurl', 'master_ajaxurl');
?>
<script>
$(document).ready(function () {
        var ajaxurl="<?php echo admin_url("admin-ajax.php'); ?>';
    $('#combobox').change(function(){
        $.ajax({
                        url:ajaxurl,
            action:'master_ajaxurl',
            type: "post",
            data: {option: $(this).find("option:selected").val()},
            success: function(data){
                //adds the echoed response to our container

                $("#details").html(data);
            }
        });
    });
});

</script>

I have a selectbox, and want to change values related to selected element, but ajax populates my div with whole html code of site.

And here is a test page I prepared.

I want to populate values from database (Kod, Parça No, Parça Adı, Fiyat, Adet, Tutar) of selected values

I realized that, If i don’t set url:ajaxurl, it returns the whole page, if i use it returns 0

4 Answers
4

    $.post(ajaxurl,{ 
        action:'master_ajaxurl',                
        option: $(this).find("option:selected").val(), // use option also here
       },
       function(data){
         //adds the echoed response to our container
        // alert(data);
        $("#details").html(data);
      }
   );

Move action and functions into function.php file

make some changes as commented

add_action('wp_ajax_master_ajaxurl', 'master_ajaxurl');
add_action('wp_ajax_nopriv_master_ajaxurl', 'master_ajaxurl');

    function master_ajaxurl() {

    $myOpt = $_POST['option']; // use option instead of data
    echo bringDetails($myOpt);
    die();
    }                     

    
    **page.php**    
    
    $(document).ready(function () {
        var ajaxurl="----admin_url----";
        $('#combobox').click(function(){

            $.post(ajaxurl,{                
                action:'master_ajaxurl',
                option: data to send, // key => value
                                option2: 'hello'
            },
                function(data){
                //adds the echoed response to our container
                alert(data);
                //$("#details").html(data);
            }
        );
        });
    });


    **functions.php**
    function master_ajaxurl() {

    $myOpt = $_POST['option'];
    echo bringDetails($myOpt);
    die();
     } 

must use echo and die() in your ajax output function.
this is working for me. Hope this works now.

Leave a Reply

Your email address will not be published. Required fields are marked *