how do I use jQuery.load() in wordpress

I want to use .load() within enquire.js to load some html into a div, however I'm not sure ajax call syntax?

  • salsasteve

    Hi Michael,

    Here is the enquire.js config code I want to utilise:

    $( document ).ready(function() {
        var partial;
        enquire.register("screen and (min-width:770px)", {
            // OPTIONAL
            // If supplied, triggered when a media query matches.
            match : function() {
    
                // show banner
    
            },      
    
            // OPTIONAL
            // If supplied, triggered when the media query transitions
            // *from a matched state to an unmatched state*.
            unmatch : function() {
    
                // hide banner
            },    
    
            // OPTIONAL
            // If supplied, triggered once, when the handler is registered.
            setup : function() {
    
                // load banner content in via AJAX.
    
            },    
    
            // OPTIONAL, defaults to false
            // If set to true, defers execution of the setup function
            // until the first time the media query is matched
            deferSetup : true,
    
        }, true); // note the <code>true</code>  it signifies to enquire that if the browser is incapable of understanding CSS3 media queries, then always consider this query a match.
    });

    All the tutorials I've found go through wp_localize_script and $.ajax loading json objects. I think I just need to load html via .load() but I'm not sure of the syntax?
    So I've joined wpmudev in the hope that you can help?

    Steve.

  • salsasteve

    OK, I've made some progress. I've got the following code working to an extent.

    jQuery(function($) {
    // DOM ready function that sets the value of $ locally in the function scope, that way you can always use $
        enquire.register("screen and (min-width:770px)", {
            // OPTIONAL, defaults to false
            // If set to true, defers execution of the setup function
            // until the first time the media query is matched
            deferSetup : true,
    
            // OPTIONAL
            // If supplied, triggered once, when the handler is registered.
            setup : function() {
                $(".large-logo").load("wp-content/themes/labzip-video-membership/header-partial.php");
            }, 
    
            // OPTIONAL
            // If supplied, triggered when a media query matches.
            match : function() {
                $(".large-logo").show();
            },      
    
            // OPTIONAL
            // If supplied, triggered when the media query transitions
            // *from a matched state to an unmatched state*.
            unmatch : function() {
                $(".large-logo").hide();
            },    
    
        }, true); // note the <code>true</code>  it signifies to enquire that if the browser is incapable of understanding CSS3 media queries, then always consider this query a match.
    });

    However, not all contents of the header-partial.php from the .load() call appear in the DOM?

    Here is content from the header-partial.php:

    <div class="large-logo-container">
    	<img src="<?php echo get_stylesheet_directory_uri() ?>/images/tlc-main-header.png" alt="">
    </div>

    And as you can see here on inspection:
    The img tag and contents are missing from the source?

    Please advise,

    Steve

  • Ash

    Hello @salsasteve

    I hope you are well today.

    This is because when the ajax load is called then get_stylesheet_directory_uri() function is not initialized.

    Are you using any wordpress hook to load the DOM? If the script is called before init hook, then get_stylesheet_directory_uri() function won't return anything.

    How did you include the js? Did you use wp_register_script and wp_enqueue_script?

    http://codex.wordpress.org/Function_Reference/wp_register_script
    http://codex.wordpress.org/Function_Reference/wp_enqueue_script

    Hope it helps :slight_smile: Please feel free to ask more question if you have.

    Cheers
    Ash

  • Ash

    Hello @salsasteve

    Thank you for your patience.

    Would you please send me your ftp details to me so that I can check the issue? Also, include all relevant links and procedure how I can replicate the issue.

    To send me details, please use our contact form: https://premium.wpmudev.org/contact/

    Select: I have a different question
    Subject: Attn-Ash
    Details: Send all required details (admin info and/or ftp details) with a link of this thread, so that I can track.
    Also post a note here once you send the info.

    I will be happy to take a look :slight_smile:

    Cheers
    Ash

  • salsasteve

    Hi Ash,

    I don't mean to be difficult but I'm not confident with giving up ftp access to the server. Would it work for you if I created a clone and gave you admin access to it?

    I'm also not filled with confidence that you need further details on creating the issue in spite of the information I have already supplied?

    Your latest response reads like generically created response from someone that is ignoring the information I have previously supplied and wants me to supply it all over again?

    I apologise if I've got this wrong.

    Have you examined the code supplied in the post on THU DEC 11 2014, 3:24:53 PM for errors in the ajax call?

    Regards,

    Steve.

    Steve.

  • Ash

    Hello @salsasteve

    You don't feel confident to send ftp, this is pretty normal :slight_smile: But we work here in this way. When a member has any issues, and we can't fix over just texting each other, then we ask for login details, login at their site and try to fix it.

    Would it work for you if I created a clone and gave you admin access to it?

    Sure, but I need ftp access to edit the file. You can just create the clone in a temporary folder and give me ftp access for that folder only :slight_smile:slight_frown:

    Your latest response reads like generically created response from someone that is ignoring the information I have previously supplied and wants me to supply it all over again?

    I did read over your answer. But as this is an ajax call, I need to reply based on guessing. I am sorry for any confusion, but this is difficult to suggest in this scenario. You got it right that it is a generically created response, that means we use this many times, rather than typing those texts again and again :slight_smile:

    Anyway, as I said, you can send me clone site access, no problem. But please make sure you include the procedure how can I see the output, page links etc :slight_smile:

    I will definitely take a look.

    Cheers
    Ash

  • Jose

    Hi there @salsasteve,

    I'm one of the second level support guys, Ash asked if I'd take a look to see if there was something I could suggest without him needing access.

    As a side note, asking access is a normal procedure and the aim is to accelerate response times when the issue can't be sorted easily.

    In this case we were able to find the problem by sniffing in your site network requests.
    Due to the complexity of your code, we assumed some basic steps and overlooked a big issue in your approach.

    First, whenever you have an issue with an ajax request, the first step is to check if the url that you are trying to load is working properly.
    If you try to access the same url via browser, the issue will be evident:
    http://webworksouth.net/testbed/vms3/wp-content/themes/labzip-video-membership/header-partial.php

    If you go to 'View page source' you will find the following error:
    <b>Fatal error</b>: Call to undefined function get_stylesheet_directory_uri() in <b>/home/artrageg/public_html/testbed/vms3/wp-content/themes/labzip-video-membership/header-partial.php</b> on line <b>2</b><br />

    This happens because you are trying to load a php file from your theme directly, without initializing wordpress.

    The correct approach here is to create a wp ajax handler to return your theme's dynamic assets.

    It would require something like this in your theme's functions.php:

    add_action( 'wp_ajax_nopriv_theme_header', 'theme_header_callback' );
    
    function theme_header_callback() {
    	echo get_stylesheet_directory_uri() . '/your-file-path';
    	die(); // this is required to terminate immediately and return a proper response
    }

    You may be interested in take a look at this article:
    http://codex.wordpress.org/AJAX_in_Plugins

    Hope this helps.
    Please don't hesitate to ask if you have further questions :slight_smile:

    Cheers,
    Jose

  • salsasteve

    Hi Ash,

    One more thing, would you please try with this:
    <img src="<?php bloginfo('stylesheet_directory') ?>/images/tlc-main-header.png" alt="">

    I tried it and got the same issue as the get_stylesheet function.

    Jose,

    If you go to 'View page source' you will find the following error:
    <b>Fatal error</b>: Call to undefined function get_stylesheet_directory_uri() in <b>/home/artrageg/public_html/testbed/vms3/wp-content/themes/labzip-video-membership/header-partial.php</b> on line <b>2</b>

    I didn't see that error in the 3 browsers I searched with but I don't doubt that it exists. Where in the browser inspector can I see it?

    It would require something like this in your theme's functions.php:
    add_action( 'wp_ajax_nopriv_theme_header', 'theme_header_callback' );

    function theme_header_callback() {
    echo get_stylesheet_directory_uri() . '/your-file-path';
    die(); // this is required to terminate immediately and return a proper response
    }

    I've put it in my functions.php, but I've a feeling something like wp_localize_script is also required with this approach because it has no effect?

    You may be interested in take a look at this article:
    http://codex.wordpress.org/AJAX_in_Plugins

    The problem with the codex and every other article I had already read is that they all use .ajax call rather than a simple .load() call, they all used post (not get) and they all passed a complex json object rather than a php/html file. So I could not adapt it to my scenario. This is why I have purchased a membership here?

    we assumed some basic steps and overlooked a big issue in your approach.

    Can you explain to me why my approach is a big issue, after all, the ajax call and the rendering work perfectly if I put an absolute path in the image elements src attribute(which I have now done for you to see)?

    Regards.

    Steve.

  • Jose

    Hey Steve,

    Can you explain to me why my approach is a big issue, after all, the ajax call and the rendering work perfectly if I put an absolute path in the image elements src attribute(which I have now done for you to see)?

    Your jQuery code is correct, there is no issues on that part. You can use .load(), .ajax(), or .get() and it will work. That is not relevant.
    The problem here is your destination URL. You are trying to load a single template file from your theme directly, without initializing WP, and it is not meant to work on that way. It will work only if you hardcode your code.
    Why? Because the template will try to call a method declared in WP core. In this case the method 'get_stylesheet_directory_uri()'.
    This templates files are meant to be loaded by WP core, when all the core methods are already defined.

    I didn't see that error in the 3 browsers I searched with but I don't doubt that it exists. Where in the browser inspector can I see it?

    Asynchronous calls responses can be seen in the Network traffic panel in chrome inspector, firebug, or similar tools. (See attached image)
    Also, you can see the error by looking into the page source in your browser:
    view-source:http://webworksouth.net/testbed/vms3/wp-content/themes/labzip-video-membership/header-partial.php
    (make sure to prepend the 'view-source' part).

    I've put it in my functions.php, but I've a feeling something like wp_localize_script is also required with this approach because it has no effect?

    Sorry, my snippet above was just a rough draft. It wasn't meant to work, but just to point you in the right direction.

    Here is a code that should work fine for this case. Paste this into your functions.php file:

    function theme_header_callback() {
        ?>
        <div class="large-logo-container">
            <img src="<?php echo get_stylesheet_directory_uri() ?>/images/tlc-main-header.png" alt="">
        </div>
        <?php
        die();
    }
    
    add_action( 'wp_ajax_nopriv_theme_header', 'theme_header_callback' );
    add_action( 'wp_ajax_theme_header', 'theme_header_callback' );

    Then, in your script you will change the destination url to this:

    setup : function() {
                $('.large-logo').load('wp-admin/admin-ajax.php?action=theme_header');
    }

    Please let me know how it works.

    Cheers!
    Jose

  • salsasteve

    Hi Jose,

    I am delighted to report that your code was a complete success! :slight_smile: The great thing about it is that I understand what is going on. Your approach explanation was very informative (This is what needs to be in the wordpress codex) and in my opinion would make the basis of a very useful and valuable article the is missing on the net.

    This was exactly the kind of expert support I was hoping for, worth every penny.

    Thanks very much!

    Steve.

  • Jose

    Hey Steve,

    Hope you are doing fantastic today :slight_smile:

    Try changing this:

    function theme_header_callback() {
        ?>
        <div class="large-logo-container">
            <img src="<?php echo get_stylesheet_directory_uri() ?>/images/tlc-main-header.png" alt="">
        </div>
        <?php
        die();
    }

    Into this:

    function theme_header_callback() {
        include_once(get_template_directory() . '/header-partial.php');
        die();
    }

    Didn't test it on my install, but it should work.

    Please let me know if you find any glitch.

    Cheers,
    Jose

  • salsasteve

    Hi Jose,
    I made the change you suggested but as you can see here:
    It doesn't seem to have even retrieved any part of the file.

    In the meantime I have relocated your 1st solution into a plugin and successfully created a further call from it.

    With the separated out into a plugin I've got a kind of modular structure that I wanted.

    It would be useful though, to know how to pull html in from a php file with ajax as I have not been able to find anything that simply describes just that?

    So I think I will re-resovle this thread and start a new one.

    Thanks Jose

  • Jose

    Steve,

    Just tried my snippet above in my own install and it works just fine. You should made some mistake when replacing the code.

    Let me know if you want me to look further on this.

    It would be useful though, to know how to pull html in from a php file with ajax as I have not been able to find anything that simply describes just that?

    You are already doing it. I don't get the question. Could you please clarify?

    Cheers,
    Jose

  • Jose

    Hey Steve,

    Do I need to change the get_template function to get_stylesheet?

    Yes, if you are using a child theme, then use get_stylesheet_directory(). That would explain why it didn't work for you before. :slight_smile:

    To 'pull html in from an html file', the best approach is to use jQuery.load() exactly like you are doing now.

    If you whant to include a template part into other template before sending it to the browser, you can use include or require PHP statements.

    See more here http://php.net/manual/en/function.include.php.

    You should keep in mind that all the html markup in wordpress is built using PHP. So, If you want to alter your html, mix different parts, etc, the best way to do it is in server side with PHP.

    The jQuery approach is appropiate if you need to load html parts after the page was loaded in the browser. It is meant to load dynamic content without reloading the whole page.

    Hope this answer your question. :slight_smile:

    Don't hesitate to ask if you have further questions. We are here to help.

    Cheers,
    Jose

  • Jose

    Hi Steve,

    No, you don't need to secure your AJAX since this template should be accessible for non-logged users as well.

    If you need to do some secure AJAX call at some point, you only need to remove the public action listener.

    In my code above, we are listening for public and private calls:

    add_action( 'wp_ajax_nopriv_theme_header', 'theme_header_callback' );//This will work for non-logged users
    add_action( 'wp_ajax_theme_header', 'theme_header_callback' );//This will work for logged user only

    If you want a secure ajax, use just add_action( 'wp_ajax_{your_action_name}',
    if it is public use add_action( 'wp_ajax_nopriv{your_action_name}'

    That simple it is :slight_smile:

    Cheers,
    Jose

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.