skip to Main Content

The most frustrating thing is that this code was working then suddenly it startet returning an entire page of HTML rather than just the HTML code from the template below.

I’m calling an ajax function and passing it an object that looks like this (result of console.log(data)):

Screenshot of console.log(data)

Here is my ajax function:

function mapResults (data) {

        //console.log(data);

        $.ajax({
            type: 'post',
            url: wp_ajax.wp_url,
            data: {action: 'marker_in_viewport', resultsArray: data},
            success: function(result) {
                $('#map-results').html(result);
            },
            error: function(result) {
                console.warn(result);
            }
        });

    }

Here is the PHP code that handles the request:

<?php
add_action( 'wp_ajax_nopriv_marker_in_viewport', 'marker_in_viewport');
add_action( 'wp_ajax_marker_in_viewport', 'marker_in_viewport');

function marker_in_viewport() {

    $locationResults = $_POST['resultsArray'];

      $posts = get_posts(array(
        'post_type' => 'accommodation',
        'post__in' => $locationResults,
        
    ));  

    ?>

    <?php

        //require result template
        //require_once ('map-results.php');

        if( $posts ) { ?>     
            
            <?php foreach( $posts as $post ) {
        
                            $id = $post->ID;
                            $title = get_the_title($id);
                            $location = get_field('location', $id);
                            $permalink = get_permalink( $id );
                            $rooms_available_from = get_field('rooms_available_from', $id);
                            $gallery = get_field('gallery', $id);
        
                            ?>
        
                            <div class="col-md-4 accom-results-cont pb-3">
        
                            <?php if ($gallery) : ?>
        
                                <a href="<?= $permalink; ?>" title="Learn more about <?= $title; ?>">
        
                                    <div class="accom-results-img-cont">
                                
                                        <img class="img-fluid" src="<?= $gallery['url']; ?>" alt="An image of <?= $title; ?>" >
        
                                    </div>
        
                                
        
                            <?php endif; ?>
        
                                
        
                                    <div class="accom-results-data-cont pr-3 pt-3">
        
                                        <?php if ( $title ) : ?>
        
                                            <p class="results-title"><b><?= $title ?></b></p>
        
                                        <?php endif; ?>
        
                                       
        
                                        
        
                                    </div>
                            
                                </a>
                            
                            </div>
        
                        <?php } ?>
        
        <?php } ?>    

<?php wp_die(); ?>

<?php } ?>

And in my page template I have the following div where I want the results to be populated:

<div id="map-results"class="row py-5"></div>

Any ideas what I have done wrong?

3

