Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP variables in jQuery function not correctly passing

I have a couple of jQuery functions that pass PHP data to the JS function using the wordpress wp_localize_scripts function:

function mb_scripts_settings() {

    // blanks
    $mb_ajax_form_type = $mb_get_page_slug = $mb_redirect = $mb_redirect_time = $mb_form_disable = $mb_array = '';

    // get the form type
    $mb_ajax_form_type      = ( is_front_page() ? 'change'  : 'submit'  );

    // get the page slug from ID
    $mb_get_page_slug       = get_post_field( 'post_name', get_the_ID() );

    // if the page is admin or password
    if( is_page( array('admin', 'pw') ) ) {
        $mb_redirect        = true;
        $mb_redirect_time   = 3000;
        $mb_form_disable    = true;

        if( is_page('admin') ) {
            // generate the url for redirection
            $mb_form_area           = ( ( is_page('admin') && isset($_GET['mbtab']) )   ? $_GET['mbtab']    : null      );
            $mb_form_area_url       = ( empty($mb_form_area)    ? '/' : '/admin/?mbtab=' . $mb_form_area . '&mbform=1'  );
            $mb_form_area_url       = get_home_url( $mb_form_area_url );
        }
    }

    // if the page is front
    if( is_front_page() ) {
        $mb_redirect        = false;
        $mb_redirect_time   = 0;
        $mb_form_disable    = false;
        $mb_get_page_slug   = 'front_page';
        $mb_form_area = $mb_form_area_url = null;
    }

    // build the array
    $mb_array = array(
                $mb_ajax_form_type,
                $mb_get_page_slug,
                $mb_redirect,
                $mb_redirect_time,
                $mb_form_disable
            );

    return $mb_array;
}

Which would output an array with all the needed data for the JS function:

// create the script
$(function() {

    // var
    var mb_form_type        = mb_mbtheme_js[0],
        mb_form_type        = '.' + mb_form_type,
        mb_get_page_slug    = mb_mbtheme_js[1],
        mb_redirect         = mb_mbtheme_js[2],
        mb_redirect_time    = mb_mbtheme_js[3],
        mb_form_disable     = mb_mbtheme_js[4];

    // trigger the ajax on form type
    // $("#mb_ajax_form") + mb_form_type + ( function( mb_ajax_form ) {
    $("#mb_ajax_form").change( function( mb_ajax_form ) {

        // stop the default function of buttons
        mb_ajax_form.preventDefault();

        // do the ajax
        mb_ajax_form_js();

    });

});


// accept the form ID
function mb_ajax_form_js() {

    // get the vriables
    var mb_ajax_form_data   = new FormData( $("#mb_ajax_form")[0] ),
        mb_ajax_form_time   = 60,
        mb_ajax_form_links  = "#mb_ajax_form input, #mb_ajax_form submit, #mb_ajax_form button";


    // do the ajax
    $.ajax({
        method:         "POST",
        data:           mb_ajax_form_data,
        contentType:    false,
        processData:    false,

        // the before send function
        beforeSend: function( before ) {
                        // lock the form input and select
                        $( mb_ajax_form_links ).prop( "disabled", true );
                    },

        // the success function
        success:    function( success ) {
                        // show the response
                        $( "#response" ).show().html( success );

                        // scroll to the top of the container - response divHeight
                        $( "section.mbcontainer" ).animate({
                            scrollTop: $( "#response" ).offset().top
                        }, "slow" );

                        // re-enable the submit button
//                          $( mb_ajax_form_links ).prop( "disabled", false );
                    },

        // the complete function
        complete:   function( complete ) {
                        // if we are seeing the success message
                        if( $( "#response div" ).hasClass( "mbsuccessmessage" ) ) {

                            // the admin or password page conditions
                            if( mb_get_page_slug == 'admin' || mb_get_page_slug == 'pw' ) {
                                // set the redirection
                                setTimeout( function() { window.location.replace( mb_redirect ); }, mb_redirect_time );

                                // what to do with the form
                                $( mb_ajax_form_links ).prop( "disabled", mb_form_disable );

                            }

                            // the front page conditions
                            if(  mb_get_page_slug == 'front_page' ) {
                                // set the redirection
                                setTimeout( function() { $(".mbsuccessmessage").slideUp(); }, mb_redirect_time );
                            }
                        }
                    },

        // the error function
        error:      function( error ) {
                        // log the error
                        console.error( error );
                    }
    });
}

