I have a form that submits via jquery ajax to itself. I want to change the error message "#error" display from "none" to "block" if there is an error.

 $username = "username";
 $password = "password";
 if ($_POST['username'] != $username || $_POST['password'] != $password) {
 /*need to make change here*/

/* Log in form*/ /target page after logged in/ and the submit function

<script type="text/javascript">
$(function() {          
            errorPlacement: function(error,element) {
                   return true;

            submitHandler: function(form) {
                return false;

            rules: {
                    username: {
                        required: true
                    password: {
                        required: true

In essence the log in form is first displayed, if you log in correctly it shows the content. if you hit submit with nothing in the fields, the text inputs receive the error class - that part works. But if you submit a blank or incorrect form, the form just clears. I tried echo'ing "Error" in the first part if it's incorrect then using a success handler based on the returned value - and changing the disply - but when i add echo "Error"; it just prints "Error" on the top of the page.


Accepted Answer

In your PHP code, set a variable like this:

$state = 'block';
        var state = "<?=$state?>";

Basically, you output a PHP variable to your file, and then use a global javascript variable to hold the value of that variable. In your Jquery code, you'll be able to read this variable.

I use a more modularized version of this in my framework where my render engine is able to control which CSS or JS file to load. There's also a global javascript object generated by my script that holds all global data like base url, server time zone, sync data, and so forth that is to be reused in all client side scripts.

Hope this helps.


Here's how it works:

// In your html file 
<script>var a = '<?=$state?>';</script> <-- set the global var here
<script src="js/bar.js"></script>       <-- include your scripts after the global one


// In your bar.js file 
alert(a)  // should show the contents of $state stored in the global var a
Written by Ruben Tan
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki