0

I have a simple jQuery script in a WordPress plugin that is using a jQuery wrapper:

$("#myForm").submit(function(e){

    e.preventDefault();

    if ($('input[name="username"]').val() == "" || $('input[name="password"]').val() == "") 

        $("#NotesArea").html("Please enter both Username and Passnumber");

    else

        $.post($(this).attr("action"), $(this).serialize())

              .done(function(data)              { $("#NotesArea").html(data); })

              .fail(function(jqXHR, textStatus) {alert( "Request failed: " + textStatus );});

});

I am calling this script from within the WordPress Dashboard and i am getting always this error:

Uncaught TypeError: $ is not a function

Alright, I made it like this, no errors but the code doesn't work!

(function($){
$("#myForm").submit(function(e){

    e.preventDefault();

    if ($('input[name="username"]').val() == "" || $('input[name="password"]').val() == "") 

        $("#NotesArea").html("Please enter both Username and Passnumber");

    else

        $.post($(this).attr("action"), $(this).serialize())

              .done(function(data)              { $("#NotesArea").html(data); })

              .fail(function(jqXHR, textStatus) {alert( "Request failed: " + textStatus );});

});
})(jQuery);
1
  • 1
    it seems like jquery conflicts because of two different version is used. Commented Oct 5, 2016 at 20:05

3 Answers 3

3

Wordpress use noConflict which removes the $ alias

Wrap your code in the following IIFE and you can continue using $ inside it

(function($){
  /* your code*/

})(jQuery);
Sign up to request clarification or add additional context in comments.

4 Comments

I made it like what you have suggested, but it won't work! see y edit plz.
"doesn't work" isn't very informative. Does the submit event get triggered? does that ajax request get made? Need more detail
"ReferenceError: jQuery is not defined" this was the error!
Then either jQuery.js isn't loaded or your script is being included before jQuery.js. Are you using proper wordpress wp_enqueue_script() for this?
2

jQuery is in compatibility mode, use "jQuery" instead of "$".

https://premium.wpmudev.org/blog/adding-jquery-scripts-wordpress/

Comments

1

Make sure you call jquery library BEFORE your script.

1 Comment

'sure' not 'shure'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.