However, it doesn't seem to be working as I thought it would when it wasn't being passed via the array and was all hard coded in. Things like the mb_form_type weren't working until I created a new variable with the '.' + mb_form_type.

Now it is spitting an error on the complete: function but I have also tried setting the if statement to compare as String() == String(mb_get_page_slug) == String('admin') but that didn't work either.

Is there something I am missing in the comparisons?

like image 902
markb Avatar asked Nov 22 '19 04:11

markb


People also ask

How to pass value in function in PHP?

Information can be passed to functions through arguments. An argument is just like a variable. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

What does $$ mean in jQuery?

In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery. A (selector) to "query (or find)" HTML elements.

Which is the right way to declare variable in PHP?

A variable starts with the $ sign, followed by the name of the variable. A variable name must start with a letter or the underscore character. A variable name cannot start with a number. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )


1 Answers

Your issue is one of scope. $(function() {}); creates a closure and you define your vars in that closure. Code outside the closure cant see those variables. To fix this, you have several options, here are 2 that would work:

1) move the variables to outside the closure like this:

// var
var mb_form_type        = mb_mbtheme_js[0],
    mb_form_type        = '.' + mb_form_type,
    mb_get_page_slug    = mb_mbtheme_js[1],
    mb_redirect         = mb_mbtheme_js[2],
    mb_redirect_time    = mb_mbtheme_js[3],
    mb_form_disable     = mb_mbtheme_js[4];


// create the script
$(function() {

    // trigger the ajax on form type
    // $("#mb_ajax_form") + mb_form_type + ( function( mb_ajax_form ) {
    $("#mb_ajax_form").change( function( mb_ajax_form ) {

        // stop the default function of buttons
        mb_ajax_form.preventDefault();

        // do the ajax
        mb_ajax_form_js();

    });

});

// accept the form ID
function mb_ajax_form_js() {
    // your code here...omitted for brevity 
}

2) move your function inside the closure like this (note, anything calling mb_ajax_form_js will also need to be inside the closure):

// create the script
$(function() {

    // var
    var mb_form_type        = mb_mbtheme_js[0],
        mb_form_type        = '.' + mb_form_type,
        mb_get_page_slug    = mb_mbtheme_js[1],
        mb_redirect         = mb_mbtheme_js[2],
        mb_redirect_time    = mb_mbtheme_js[3],
        mb_form_disable     = mb_mbtheme_js[4];

    // trigger the ajax on form type
    // $("#mb_ajax_form") + mb_form_type + ( function( mb_ajax_form ) {
    $("#mb_ajax_form").change( function( mb_ajax_form ) {

        // stop the default function of buttons
        mb_ajax_form.preventDefault();

        // do the ajax
        mb_ajax_form_js();

    });



    // accept the form ID
    function mb_ajax_form_js() {
        // your code here...omitted for brevity 
    }

});

Update:

For accessing the submit and change functions using a string variable (mb_form_type), you'll need to use the "array access syntax" rather than the dot notation you have tried.

As a simple example, this would work (note that mb_form_type doesnt contain the .):

var mb_form_type = 'change';


$("#mb_ajax_form")[mb_form_type]( function( mb_ajax_form ) {
    alert('This will work using array access syntax');
});

here's a working example

like image 117
Wesley Smith Avatar answered Oct 05 '22 23:10

Wesley Smith