Answers


  1. Chosen as BEST ANSWER

    Finally got this working after about a week of trying!!

    Here is my AJAX Function inside js/script.js

     $.ajax({
                type: 'post',
                //dataType: 'json',
                url: map_ajax_obj.ajaxurl,
                data: {action: 'marker_in_viewport', resultsArray: data, nonce: map_ajax_obj.nonce},
                success: function(result) {
                    //console.log(result);
                    $('#map-results').html(result);
                },
                error: function(result) {
                    console.warn(result);
                }
            });
    

    Inside my functions.php file I have enqueued and localised my wp-admin.php like this

        function load_req_scripts()
        {
            wp_register_script( 'custom-js-script', get_template_directory_uri() . '/js/script.js', array( 'jquery'), '', true);
            wp_enqueue_script( 'custom-js-script' );
        
            wp_localize_script(
                'custom-js-script', //I think this is a dependancy on the above script though not entirely sure
                'map_ajax_obj',
                array (
                   
                    'ajaxurl' => admin_url('admin-ajax.php'), 
                    'nonce'  => wp_create_nonce('ajax_nonce')
                )
            );
        }
        add_action( 'wp_enqueue_scripts', 'load_req_scripts' );
    
    require_once('ajax/accommodation-ajax.php'); //where to handle and return the data to the ajax call
    

    here is the function in my accommodation-ajax.php file

    <?php
    
    function marker_in_viewport() {
    
        $locationResults = $_POST['resultsArray'];
    
        if (!empty($locationResults)) {
    
        $posts = get_posts(array(
            'post_type' => 'accommodation',
            'post__in'  => $locationResults    
        ));
    
        if( $posts ) {  
            
            foreach( $posts as $post ) {
    
            $id        = $post->ID;
            $title     = get_the_title($id);
            $location  = get_field('location', $id);
            $permalink = get_permalink( $id );
            $gallery   = get_field('gallery', $id);
            $rooms_available_from = get_field('rooms_available_from', $id);
            ?>
            <div class="col-md-4 accom-results-cont pb-3">
                <a href="<?php echo $permalink; ?>" title="Learn more about <?php echo $title; ?>">
                    <?php if ( $gallery ) : ?>
                        <div class="accom-results-img-cont">
                            <img class="img-fluid" src="<?php echo $gallery['url']; ?>" alt="An image of <?php echo $title; ?>" >
                        </div>
                    <?php endif; ?>
                    <div class="accom-results-data-cont pr-3 pt-3">
                        <?php if ( $title ) : ?>
                            <p class="results-title"><b><?php echo $title; ?></b></p>
                        <?php endif; ?>
                    </div>
                </a>
            </div>
        <?php } //end for each 
        
        } //end if posts
    
        } //end if not empty
    
        else {
    
            echo "No results found please search again!";
    
        }
    
        wp_die();
    }
    
    add_action( 'wp_ajax_nopriv_marker_in_viewport', 'marker_in_viewport');
    add_action( 'wp_ajax_marker_in_viewport', 'marker_in_viewport');
    

    As to why this now works compared to what I posted above I have no idea!! Could it be the NONCE? though I'm not using it to authenticate in the PHP function. Anyway hope this helps someone or my future self next time I'm banging my head against the wall with wordpress ajax calls.

    UPDATE So this stopped working for me again then I realised that it was working when logged in as admin and not workign for logged out and all other users. Because this is a membership site I wanted to block anyone that wasn't an admin form the admin area. Didn't realise that this function was also blocking access to the admin-ajax.php file too. This was redirecting to the Homepage hence why the AJAX call was returning the entire page HTML.

    SO I needed to update my function to include:

    && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX )
    

    to the following:

    //block users from admin if not admin
    function blockusers_wps_init() {
            if ( is_admin() && ! current_user_can( 'administrator' ) && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) ) {
                    wp_redirect( home_url() );
                    exit;
            }
    }
    
    add_action( 'init', 'blockusers_wps_init' );
    

  2. I revised your code. try the below code.

    function mapResults (data) {
    
        $.ajax({
            type: 'post',
            dataType : "json",
            url: wp_ajax.wp_url,
            data: {action: 'marker_in_viewport', resultsArray: data},
            success: function(result) {
                $('#map-results').html(result.data.html);
            },error: function(result) {
                console.warn(result);
            }
        });
    
    }
    

    You can use ob_start() and ob_get_clean().

    add_action( 'wp_ajax_nopriv_marker_in_viewport', 'marker_in_viewport');
    add_action( 'wp_ajax_marker_in_viewport', 'marker_in_viewport');
    
    function marker_in_viewport() {
    
        $locationResults = $_POST['resultsArray'];
    
        $posts = get_posts(array(
            'post_type' => 'accommodation',
            'post__in'  => $locationResults    
        ));  
    
        ob_start();
    
        if( $posts ) {  foreach( $posts as $post ) {
    
            $id        = $post->ID;
            $title     = get_the_title($id);
            $location  = get_field('location', $id);
            $permalink = get_permalink( $id );
            $gallery   = get_field('gallery', $id);
            $rooms_available_from = get_field('rooms_available_from', $id);
            ?>
            <div class="col-md-4 accom-results-cont pb-3">
                <a href="<?php echo $permalink; ?>" title="Learn more about <?php echo $title; ?>">
                    <?php if ( $gallery ) : ?>
                        <div class="accom-results-img-cont">
                            <img class="img-fluid" src="<?php echo $gallery['url']; ?>" alt="An image of <?php echo $title; ?>" >
                        </div>
                    <?php endif; ?>
                    <div class="accom-results-data-cont pr-3 pt-3">
                        <?php if ( $title ) : ?>
                            <p class="results-title"><b><?php echo $title; ?></b></p>
                        <?php endif; ?>
                    </div>
                </a>
            </div>
    
        <?php } } 
    
        $html = ob_get_clean();
    
        wp_send_json_success(array(
            'html' => $html
        ));
        
    }
    

    USEFUL LINKS

    Login or Signup to reply.
  3. Don’t use wp_die() it’s returning html, use just die()

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search