I am trying to count data from custom wordpress database. Mysql Query works fine as I have already tested with default values directly but when sending the data from form to ajax its not sending data in php for the query.

Here is my code in function.php:

function searchdata() {
     $postcode = $_POST['$postcode'];
            global $wpdb;
            $resultdyn =  $wpdb->get_var( "SELECT count(*) FROM wp_cdata WHERE code = '$postcode'" );
            echo "<p>Result: {$resultdyn}</p>";
            echo "Search Results for: $postcode";
            exit();
}
add_action( 'wp_ajax_nopriv_searchdata', 'searchdata');
add_action( 'wp_ajax_searchdata', 'searchdata' );

function add_myjavascript(){  
    wp_register_script( 'globals', get_stylesheet_directory_uri() . "/js/search.js", array( 'jquery' ) ); 
    wp_enqueue_script( 'globals' );
    wp_localize_script( 'globals', 'yes', array( 'ajaxurl' => admin_url( '../../wp-admin/admin-ajax.php' ) ) );
}  
add_action( 'init', 'add_myjavascript' );

Here is my jquery search.js code:

jQuery(document).ready(function() {      
    jQuery("#mysearchform").submit(function(e){
         e.preventDefault();      
                 var sentdata = jQuery(this).serialize();
  // var dataString = 'postcode='+ postcode;
             $('div.cart').append('<span class="loading">LOADING</span>');
        jQuery.post(yes.ajaxurl, {action : 'searchdata'}, {postcode:$("#postcode").val()},
            function( response) {
                  jQuery("#searchresult").html(response);
                $('span.loading').remove();
                return false;
            } 
        );
    }); 
}); 

My search form code:

<form action="" id="mysearchform" method="post">
<div><input name="postcode" id="postcode" size="200" type="text" value="" placeholder="Postcode here *" />
<input id="myformsubmit" name="Submit" type="submit" value="Search" /></div>
</form>
<div id="searchresult"></div>

I don’t know where i am making the mistake anybody can help ?

I am unable to get the postcode values from my search form to POST in function.

Thanks in advance.

Read more here: Ajax not posting form data to query in PHP function


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: